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