mark_sweep.cc revision 4b95e8fad803ad307fa09c11c08894544e07a731
1/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "mark_sweep.h"
18
19#include <functional>
20#include <numeric>
21#include <climits>
22#include <vector>
23
24#include "base/logging.h"
25#include "base/macros.h"
26#include "base/mutex-inl.h"
27#include "base/timing_logger.h"
28#include "gc/accounting/card_table-inl.h"
29#include "gc/accounting/heap_bitmap.h"
30#include "gc/accounting/space_bitmap-inl.h"
31#include "gc/heap.h"
32#include "gc/space/image_space.h"
33#include "gc/space/large_object_space.h"
34#include "gc/space/space-inl.h"
35#include "indirect_reference_table.h"
36#include "intern_table.h"
37#include "jni_internal.h"
38#include "monitor.h"
39#include "mark_sweep-inl.h"
40#include "mirror/class-inl.h"
41#include "mirror/class_loader.h"
42#include "mirror/dex_cache.h"
43#include "mirror/field.h"
44#include "mirror/field-inl.h"
45#include "mirror/object-inl.h"
46#include "mirror/object_array.h"
47#include "mirror/object_array-inl.h"
48#include "runtime.h"
49#include "thread-inl.h"
50#include "thread_list.h"
51#include "verifier/method_verifier.h"
52
53using namespace art::mirror;
54
55namespace art {
56namespace gc {
57namespace collector {
58
59// Performance options.
60static const bool kParallelMarkStack = true;
61static const bool kDisableFinger = true; // TODO: Fix, bit rotten.
62static const bool kUseMarkStackPrefetch = true;
63
64// Profiling and information flags.
65static const bool kCountClassesMarked = false;
66static const bool kProfileLargeObjects = false;
67static const bool kMeasureOverhead = false;
68static const bool kCountTasks = false;
69static const bool kCountJavaLangRefs = false;
70
71class SetFingerVisitor {
72 public:
73  SetFingerVisitor(MarkSweep* const mark_sweep) : mark_sweep_(mark_sweep) {
74  }
75
76  void operator ()(void* finger) const {
77    mark_sweep_->SetFinger(reinterpret_cast<Object*>(finger));
78  }
79
80 private:
81  MarkSweep* const mark_sweep_;
82};
83
84void MarkSweep::ImmuneSpace(space::ContinuousSpace* space) {
85  // Bind live to mark bitmap if necessary.
86  if (space->GetLiveBitmap() != space->GetMarkBitmap()) {
87    BindLiveToMarkBitmap(space);
88  }
89
90  // Add the space to the immune region.
91  if (immune_begin_ == NULL) {
92    DCHECK(immune_end_ == NULL);
93    SetImmuneRange(reinterpret_cast<Object*>(space->Begin()),
94                   reinterpret_cast<Object*>(space->End()));
95  } else {
96    const std::vector<space::ContinuousSpace*>& spaces = GetHeap()->GetContinuousSpaces();
97    const space::ContinuousSpace* prev_space = NULL;
98    // Find out if the previous space is immune.
99    // TODO: C++0x
100    typedef std::vector<space::ContinuousSpace*>::const_iterator It;
101    for (It it = spaces.begin(), end = spaces.end(); it != end; ++it) {
102      if (*it == space) {
103        break;
104      }
105      prev_space = *it;
106    }
107
108    // If previous space was immune, then extend the immune region. Relies on continuous spaces
109    // being sorted by Heap::AddContinuousSpace.
110    if (prev_space != NULL &&
111        immune_begin_ <= reinterpret_cast<Object*>(prev_space->Begin()) &&
112        immune_end_ >= reinterpret_cast<Object*>(prev_space->End())) {
113      immune_begin_ = std::min(reinterpret_cast<Object*>(space->Begin()), immune_begin_);
114      immune_end_ = std::max(reinterpret_cast<Object*>(space->End()), immune_end_);
115    }
116  }
117}
118
119void MarkSweep::BindBitmaps() {
120  const std::vector<space::ContinuousSpace*>& spaces = GetHeap()->GetContinuousSpaces();
121  WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
122
123  // Mark all of the spaces we never collect as immune.
124  typedef std::vector<space::ContinuousSpace*>::const_iterator It;
125  for (It it = spaces.begin(), end = spaces.end(); it != end; ++it) {
126    space::ContinuousSpace* space = *it;
127    if (space->GetGcRetentionPolicy() == space::kGcRetentionPolicyNeverCollect) {
128      ImmuneSpace(space);
129    }
130  }
131}
132
133MarkSweep::MarkSweep(Heap* heap, bool is_concurrent, const std::string& name_prefix)
134    : GarbageCollector(heap,
135                       name_prefix + (name_prefix.empty() ? "" : " ") +
136                       (is_concurrent ? "concurrent mark sweep": "mark sweep")),
137      current_mark_bitmap_(NULL),
138      java_lang_Class_(NULL),
139      mark_stack_(NULL),
140      finger_(NULL),
141      immune_begin_(NULL),
142      immune_end_(NULL),
143      soft_reference_list_(NULL),
144      weak_reference_list_(NULL),
145      finalizer_reference_list_(NULL),
146      phantom_reference_list_(NULL),
147      cleared_reference_list_(NULL),
148      gc_barrier_(new Barrier(0)),
149      large_object_lock_("mark sweep large object lock", kMarkSweepLargeObjectLock),
150      mark_stack_expand_lock_("mark sweep mark stack expand lock"),
151      is_concurrent_(is_concurrent),
152      clear_soft_references_(false) {
153}
154
155void MarkSweep::InitializePhase() {
156  timings_.Reset();
157  timings_.StartSplit("InitializePhase");
158  mark_stack_ = GetHeap()->mark_stack_.get();
159  DCHECK(mark_stack_ != NULL);
160  finger_ = NULL;
161  SetImmuneRange(NULL, NULL);
162  soft_reference_list_ = NULL;
163  weak_reference_list_ = NULL;
164  finalizer_reference_list_ = NULL;
165  phantom_reference_list_ = NULL;
166  cleared_reference_list_ = NULL;
167  freed_bytes_ = 0;
168  freed_objects_ = 0;
169  class_count_ = 0;
170  array_count_ = 0;
171  other_count_ = 0;
172  large_object_test_ = 0;
173  large_object_mark_ = 0;
174  classes_marked_ = 0;
175  overhead_time_ = 0;
176  work_chunks_created_ = 0;
177  work_chunks_deleted_ = 0;
178  reference_count_ = 0;
179  java_lang_Class_ = Class::GetJavaLangClass();
180  CHECK(java_lang_Class_ != NULL);
181  FindDefaultMarkBitmap();
182  // Do any pre GC verification.
183  heap_->PreGcVerification(this);
184}
185
186void MarkSweep::ProcessReferences(Thread* self) {
187  timings_.NewSplit("ProcessReferences");
188  WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
189  ProcessReferences(&soft_reference_list_, clear_soft_references_, &weak_reference_list_,
190                    &finalizer_reference_list_, &phantom_reference_list_);
191}
192
193bool MarkSweep::HandleDirtyObjectsPhase() {
194  Thread* self = Thread::Current();
195  accounting::ObjectStack* allocation_stack = GetHeap()->allocation_stack_.get();
196  Locks::mutator_lock_->AssertExclusiveHeld(self);
197
198  {
199    timings_.NewSplit("ReMarkRoots");
200    WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
201
202    // Re-mark root set.
203    ReMarkRoots();
204
205    // Scan dirty objects, this is only required if we are not doing concurrent GC.
206    RecursiveMarkDirtyObjects(accounting::CardTable::kCardDirty);
207  }
208
209  ProcessReferences(self);
210
211  // Only need to do this if we have the card mark verification on, and only during concurrent GC.
212  if (GetHeap()->verify_missing_card_marks_) {
213    WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
214    // This second sweep makes sure that we don't have any objects in the live stack which point to
215    // freed objects. These cause problems since their references may be previously freed objects.
216    SweepArray(allocation_stack, false);
217  } else {
218    timings_.NewSplit("UnMarkAllocStack");
219    WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
220    // The allocation stack contains things allocated since the start of the GC. These may have been
221    // marked during this GC meaning they won't be eligible for reclaiming in the next sticky GC.
222    // Remove these objects from the mark bitmaps so that they will be eligible for sticky
223    // collection.
224    heap_->UnMarkAllocStack(GetHeap()->alloc_space_->GetMarkBitmap(),
225                            GetHeap()->large_object_space_->GetMarkObjects(),
226                            allocation_stack);
227  }
228  return true;
229}
230
231bool MarkSweep::IsConcurrent() const {
232  return is_concurrent_;
233}
234
235void MarkSweep::MarkingPhase() {
236  Heap* heap = GetHeap();
237  Thread* self = Thread::Current();
238
239  timings_.NewSplit("BindBitmaps");
240  BindBitmaps();
241  FindDefaultMarkBitmap();
242  // Process dirty cards and add dirty cards to mod union tables.
243  heap->ProcessCards(timings_);
244
245  // Need to do this before the checkpoint since we don't want any threads to add references to
246  // the live stack during the recursive mark.
247  timings_.NewSplit("SwapStacks");
248  heap->SwapStacks();
249
250  WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
251  if (Locks::mutator_lock_->IsExclusiveHeld(self)) {
252    // If we exclusively hold the mutator lock, all threads must be suspended.
253    timings_.NewSplit("MarkRoots");
254    MarkRoots();
255  } else {
256    timings_.NewSplit("MarkRootsCheckpoint");
257    MarkRootsCheckpoint(self);
258    timings_.NewSplit("MarkNonThreadRoots");
259    MarkNonThreadRoots();
260  }
261  timings_.NewSplit("MarkConcurrentRoots");
262  MarkConcurrentRoots();
263
264  heap->UpdateAndMarkModUnion(this, timings_, GetGcType());
265  MarkReachableObjects();
266}
267
268void MarkSweep::MarkReachableObjects() {
269  // Mark everything allocated since the last as GC live so that we can sweep concurrently,
270  // knowing that new allocations won't be marked as live.
271  timings_.NewSplit("MarkStackAsLive");
272  accounting::ObjectStack* live_stack = heap_->GetLiveStack();
273  heap_->MarkAllocStack(heap_->alloc_space_->GetLiveBitmap(),
274                       heap_->large_object_space_->GetLiveObjects(),
275                       live_stack);
276  live_stack->Reset();
277  // Recursively mark all the non-image bits set in the mark bitmap.
278  RecursiveMark();
279  DisableFinger();
280}
281
282void MarkSweep::ReclaimPhase() {
283  Thread* self = Thread::Current();
284
285  if (!IsConcurrent()) {
286    ProcessReferences(self);
287  }
288
289  // Before freeing anything, lets verify the heap.
290  if (kIsDebugBuild) {
291    ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
292    VerifyImageRoots();
293  }
294  heap_->PreSweepingGcVerification(this);
295
296  {
297    WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
298
299    // Reclaim unmarked objects.
300    Sweep(false);
301
302    // Swap the live and mark bitmaps for each space which we modified space. This is an
303    // optimization that enables us to not clear live bits inside of the sweep. Only swaps unbound
304    // bitmaps.
305    timings_.NewSplit("SwapBitmaps");
306    SwapBitmaps();
307
308    // Unbind the live and mark bitmaps.
309    UnBindBitmaps();
310  }
311}
312
313void MarkSweep::SetImmuneRange(Object* begin, Object* end) {
314  immune_begin_ = begin;
315  immune_end_ = end;
316}
317
318void MarkSweep::FindDefaultMarkBitmap() {
319  const std::vector<space::ContinuousSpace*>& spaces = GetHeap()->GetContinuousSpaces();
320  // TODO: C++0x
321  typedef std::vector<space::ContinuousSpace*>::const_iterator It;
322  for (It it = spaces.begin(), end = spaces.end(); it != end; ++it) {
323    space::ContinuousSpace* space = *it;
324    if (space->GetGcRetentionPolicy() == space::kGcRetentionPolicyAlwaysCollect) {
325      current_mark_bitmap_ = (*it)->GetMarkBitmap();
326      CHECK(current_mark_bitmap_ != NULL);
327      return;
328    }
329  }
330  GetHeap()->DumpSpaces();
331  LOG(FATAL) << "Could not find a default mark bitmap";
332}
333
334void MarkSweep::ExpandMarkStack() {
335  // Rare case, no need to have Thread::Current be a parameter.
336  MutexLock mu(Thread::Current(), mark_stack_expand_lock_);
337  if (UNLIKELY(mark_stack_->Size() < mark_stack_->Capacity())) {
338    // Someone else acquired the lock and expanded the mark stack before us.
339    return;
340  }
341  std::vector<Object*> temp;
342  temp.insert(temp.begin(), mark_stack_->Begin(), mark_stack_->End());
343  mark_stack_->Resize(mark_stack_->Capacity() * 2);
344  for (size_t i = 0; i < temp.size(); ++i) {
345    mark_stack_->PushBack(temp[i]);
346  }
347}
348
349inline void MarkSweep::MarkObjectNonNullParallel(const Object* obj, bool check_finger) {
350  DCHECK(obj != NULL);
351  if (MarkObjectParallel(obj)) {
352    if (kDisableFinger || (check_finger && obj < finger_)) {
353      while (UNLIKELY(!mark_stack_->AtomicPushBack(const_cast<Object*>(obj)))) {
354        // Only reason a push can fail is that the mark stack is full.
355        ExpandMarkStack();
356      }
357    }
358  }
359}
360
361inline void MarkSweep::MarkObjectNonNull(const Object* obj, bool check_finger) {
362  DCHECK(obj != NULL);
363
364  if (obj >= immune_begin_ && obj < immune_end_) {
365    DCHECK(IsMarked(obj));
366    return;
367  }
368
369  // Try to take advantage of locality of references within a space, failing this find the space
370  // the hard way.
371  accounting::SpaceBitmap* object_bitmap = current_mark_bitmap_;
372  if (UNLIKELY(!object_bitmap->HasAddress(obj))) {
373    accounting::SpaceBitmap* new_bitmap = heap_->GetMarkBitmap()->GetContinuousSpaceBitmap(obj);
374    if (LIKELY(new_bitmap != NULL)) {
375      object_bitmap = new_bitmap;
376    } else {
377      MarkLargeObject(obj);
378      return;
379    }
380  }
381
382  // This object was not previously marked.
383  if (!object_bitmap->Test(obj)) {
384    object_bitmap->Set(obj);
385    if (kDisableFinger || (check_finger && obj < finger_)) {
386      // Do we need to expand the mark stack?
387      if (UNLIKELY(mark_stack_->Size() >= mark_stack_->Capacity())) {
388        ExpandMarkStack();
389      }
390      // The object must be pushed on to the mark stack.
391      mark_stack_->PushBack(const_cast<Object*>(obj));
392    }
393  }
394}
395
396// Rare case, probably not worth inlining since it will increase instruction cache miss rate.
397bool MarkSweep::MarkLargeObject(const Object* obj) {
398  // TODO: support >1 discontinuous space.
399  space::LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
400  accounting::SpaceSetMap* large_objects = large_object_space->GetMarkObjects();
401  if (kProfileLargeObjects) {
402    ++large_object_test_;
403  }
404  if (UNLIKELY(!large_objects->Test(obj))) {
405    if (!large_object_space->Contains(obj)) {
406      LOG(ERROR) << "Tried to mark " << obj << " not contained by any spaces";
407      LOG(ERROR) << "Attempting see if it's a bad root";
408      VerifyRoots();
409      LOG(FATAL) << "Can't mark bad root";
410    }
411    if (kProfileLargeObjects) {
412      ++large_object_mark_;
413    }
414    large_objects->Set(obj);
415    // Don't need to check finger since large objects never have any object references.
416    return true;
417  }
418  return false;
419}
420
421inline bool MarkSweep::MarkObjectParallel(const Object* obj) {
422  DCHECK(obj != NULL);
423
424  if (obj >= immune_begin_ && obj < immune_end_) {
425    DCHECK(IsMarked(obj));
426    return false;
427  }
428
429  // Try to take advantage of locality of references within a space, failing this find the space
430  // the hard way.
431  accounting::SpaceBitmap* object_bitmap = current_mark_bitmap_;
432  if (UNLIKELY(!object_bitmap->HasAddress(obj))) {
433    accounting::SpaceBitmap* new_bitmap = heap_->GetMarkBitmap()->GetContinuousSpaceBitmap(obj);
434    if (new_bitmap != NULL) {
435      object_bitmap = new_bitmap;
436    } else {
437      // TODO: Remove the Thread::Current here?
438      // TODO: Convert this to some kind of atomic marking?
439      MutexLock mu(Thread::Current(), large_object_lock_);
440      return MarkLargeObject(obj);
441    }
442  }
443
444  // Return true if the object was not previously marked.
445  return !object_bitmap->AtomicTestAndSet(obj);
446}
447
448// Used to mark objects when recursing.  Recursion is done by moving
449// the finger across the bitmaps in address order and marking child
450// objects.  Any newly-marked objects whose addresses are lower than
451// the finger won't be visited by the bitmap scan, so those objects
452// need to be added to the mark stack.
453void MarkSweep::MarkObject(const Object* obj) {
454  if (obj != NULL) {
455    MarkObjectNonNull(obj, true);
456  }
457}
458
459void MarkSweep::MarkRoot(const Object* obj) {
460  if (obj != NULL) {
461    MarkObjectNonNull(obj, false);
462  }
463}
464
465void MarkSweep::MarkRootParallelCallback(const Object* root, void* arg) {
466  DCHECK(root != NULL);
467  DCHECK(arg != NULL);
468  MarkSweep* mark_sweep = reinterpret_cast<MarkSweep*>(arg);
469  mark_sweep->MarkObjectNonNullParallel(root, false);
470}
471
472void MarkSweep::MarkObjectCallback(const Object* root, void* arg) {
473  DCHECK(root != NULL);
474  DCHECK(arg != NULL);
475  MarkSweep* mark_sweep = reinterpret_cast<MarkSweep*>(arg);
476  mark_sweep->MarkObjectNonNull(root, false);
477}
478
479void MarkSweep::ReMarkObjectVisitor(const Object* root, void* arg) {
480  DCHECK(root != NULL);
481  DCHECK(arg != NULL);
482  MarkSweep* mark_sweep = reinterpret_cast<MarkSweep*>(arg);
483  mark_sweep->MarkObjectNonNull(root, true);
484}
485
486void MarkSweep::VerifyRootCallback(const Object* root, void* arg, size_t vreg,
487                                   const StackVisitor* visitor) {
488  reinterpret_cast<MarkSweep*>(arg)->VerifyRoot(root, vreg, visitor);
489}
490
491void MarkSweep::VerifyRoot(const Object* root, size_t vreg, const StackVisitor* visitor) {
492  // See if the root is on any space bitmap.
493  if (GetHeap()->GetLiveBitmap()->GetContinuousSpaceBitmap(root) == NULL) {
494    space::LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
495    if (!large_object_space->Contains(root)) {
496      LOG(ERROR) << "Found invalid root: " << root;
497      if (visitor != NULL) {
498        LOG(ERROR) << visitor->DescribeLocation() << " in VReg: " << vreg;
499      }
500    }
501  }
502}
503
504void MarkSweep::VerifyRoots() {
505  Runtime::Current()->GetThreadList()->VerifyRoots(VerifyRootCallback, this);
506}
507
508// Marks all objects in the root set.
509void MarkSweep::MarkRoots() {
510  Runtime::Current()->VisitNonConcurrentRoots(MarkObjectCallback, this);
511}
512
513void MarkSweep::MarkNonThreadRoots() {
514  Runtime::Current()->VisitNonThreadRoots(MarkObjectCallback, this);
515}
516
517void MarkSweep::MarkConcurrentRoots() {
518  // Visit all runtime roots and clear dirty flags.
519  Runtime::Current()->VisitConcurrentRoots(MarkObjectCallback, this, false, true);
520}
521
522class CheckObjectVisitor {
523 public:
524  CheckObjectVisitor(MarkSweep* const mark_sweep)
525      : mark_sweep_(mark_sweep) {
526
527  }
528
529  void operator ()(const Object* obj, const Object* ref, MemberOffset offset, bool is_static) const
530      NO_THREAD_SAFETY_ANALYSIS {
531    if (kDebugLocking) {
532      Locks::heap_bitmap_lock_->AssertSharedHeld(Thread::Current());
533    }
534    mark_sweep_->CheckReference(obj, ref, offset, is_static);
535  }
536
537 private:
538  MarkSweep* const mark_sweep_;
539};
540
541void MarkSweep::CheckObject(const Object* obj) {
542  DCHECK(obj != NULL);
543  CheckObjectVisitor visitor(this);
544  VisitObjectReferences(obj, visitor);
545}
546
547void MarkSweep::VerifyImageRootVisitor(Object* root, void* arg) {
548  DCHECK(root != NULL);
549  DCHECK(arg != NULL);
550  MarkSweep* mark_sweep = reinterpret_cast<MarkSweep*>(arg);
551  DCHECK(mark_sweep->heap_->GetMarkBitmap()->Test(root));
552  mark_sweep->CheckObject(root);
553}
554
555void MarkSweep::BindLiveToMarkBitmap(space::ContinuousSpace* space) {
556  CHECK(space->IsDlMallocSpace());
557  space::DlMallocSpace* alloc_space = space->AsDlMallocSpace();
558  accounting::SpaceBitmap* live_bitmap = space->GetLiveBitmap();
559  accounting::SpaceBitmap* mark_bitmap = alloc_space->mark_bitmap_.release();
560  GetHeap()->GetMarkBitmap()->ReplaceBitmap(mark_bitmap, live_bitmap);
561  alloc_space->temp_bitmap_.reset(mark_bitmap);
562  alloc_space->mark_bitmap_.reset(live_bitmap);
563}
564
565class ScanObjectVisitor {
566 public:
567  ScanObjectVisitor(MarkSweep* const mark_sweep) : mark_sweep_(mark_sweep) {
568  }
569
570  // TODO: Fixme when anotatalysis works with visitors.
571  void operator ()(const Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
572    if (kDebugLocking) {
573      Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
574      Locks::heap_bitmap_lock_->AssertExclusiveHeld(Thread::Current());
575    }
576    mark_sweep_->ScanObject(obj);
577  }
578
579 private:
580  MarkSweep* const mark_sweep_;
581};
582
583void MarkSweep::ScanGrayObjects(byte minimum_age) {
584  accounting::CardTable* card_table = GetHeap()->GetCardTable();
585  const std::vector<space::ContinuousSpace*>& spaces = GetHeap()->GetContinuousSpaces();
586  ScanObjectVisitor visitor(this);
587  SetFingerVisitor finger_visitor(this);
588  // TODO: C++0x
589  typedef std::vector<space::ContinuousSpace*>::const_iterator It;
590  for (It it = spaces.begin(), space_end = spaces.end(); it != space_end; ++it) {
591    space::ContinuousSpace* space = *it;
592    switch (space->GetGcRetentionPolicy()) {
593      case space::kGcRetentionPolicyNeverCollect:
594        timings_.NewSplit("ScanGrayImageSpaceObjects");
595        break;
596      case space::kGcRetentionPolicyFullCollect:
597        timings_.NewSplit("ScanGrayZygoteSpaceObjects");
598        break;
599      case space::kGcRetentionPolicyAlwaysCollect:
600        timings_.NewSplit("ScanGrayAllocSpaceObjects");
601        break;
602    }
603    byte* begin = space->Begin();
604    byte* end = space->End();
605    // Image spaces are handled properly since live == marked for them.
606    accounting::SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
607    card_table->Scan(mark_bitmap, begin, end, visitor, finger_visitor, minimum_age);
608  }
609}
610
611class CheckBitmapVisitor {
612 public:
613  CheckBitmapVisitor(MarkSweep* mark_sweep) : mark_sweep_(mark_sweep) {
614  }
615
616  void operator ()(const Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
617    if (kDebugLocking) {
618      Locks::heap_bitmap_lock_->AssertSharedHeld(Thread::Current());
619    }
620    DCHECK(obj != NULL);
621    mark_sweep_->CheckObject(obj);
622  }
623
624 private:
625  MarkSweep* mark_sweep_;
626};
627
628void MarkSweep::VerifyImageRoots() {
629  // Verify roots ensures that all the references inside the image space point
630  // objects which are either in the image space or marked objects in the alloc
631  // space
632  CheckBitmapVisitor visitor(this);
633  const std::vector<space::ContinuousSpace*>& spaces = GetHeap()->GetContinuousSpaces();
634  // TODO: C++0x
635  typedef std::vector<space::ContinuousSpace*>::const_iterator It;
636  for (It it = spaces.begin(), end = spaces.end(); it != end; ++it) {
637    if ((*it)->IsImageSpace()) {
638      space::ImageSpace* space = (*it)->AsImageSpace();
639      uintptr_t begin = reinterpret_cast<uintptr_t>(space->Begin());
640      uintptr_t end = reinterpret_cast<uintptr_t>(space->End());
641      accounting::SpaceBitmap* live_bitmap = space->GetLiveBitmap();
642      DCHECK(live_bitmap != NULL);
643      live_bitmap->VisitMarkedRange(begin, end, visitor, VoidFunctor());
644    }
645  }
646}
647
648// Populates the mark stack based on the set of marked objects and
649// recursively marks until the mark stack is emptied.
650void MarkSweep::RecursiveMark() {
651  timings_.NewSplit("RecursiveMark");
652  // RecursiveMark will build the lists of known instances of the Reference classes.
653  // See DelayReferenceReferent for details.
654  CHECK(soft_reference_list_ == NULL);
655  CHECK(weak_reference_list_ == NULL);
656  CHECK(finalizer_reference_list_ == NULL);
657  CHECK(phantom_reference_list_ == NULL);
658  CHECK(cleared_reference_list_ == NULL);
659
660  const bool partial = GetGcType() == kGcTypePartial;
661  SetFingerVisitor set_finger_visitor(this);
662  ScanObjectVisitor scan_visitor(this);
663  if (!kDisableFinger) {
664    finger_ = NULL;
665    const std::vector<space::ContinuousSpace*>& spaces = GetHeap()->GetContinuousSpaces();
666    // TODO: C++0x
667    typedef std::vector<space::ContinuousSpace*>::const_iterator It;
668    for (It it = spaces.begin(), end = spaces.end(); it != end; ++it) {
669      space::ContinuousSpace* space = *it;
670      if ((space->GetGcRetentionPolicy() == space::kGcRetentionPolicyAlwaysCollect) ||
671          (!partial && space->GetGcRetentionPolicy() == space::kGcRetentionPolicyFullCollect)) {
672        current_mark_bitmap_ = space->GetMarkBitmap();
673        if (current_mark_bitmap_ == NULL) {
674          GetHeap()->DumpSpaces();
675          LOG(FATAL) << "invalid bitmap";
676        }
677        // This function does not handle heap end increasing, so we must use the space end.
678        uintptr_t begin = reinterpret_cast<uintptr_t>(space->Begin());
679        uintptr_t end = reinterpret_cast<uintptr_t>(space->End());
680        current_mark_bitmap_->VisitMarkedRange(begin, end, scan_visitor, set_finger_visitor);
681      }
682    }
683  }
684  DisableFinger();
685  timings_.NewSplit("ProcessMarkStack");
686  ProcessMarkStack();
687}
688
689bool MarkSweep::IsMarkedCallback(const Object* object, void* arg) {
690  return
691      reinterpret_cast<MarkSweep*>(arg)->IsMarked(object) ||
692      !reinterpret_cast<MarkSweep*>(arg)->GetHeap()->GetLiveBitmap()->Test(object);
693}
694
695void MarkSweep::RecursiveMarkDirtyObjects(byte minimum_age) {
696  ScanGrayObjects(minimum_age);
697  timings_.NewSplit("ProcessMarkStack");
698  ProcessMarkStack();
699}
700
701void MarkSweep::ReMarkRoots() {
702  Runtime::Current()->VisitRoots(ReMarkObjectVisitor, this, true, true);
703}
704
705void MarkSweep::SweepJniWeakGlobals(IsMarkedTester is_marked, void* arg) {
706  JavaVMExt* vm = Runtime::Current()->GetJavaVM();
707  MutexLock mu(Thread::Current(), vm->weak_globals_lock);
708  IndirectReferenceTable* table = &vm->weak_globals;
709  typedef IndirectReferenceTable::iterator It;  // TODO: C++0x auto
710  for (It it = table->begin(), end = table->end(); it != end; ++it) {
711    const Object** entry = *it;
712    if (!is_marked(*entry, arg)) {
713      *entry = kClearedJniWeakGlobal;
714    }
715  }
716}
717
718struct ArrayMarkedCheck {
719  accounting::ObjectStack* live_stack;
720  MarkSweep* mark_sweep;
721};
722
723// Either marked or not live.
724bool MarkSweep::IsMarkedArrayCallback(const Object* object, void* arg) {
725  ArrayMarkedCheck* array_check = reinterpret_cast<ArrayMarkedCheck*>(arg);
726  if (array_check->mark_sweep->IsMarked(object)) {
727    return true;
728  }
729  accounting::ObjectStack* live_stack = array_check->live_stack;
730  return std::find(live_stack->Begin(), live_stack->End(), object) == live_stack->End();
731}
732
733void MarkSweep::SweepSystemWeaksArray(accounting::ObjectStack* allocations) {
734  Runtime* runtime = Runtime::Current();
735  // The callbacks check
736  // !is_marked where is_marked is the callback but we want
737  // !IsMarked && IsLive
738  // So compute !(!IsMarked && IsLive) which is equal to (IsMarked || !IsLive).
739  // Or for swapped (IsLive || !IsMarked).
740
741  ArrayMarkedCheck visitor;
742  visitor.live_stack = allocations;
743  visitor.mark_sweep = this;
744  runtime->GetInternTable()->SweepInternTableWeaks(IsMarkedArrayCallback, &visitor);
745  runtime->GetMonitorList()->SweepMonitorList(IsMarkedArrayCallback, &visitor);
746  SweepJniWeakGlobals(IsMarkedArrayCallback, &visitor);
747}
748
749void MarkSweep::SweepSystemWeaks() {
750  Runtime* runtime = Runtime::Current();
751  // The callbacks check
752  // !is_marked where is_marked is the callback but we want
753  // !IsMarked && IsLive
754  // So compute !(!IsMarked && IsLive) which is equal to (IsMarked || !IsLive).
755  // Or for swapped (IsLive || !IsMarked).
756  runtime->GetInternTable()->SweepInternTableWeaks(IsMarkedCallback, this);
757  runtime->GetMonitorList()->SweepMonitorList(IsMarkedCallback, this);
758  SweepJniWeakGlobals(IsMarkedCallback, this);
759}
760
761bool MarkSweep::VerifyIsLiveCallback(const Object* obj, void* arg) {
762  reinterpret_cast<MarkSweep*>(arg)->VerifyIsLive(obj);
763  // We don't actually want to sweep the object, so lets return "marked"
764  return true;
765}
766
767void MarkSweep::VerifyIsLive(const Object* obj) {
768  Heap* heap = GetHeap();
769  if (!heap->GetLiveBitmap()->Test(obj)) {
770    space::LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
771    if (!large_object_space->GetLiveObjects()->Test(obj)) {
772      if (std::find(heap->allocation_stack_->Begin(), heap->allocation_stack_->End(), obj) ==
773          heap->allocation_stack_->End()) {
774        // Object not found!
775        heap->DumpSpaces();
776        LOG(FATAL) << "Found dead object " << obj;
777      }
778    }
779  }
780}
781
782void MarkSweep::VerifySystemWeaks() {
783  Runtime* runtime = Runtime::Current();
784  // Verify system weaks, uses a special IsMarked callback which always returns true.
785  runtime->GetInternTable()->SweepInternTableWeaks(VerifyIsLiveCallback, this);
786  runtime->GetMonitorList()->SweepMonitorList(VerifyIsLiveCallback, this);
787
788  JavaVMExt* vm = runtime->GetJavaVM();
789  MutexLock mu(Thread::Current(), vm->weak_globals_lock);
790  IndirectReferenceTable* table = &vm->weak_globals;
791  typedef IndirectReferenceTable::iterator It;  // TODO: C++0x auto
792  for (It it = table->begin(), end = table->end(); it != end; ++it) {
793    const Object** entry = *it;
794    VerifyIsLive(*entry);
795  }
796}
797
798struct SweepCallbackContext {
799  MarkSweep* mark_sweep;
800  space::AllocSpace* space;
801  Thread* self;
802};
803
804class CheckpointMarkThreadRoots : public Closure {
805 public:
806  CheckpointMarkThreadRoots(MarkSweep* mark_sweep) : mark_sweep_(mark_sweep) {
807
808  }
809
810  virtual void Run(Thread* thread) NO_THREAD_SAFETY_ANALYSIS {
811    // Note: self is not necessarily equal to thread since thread may be suspended.
812    Thread* self = Thread::Current();
813    CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
814        << thread->GetState() << " thread " << thread << " self " << self;
815    thread->VisitRoots(MarkSweep::MarkRootParallelCallback, mark_sweep_);
816    mark_sweep_->GetBarrier().Pass(self);
817  }
818
819 private:
820  MarkSweep* mark_sweep_;
821};
822
823void MarkSweep::MarkRootsCheckpoint(Thread* self) {
824  CheckpointMarkThreadRoots check_point(this);
825  ThreadList* thread_list = Runtime::Current()->GetThreadList();
826  // Request the check point is run on all threads returning a count of the threads that must
827  // run through the barrier including self.
828  size_t barrier_count = thread_list->RunCheckpoint(&check_point);
829  // Release locks then wait for all mutator threads to pass the barrier.
830  // TODO: optimize to not release locks when there are no threads to wait for.
831  Locks::heap_bitmap_lock_->ExclusiveUnlock(self);
832  Locks::mutator_lock_->SharedUnlock(self);
833  ThreadState old_state = self->SetState(kWaitingForCheckPointsToRun);
834  CHECK_EQ(old_state, kWaitingPerformingGc);
835  gc_barrier_->Increment(self, barrier_count);
836  self->SetState(kWaitingPerformingGc);
837  Locks::mutator_lock_->SharedLock(self);
838  Locks::heap_bitmap_lock_->ExclusiveLock(self);
839}
840
841void MarkSweep::SweepCallback(size_t num_ptrs, Object** ptrs, void* arg) {
842  SweepCallbackContext* context = static_cast<SweepCallbackContext*>(arg);
843  MarkSweep* mark_sweep = context->mark_sweep;
844  Heap* heap = mark_sweep->GetHeap();
845  space::AllocSpace* space = context->space;
846  Thread* self = context->self;
847  Locks::heap_bitmap_lock_->AssertExclusiveHeld(self);
848  // Use a bulk free, that merges consecutive objects before freeing or free per object?
849  // Documentation suggests better free performance with merging, but this may be at the expensive
850  // of allocation.
851  size_t freed_objects = num_ptrs;
852  // AllocSpace::FreeList clears the value in ptrs, so perform after clearing the live bit
853  size_t freed_bytes = space->FreeList(self, num_ptrs, ptrs);
854  heap->RecordFree(freed_objects, freed_bytes);
855  mark_sweep->freed_objects_.fetch_add(freed_objects);
856  mark_sweep->freed_bytes_.fetch_add(freed_bytes);
857}
858
859void MarkSweep::ZygoteSweepCallback(size_t num_ptrs, Object** ptrs, void* arg) {
860  SweepCallbackContext* context = static_cast<SweepCallbackContext*>(arg);
861  Locks::heap_bitmap_lock_->AssertExclusiveHeld(context->self);
862  Heap* heap = context->mark_sweep->GetHeap();
863  // We don't free any actual memory to avoid dirtying the shared zygote pages.
864  for (size_t i = 0; i < num_ptrs; ++i) {
865    Object* obj = static_cast<Object*>(ptrs[i]);
866    heap->GetLiveBitmap()->Clear(obj);
867    heap->GetCardTable()->MarkCard(obj);
868  }
869}
870
871void MarkSweep::SweepArray(accounting::ObjectStack* allocations, bool swap_bitmaps) {
872  size_t freed_bytes = 0;
873  space::DlMallocSpace* space = heap_->GetAllocSpace();
874
875  // If we don't swap bitmaps then newly allocated Weaks go into the live bitmap but not mark
876  // bitmap, resulting in occasional frees of Weaks which are still in use.
877  timings_.NewSplit("SweepSystemWeaks");
878  SweepSystemWeaksArray(allocations);
879
880  timings_.NewSplit("Process allocation stack");
881  // Newly allocated objects MUST be in the alloc space and those are the only objects which we are
882  // going to free.
883  accounting::SpaceBitmap* live_bitmap = space->GetLiveBitmap();
884  accounting::SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
885  space::LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
886  accounting::SpaceSetMap* large_live_objects = large_object_space->GetLiveObjects();
887  accounting::SpaceSetMap* large_mark_objects = large_object_space->GetMarkObjects();
888  if (swap_bitmaps) {
889    std::swap(live_bitmap, mark_bitmap);
890    std::swap(large_live_objects, large_mark_objects);
891  }
892
893  size_t freed_large_objects = 0;
894  size_t count = allocations->Size();
895  Object** objects = const_cast<Object**>(allocations->Begin());
896  Object** out = objects;
897
898  // Empty the allocation stack.
899  Thread* self = Thread::Current();
900  for (size_t i = 0;i < count;++i) {
901    Object* obj = objects[i];
902    // There should only be objects in the AllocSpace/LargeObjectSpace in the allocation stack.
903    if (LIKELY(mark_bitmap->HasAddress(obj))) {
904      if (!mark_bitmap->Test(obj)) {
905        // Don't bother un-marking since we clear the mark bitmap anyways.
906        *(out++) = obj;
907      }
908    } else if (!large_mark_objects->Test(obj)) {
909      ++freed_large_objects;
910      freed_bytes += large_object_space->Free(self, obj);
911    }
912  }
913  CHECK_EQ(count, allocations->Size());
914  timings_.NewSplit("FreeList");
915
916  size_t freed_objects = out - objects;
917  freed_bytes += space->FreeList(self, freed_objects, objects);
918  VLOG(heap) << "Freed " << freed_objects << "/" << count
919             << " objects with size " << PrettySize(freed_bytes);
920  heap_->RecordFree(freed_objects + freed_large_objects, freed_bytes);
921  freed_objects_.fetch_add(freed_objects);
922  freed_bytes_.fetch_add(freed_bytes);
923
924  timings_.NewSplit("ResetStack");
925  allocations->Reset();
926}
927
928void MarkSweep::Sweep(bool swap_bitmaps) {
929  DCHECK(mark_stack_->IsEmpty());
930
931  // If we don't swap bitmaps then newly allocated Weaks go into the live bitmap but not mark
932  // bitmap, resulting in occasional frees of Weaks which are still in use.
933  timings_.NewSplit("SweepSystemWeaks");
934  SweepSystemWeaks();
935
936  const bool partial = (GetGcType() == kGcTypePartial);
937  SweepCallbackContext scc;
938  scc.mark_sweep = this;
939  scc.self = Thread::Current();
940  const std::vector<space::ContinuousSpace*>& spaces = GetHeap()->GetContinuousSpaces();
941  // TODO: C++0x
942  typedef std::vector<space::ContinuousSpace*>::const_iterator It;
943  for (It it = spaces.begin(), end = spaces.end(); it != end; ++it) {
944    space::ContinuousSpace* space = *it;
945    // We always sweep always collect spaces.
946    bool sweep_space = (space->GetGcRetentionPolicy() == space::kGcRetentionPolicyAlwaysCollect);
947    if (!partial && !sweep_space) {
948      // We sweep full collect spaces when the GC isn't a partial GC (ie its full).
949      sweep_space = (space->GetGcRetentionPolicy() == space::kGcRetentionPolicyFullCollect);
950    }
951    if (sweep_space) {
952      uintptr_t begin = reinterpret_cast<uintptr_t>(space->Begin());
953      uintptr_t end = reinterpret_cast<uintptr_t>(space->End());
954      scc.space = space->AsDlMallocSpace();
955      accounting::SpaceBitmap* live_bitmap = space->GetLiveBitmap();
956      accounting::SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
957      if (swap_bitmaps) {
958        std::swap(live_bitmap, mark_bitmap);
959      }
960      if (!space->IsZygoteSpace()) {
961        timings_.NewSplit("SweepAllocSpace");
962        // Bitmaps are pre-swapped for optimization which enables sweeping with the heap unlocked.
963        accounting::SpaceBitmap::SweepWalk(*live_bitmap, *mark_bitmap, begin, end,
964                                           &SweepCallback, reinterpret_cast<void*>(&scc));
965      } else {
966        timings_.NewSplit("SweepZygote");
967        // Zygote sweep takes care of dirtying cards and clearing live bits, does not free actual
968        // memory.
969        accounting::SpaceBitmap::SweepWalk(*live_bitmap, *mark_bitmap, begin, end,
970                                           &ZygoteSweepCallback, reinterpret_cast<void*>(&scc));
971      }
972    }
973  }
974
975  timings_.NewSplit("SweepLargeObjects");
976  SweepLargeObjects(swap_bitmaps);
977}
978
979void MarkSweep::SweepLargeObjects(bool swap_bitmaps) {
980  // Sweep large objects
981  space::LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
982  accounting::SpaceSetMap* large_live_objects = large_object_space->GetLiveObjects();
983  accounting::SpaceSetMap* large_mark_objects = large_object_space->GetMarkObjects();
984  if (swap_bitmaps) {
985    std::swap(large_live_objects, large_mark_objects);
986  }
987  accounting::SpaceSetMap::Objects& live_objects = large_live_objects->GetObjects();
988  // O(n*log(n)) but hopefully there are not too many large objects.
989  size_t freed_objects = 0;
990  size_t freed_bytes = 0;
991  Thread* self = Thread::Current();
992  // TODO: C++0x
993  typedef accounting::SpaceSetMap::Objects::iterator It;
994  for (It it = live_objects.begin(), end = live_objects.end(); it != end; ++it) {
995    if (!large_mark_objects->Test(*it)) {
996      freed_bytes += large_object_space->Free(self, const_cast<Object*>(*it));
997      ++freed_objects;
998    }
999  }
1000  freed_objects_.fetch_add(freed_objects);
1001  freed_bytes_.fetch_add(freed_bytes);
1002  GetHeap()->RecordFree(freed_objects, freed_bytes);
1003}
1004
1005void MarkSweep::CheckReference(const Object* obj, const Object* ref, MemberOffset offset, bool is_static) {
1006  const std::vector<space::ContinuousSpace*>& spaces = GetHeap()->GetContinuousSpaces();
1007  // TODO: C++0x
1008  typedef std::vector<space::ContinuousSpace*>::const_iterator It;
1009  for (It it = spaces.begin(), end = spaces.end(); it != end; ++it) {
1010    space::ContinuousSpace* space = *it;
1011    if (space->IsDlMallocSpace() && space->Contains(ref)) {
1012      DCHECK(IsMarked(obj));
1013
1014      bool is_marked = IsMarked(ref);
1015      if (!is_marked) {
1016        LOG(INFO) << *space;
1017        LOG(WARNING) << (is_static ? "Static ref'" : "Instance ref'") << PrettyTypeOf(ref)
1018                     << "' (" << reinterpret_cast<const void*>(ref) << ") in '" << PrettyTypeOf(obj)
1019                     << "' (" << reinterpret_cast<const void*>(obj) << ") at offset "
1020                     << reinterpret_cast<void*>(offset.Int32Value()) << " wasn't marked";
1021
1022        const Class* klass = is_static ? obj->AsClass() : obj->GetClass();
1023        DCHECK(klass != NULL);
1024        const ObjectArray<Field>* fields = is_static ? klass->GetSFields() : klass->GetIFields();
1025        DCHECK(fields != NULL);
1026        bool found = false;
1027        for (int32_t i = 0; i < fields->GetLength(); ++i) {
1028          const Field* cur = fields->Get(i);
1029          if (cur->GetOffset().Int32Value() == offset.Int32Value()) {
1030            LOG(WARNING) << "Field referencing the alloc space was " << PrettyField(cur);
1031            found = true;
1032            break;
1033          }
1034        }
1035        if (!found) {
1036          LOG(WARNING) << "Could not find field in object alloc space with offset " << offset.Int32Value();
1037        }
1038
1039        bool obj_marked = heap_->GetCardTable()->IsDirty(obj);
1040        if (!obj_marked) {
1041          LOG(WARNING) << "Object '" << PrettyTypeOf(obj) << "' "
1042                       << "(" << reinterpret_cast<const void*>(obj) << ") contains references to "
1043                       << "the alloc space, but wasn't card marked";
1044        }
1045      }
1046    }
1047    break;
1048  }
1049}
1050
1051// Process the "referent" field in a java.lang.ref.Reference.  If the
1052// referent has not yet been marked, put it on the appropriate list in
1053// the gcHeap for later processing.
1054void MarkSweep::DelayReferenceReferent(Object* obj) {
1055  DCHECK(obj != NULL);
1056  Class* klass = obj->GetClass();
1057  DCHECK(klass != NULL);
1058  DCHECK(klass->IsReferenceClass());
1059  Object* pending = obj->GetFieldObject<Object*>(heap_->GetReferencePendingNextOffset(), false);
1060  Object* referent = heap_->GetReferenceReferent(obj);
1061  if (kCountJavaLangRefs) {
1062    ++reference_count_;
1063  }
1064  if (pending == NULL && referent != NULL && !IsMarked(referent)) {
1065    Object** list = NULL;
1066    if (klass->IsSoftReferenceClass()) {
1067      list = &soft_reference_list_;
1068    } else if (klass->IsWeakReferenceClass()) {
1069      list = &weak_reference_list_;
1070    } else if (klass->IsFinalizerReferenceClass()) {
1071      list = &finalizer_reference_list_;
1072    } else if (klass->IsPhantomReferenceClass()) {
1073      list = &phantom_reference_list_;
1074    }
1075    DCHECK(list != NULL) << PrettyClass(klass) << " " << std::hex << klass->GetAccessFlags();
1076    // TODO: One lock per list?
1077    heap_->EnqueuePendingReference(obj, list);
1078  }
1079}
1080
1081void MarkSweep::ScanRoot(const Object* obj) {
1082  ScanObject(obj);
1083}
1084
1085class MarkObjectVisitor {
1086 public:
1087  MarkObjectVisitor(MarkSweep* const mark_sweep) : mark_sweep_(mark_sweep) {
1088  }
1089
1090  // TODO: Fixme when anotatalysis works with visitors.
1091  void operator ()(const Object* /* obj */, const Object* ref, const MemberOffset& /* offset */,
1092                   bool /* is_static */) const
1093      NO_THREAD_SAFETY_ANALYSIS {
1094    if (kDebugLocking) {
1095      Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
1096      Locks::heap_bitmap_lock_->AssertExclusiveHeld(Thread::Current());
1097    }
1098    mark_sweep_->MarkObject(ref);
1099  }
1100
1101 private:
1102  MarkSweep* const mark_sweep_;
1103};
1104
1105// Scans an object reference.  Determines the type of the reference
1106// and dispatches to a specialized scanning routine.
1107void MarkSweep::ScanObject(const Object* obj) {
1108  MarkObjectVisitor visitor(this);
1109  ScanObjectVisit(obj, visitor);
1110}
1111
1112class MarkStackChunk : public Task {
1113 public:
1114  MarkStackChunk(ThreadPool* thread_pool, MarkSweep* mark_sweep, Object** begin, Object** end)
1115      : mark_sweep_(mark_sweep),
1116        thread_pool_(thread_pool),
1117        index_(0),
1118        length_(0),
1119        output_(NULL) {
1120    length_ = end - begin;
1121    if (begin != end) {
1122      // Cost not significant since we only do this for the initial set of mark stack chunks.
1123      memcpy(data_, begin, length_ * sizeof(*begin));
1124    }
1125    if (kCountTasks) {
1126      ++mark_sweep_->work_chunks_created_;
1127    }
1128  }
1129
1130  ~MarkStackChunk() {
1131    DCHECK(output_ == NULL || output_->length_ == 0);
1132    DCHECK_GE(index_, length_);
1133    delete output_;
1134    if (kCountTasks) {
1135      ++mark_sweep_->work_chunks_deleted_;
1136    }
1137  }
1138
1139  MarkSweep* const mark_sweep_;
1140  ThreadPool* const thread_pool_;
1141  static const size_t max_size = 1 * KB;
1142  // Index of which object we are scanning. Only needs to be atomic if we are doing work stealing.
1143  size_t index_;
1144  // Input / output mark stack. We add newly marked references to data_ until length reaches
1145  // max_size. This is an optimization so that less tasks are created.
1146  // TODO: Investigate using a bounded buffer FIFO.
1147  Object* data_[max_size];
1148  // How many elements in data_ we need to scan.
1149  size_t length_;
1150  // Output block, newly marked references get added to the ouput block so that another thread can
1151  // scan them.
1152  MarkStackChunk* output_;
1153
1154  class MarkObjectParallelVisitor {
1155   public:
1156    MarkObjectParallelVisitor(MarkStackChunk* chunk_task) : chunk_task_(chunk_task) {
1157
1158    }
1159
1160    void operator ()(const Object* /* obj */, const Object* ref,
1161                     const MemberOffset& /* offset */, bool /* is_static */) const {
1162      if (ref != NULL && chunk_task_->mark_sweep_->MarkObjectParallel(ref)) {
1163        chunk_task_->MarkStackPush(ref);
1164      }
1165    }
1166
1167   private:
1168    MarkStackChunk* const chunk_task_;
1169  };
1170
1171  // Push an object into the block.
1172  // Don't need to use atomic ++ since we only one thread is writing to an output block at any
1173  // given time.
1174  void Push(Object* obj) {
1175    CHECK(obj != NULL);
1176    data_[length_++] = obj;
1177  }
1178
1179  void MarkStackPush(const Object* obj) {
1180    if (static_cast<size_t>(length_) < max_size) {
1181      Push(const_cast<Object*>(obj));
1182    } else {
1183      // Internal (thread-local) buffer is full, push to a new buffer instead.
1184      if (UNLIKELY(output_ == NULL)) {
1185        AllocateOutputChunk();
1186      } else if (UNLIKELY(static_cast<size_t>(output_->length_) == max_size)) {
1187        // Output block is full, queue it up for processing and obtain a new block.
1188        EnqueueOutput();
1189        AllocateOutputChunk();
1190      }
1191      output_->Push(const_cast<Object*>(obj));
1192    }
1193  }
1194
1195  void ScanObject(Object* obj) {
1196    mark_sweep_->ScanObjectVisit(obj, MarkObjectParallelVisitor(this));
1197  }
1198
1199  void EnqueueOutput() {
1200    if (output_ != NULL) {
1201      uint64_t start = 0;
1202      if (kMeasureOverhead) {
1203        start = NanoTime();
1204      }
1205      thread_pool_->AddTask(Thread::Current(), output_);
1206      output_ = NULL;
1207      if (kMeasureOverhead) {
1208        mark_sweep_->overhead_time_.fetch_add(NanoTime() - start);
1209      }
1210    }
1211  }
1212
1213  void AllocateOutputChunk() {
1214    uint64_t start = 0;
1215    if (kMeasureOverhead) {
1216      start = NanoTime();
1217    }
1218    output_ = new MarkStackChunk(thread_pool_, mark_sweep_, NULL, NULL);
1219    if (kMeasureOverhead) {
1220      mark_sweep_->overhead_time_.fetch_add(NanoTime() - start);
1221    }
1222  }
1223
1224  void Finalize() {
1225    EnqueueOutput();
1226    delete this;
1227  }
1228
1229  // Scans all of the objects
1230  virtual void Run(Thread* self) {
1231    size_t index;
1232    while ((index = index_++) < length_) {
1233      if (kUseMarkStackPrefetch) {
1234        static const size_t prefetch_look_ahead = 1;
1235        __builtin_prefetch(data_[std::min(index + prefetch_look_ahead, length_ - 1)]);
1236      }
1237      Object* obj = data_[index];
1238      DCHECK(obj != NULL);
1239      ScanObject(obj);
1240    }
1241  }
1242};
1243
1244void MarkSweep::ProcessMarkStackParallel() {
1245  CHECK(kDisableFinger) << "parallel mark stack processing cannot work when finger is enabled";
1246  Thread* self = Thread::Current();
1247  ThreadPool* thread_pool = GetHeap()->GetThreadPool();
1248  // Split the current mark stack up into work tasks.
1249  const size_t num_threads = thread_pool->GetThreadCount();
1250  const size_t stack_size = mark_stack_->Size();
1251  const size_t chunk_size =
1252      std::min((stack_size + num_threads - 1) / num_threads,
1253               static_cast<size_t>(MarkStackChunk::max_size));
1254  size_t index = 0;
1255  for (size_t i = 0; i < num_threads || index < stack_size; ++i) {
1256    Object** begin = &mark_stack_->Begin()[std::min(stack_size, index)];
1257    Object** end = &mark_stack_->Begin()[std::min(stack_size, index + chunk_size)];
1258    index += chunk_size;
1259    thread_pool->AddTask(self, new MarkStackChunk(thread_pool, this, begin, end));
1260  }
1261  thread_pool->StartWorkers(self);
1262  thread_pool->Wait(self, true, true);
1263  mark_stack_->Reset();
1264  //LOG(INFO) << "Idle wait time " << PrettyDuration(thread_pool->GetWaitTime());
1265  CHECK_EQ(work_chunks_created_, work_chunks_deleted_) << " some of the work chunks were leaked";
1266}
1267
1268// Scan anything that's on the mark stack.
1269void MarkSweep::ProcessMarkStack() {
1270  ThreadPool* thread_pool = GetHeap()->GetThreadPool();
1271  if (kParallelMarkStack && thread_pool != NULL && thread_pool->GetThreadCount() > 0) {
1272    ProcessMarkStackParallel();
1273    return;
1274  }
1275
1276  if (kUseMarkStackPrefetch) {
1277    const size_t fifo_size = 4;
1278    const size_t fifo_mask = fifo_size - 1;
1279    const Object* fifo[fifo_size];
1280    for (size_t i = 0;i < fifo_size;++i) {
1281      fifo[i] = NULL;
1282    }
1283    size_t fifo_pos = 0;
1284    size_t fifo_count = 0;
1285    for (;;) {
1286      const Object* obj = fifo[fifo_pos & fifo_mask];
1287      if (obj != NULL) {
1288        ScanObject(obj);
1289        fifo[fifo_pos & fifo_mask] = NULL;
1290        --fifo_count;
1291      }
1292
1293      if (!mark_stack_->IsEmpty()) {
1294        const Object* obj = mark_stack_->PopBack();
1295        DCHECK(obj != NULL);
1296        fifo[fifo_pos & fifo_mask] = obj;
1297        __builtin_prefetch(obj);
1298        fifo_count++;
1299      }
1300      fifo_pos++;
1301
1302      if (!fifo_count) {
1303        CHECK(mark_stack_->IsEmpty()) << mark_stack_->Size();
1304        break;
1305      }
1306    }
1307  } else {
1308    while (!mark_stack_->IsEmpty()) {
1309      const Object* obj = mark_stack_->PopBack();
1310      DCHECK(obj != NULL);
1311      ScanObject(obj);
1312    }
1313  }
1314}
1315
1316// Walks the reference list marking any references subject to the
1317// reference clearing policy.  References with a black referent are
1318// removed from the list.  References with white referents biased
1319// toward saving are blackened and also removed from the list.
1320void MarkSweep::PreserveSomeSoftReferences(Object** list) {
1321  DCHECK(list != NULL);
1322  Object* clear = NULL;
1323  size_t counter = 0;
1324
1325  DCHECK(mark_stack_->IsEmpty());
1326
1327  while (*list != NULL) {
1328    Object* ref = heap_->DequeuePendingReference(list);
1329    Object* referent = heap_->GetReferenceReferent(ref);
1330    if (referent == NULL) {
1331      // Referent was cleared by the user during marking.
1332      continue;
1333    }
1334    bool is_marked = IsMarked(referent);
1335    if (!is_marked && ((++counter) & 1)) {
1336      // Referent is white and biased toward saving, mark it.
1337      MarkObject(referent);
1338      is_marked = true;
1339    }
1340    if (!is_marked) {
1341      // Referent is white, queue it for clearing.
1342      heap_->EnqueuePendingReference(ref, &clear);
1343    }
1344  }
1345  *list = clear;
1346  // Restart the mark with the newly black references added to the
1347  // root set.
1348  ProcessMarkStack();
1349}
1350
1351inline bool MarkSweep::IsMarked(const Object* object) const
1352    SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
1353  if (object >= immune_begin_ && object < immune_end_) {
1354    return true;
1355  }
1356  DCHECK(current_mark_bitmap_ != NULL);
1357  if (current_mark_bitmap_->HasAddress(object)) {
1358    return current_mark_bitmap_->Test(object);
1359  }
1360  return heap_->GetMarkBitmap()->Test(object);
1361}
1362
1363
1364// Unlink the reference list clearing references objects with white
1365// referents.  Cleared references registered to a reference queue are
1366// scheduled for appending by the heap worker thread.
1367void MarkSweep::ClearWhiteReferences(Object** list) {
1368  DCHECK(list != NULL);
1369  while (*list != NULL) {
1370    Object* ref = heap_->DequeuePendingReference(list);
1371    Object* referent = heap_->GetReferenceReferent(ref);
1372    if (referent != NULL && !IsMarked(referent)) {
1373      // Referent is white, clear it.
1374      heap_->ClearReferenceReferent(ref);
1375      if (heap_->IsEnqueuable(ref)) {
1376        heap_->EnqueueReference(ref, &cleared_reference_list_);
1377      }
1378    }
1379  }
1380  DCHECK(*list == NULL);
1381}
1382
1383// Enqueues finalizer references with white referents.  White
1384// referents are blackened, moved to the zombie field, and the
1385// referent field is cleared.
1386void MarkSweep::EnqueueFinalizerReferences(Object** list) {
1387  DCHECK(list != NULL);
1388  MemberOffset zombie_offset = heap_->GetFinalizerReferenceZombieOffset();
1389  bool has_enqueued = false;
1390  while (*list != NULL) {
1391    Object* ref = heap_->DequeuePendingReference(list);
1392    Object* referent = heap_->GetReferenceReferent(ref);
1393    if (referent != NULL && !IsMarked(referent)) {
1394      MarkObject(referent);
1395      // If the referent is non-null the reference must queuable.
1396      DCHECK(heap_->IsEnqueuable(ref));
1397      ref->SetFieldObject(zombie_offset, referent, false);
1398      heap_->ClearReferenceReferent(ref);
1399      heap_->EnqueueReference(ref, &cleared_reference_list_);
1400      has_enqueued = true;
1401    }
1402  }
1403  if (has_enqueued) {
1404    ProcessMarkStack();
1405  }
1406  DCHECK(*list == NULL);
1407}
1408
1409// Process reference class instances and schedule finalizations.
1410void MarkSweep::ProcessReferences(Object** soft_references, bool clear_soft,
1411                                  Object** weak_references,
1412                                  Object** finalizer_references,
1413                                  Object** phantom_references) {
1414  DCHECK(soft_references != NULL);
1415  DCHECK(weak_references != NULL);
1416  DCHECK(finalizer_references != NULL);
1417  DCHECK(phantom_references != NULL);
1418
1419  // Unless we are in the zygote or required to clear soft references
1420  // with white references, preserve some white referents.
1421  if (!clear_soft && !Runtime::Current()->IsZygote()) {
1422    PreserveSomeSoftReferences(soft_references);
1423  }
1424
1425  // Clear all remaining soft and weak references with white
1426  // referents.
1427  ClearWhiteReferences(soft_references);
1428  ClearWhiteReferences(weak_references);
1429
1430  // Preserve all white objects with finalize methods and schedule
1431  // them for finalization.
1432  EnqueueFinalizerReferences(finalizer_references);
1433
1434  // Clear all f-reachable soft and weak references with white
1435  // referents.
1436  ClearWhiteReferences(soft_references);
1437  ClearWhiteReferences(weak_references);
1438
1439  // Clear all phantom references with white referents.
1440  ClearWhiteReferences(phantom_references);
1441
1442  // At this point all reference lists should be empty.
1443  DCHECK(*soft_references == NULL);
1444  DCHECK(*weak_references == NULL);
1445  DCHECK(*finalizer_references == NULL);
1446  DCHECK(*phantom_references == NULL);
1447}
1448
1449void MarkSweep::UnBindBitmaps() {
1450  const std::vector<space::ContinuousSpace*>& spaces = GetHeap()->GetContinuousSpaces();
1451  // TODO: C++0x
1452  typedef std::vector<space::ContinuousSpace*>::const_iterator It;
1453  for (It it = spaces.begin(), end = spaces.end(); it != end; ++it) {
1454    space::ContinuousSpace* space = *it;
1455    if (space->IsDlMallocSpace()) {
1456      space::DlMallocSpace* alloc_space = space->AsDlMallocSpace();
1457      if (alloc_space->temp_bitmap_.get() != NULL) {
1458        // At this point, the temp_bitmap holds our old mark bitmap.
1459        accounting::SpaceBitmap* new_bitmap = alloc_space->temp_bitmap_.release();
1460        GetHeap()->GetMarkBitmap()->ReplaceBitmap(alloc_space->mark_bitmap_.get(), new_bitmap);
1461        CHECK_EQ(alloc_space->mark_bitmap_.release(), alloc_space->live_bitmap_.get());
1462        alloc_space->mark_bitmap_.reset(new_bitmap);
1463        DCHECK(alloc_space->temp_bitmap_.get() == NULL);
1464      }
1465    }
1466  }
1467}
1468
1469void MarkSweep::FinishPhase() {
1470  // Can't enqueue referneces if we hold the mutator lock.
1471  Object* cleared_references = GetClearedReferences();
1472  Heap* heap = GetHeap();
1473  heap->EnqueueClearedReferences(&cleared_references);
1474
1475  heap->PostGcVerification(this);
1476
1477  timings_.NewSplit("GrowForUtilization");
1478  heap->GrowForUtilization(GetGcType(), GetDurationNs());
1479
1480  timings_.NewSplit("RequestHeapTrim");
1481  heap->RequestHeapTrim();
1482
1483  // Update the cumulative statistics
1484  total_time_ns_ += GetDurationNs();
1485  total_paused_time_ns_ += std::accumulate(GetPauseTimes().begin(), GetPauseTimes().end(), 0,
1486                                           std::plus<uint64_t>());
1487  total_freed_objects_ += GetFreedObjects();
1488  total_freed_bytes_ += GetFreedBytes();
1489
1490  // Ensure that the mark stack is empty.
1491  CHECK(mark_stack_->IsEmpty());
1492
1493  if (kCountScannedTypes) {
1494    VLOG(gc) << "MarkSweep scanned classes=" << class_count_ << " arrays=" << array_count_
1495             << " other=" << other_count_;
1496  }
1497
1498  if (kCountTasks) {
1499    VLOG(gc) << "Total number of work chunks allocated: " << work_chunks_created_;
1500  }
1501
1502  if (kMeasureOverhead) {
1503    VLOG(gc) << "Overhead time " << PrettyDuration(overhead_time_);
1504  }
1505
1506  if (kProfileLargeObjects) {
1507    VLOG(gc) << "Large objects tested " << large_object_test_ << " marked " << large_object_mark_;
1508  }
1509
1510  if (kCountClassesMarked) {
1511    VLOG(gc) << "Classes marked " << classes_marked_;
1512  }
1513
1514  if (kCountJavaLangRefs) {
1515    VLOG(gc) << "References scanned " << reference_count_;
1516  }
1517
1518  // Update the cumulative loggers.
1519  cumulative_timings_.Start();
1520  cumulative_timings_.AddNewLogger(timings_);
1521  cumulative_timings_.End();
1522
1523  // Clear all of the spaces' mark bitmaps.
1524  const std::vector<space::ContinuousSpace*>& spaces = GetHeap()->GetContinuousSpaces();
1525  // TODO: C++0x
1526  typedef std::vector<space::ContinuousSpace*>::const_iterator It;
1527  for (It it = spaces.begin(), end = spaces.end(); it != end; ++it) {
1528    space::ContinuousSpace* space = *it;
1529    if (space->GetGcRetentionPolicy() != space::kGcRetentionPolicyNeverCollect) {
1530      space->GetMarkBitmap()->Clear();
1531    }
1532  }
1533  mark_stack_->Reset();
1534
1535  // Reset the marked large objects.
1536  space::LargeObjectSpace* large_objects = GetHeap()->GetLargeObjectsSpace();
1537  large_objects->GetMarkObjects()->Clear();
1538}
1539
1540}  // namespace collector
1541}  // namespace gc
1542}  // namespace art
1543