mark_sweep.cc revision cb535da36915f9d10bec3880b46f1de1f7a69f22
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#define ATRACE_TAG ATRACE_TAG_DALVIK
25#include "cutils/trace.h"
26
27#include "base/bounded_fifo.h"
28#include "base/logging.h"
29#include "base/macros.h"
30#include "base/mutex-inl.h"
31#include "base/timing_logger.h"
32#include "gc/accounting/card_table-inl.h"
33#include "gc/accounting/heap_bitmap-inl.h"
34#include "gc/accounting/mod_union_table.h"
35#include "gc/accounting/space_bitmap-inl.h"
36#include "gc/heap.h"
37#include "gc/reference_processor.h"
38#include "gc/space/image_space.h"
39#include "gc/space/large_object_space.h"
40#include "gc/space/space-inl.h"
41#include "mark_sweep-inl.h"
42#include "mirror/art_field-inl.h"
43#include "mirror/object-inl.h"
44#include "runtime.h"
45#include "scoped_thread_state_change.h"
46#include "thread-inl.h"
47#include "thread_list.h"
48
49using ::art::mirror::Object;
50
51namespace art {
52namespace gc {
53namespace collector {
54
55// Performance options.
56static constexpr bool kUseRecursiveMark = false;
57static constexpr bool kUseMarkStackPrefetch = true;
58static constexpr size_t kSweepArrayChunkFreeSize = 1024;
59static constexpr bool kPreCleanCards = true;
60
61// Parallelism options.
62static constexpr bool kParallelCardScan = true;
63static constexpr bool kParallelRecursiveMark = true;
64// Don't attempt to parallelize mark stack processing unless the mark stack is at least n
65// elements. This is temporary until we reduce the overhead caused by allocating tasks, etc.. Not
66// having this can add overhead in ProcessReferences since we may end up doing many calls of
67// ProcessMarkStack with very small mark stacks.
68static constexpr size_t kMinimumParallelMarkStackSize = 128;
69static constexpr bool kParallelProcessMarkStack = true;
70
71// Profiling and information flags.
72static constexpr bool kProfileLargeObjects = false;
73static constexpr bool kMeasureOverhead = false;
74static constexpr bool kCountTasks = false;
75static constexpr bool kCountJavaLangRefs = false;
76static constexpr bool kCountMarkedObjects = false;
77
78// Turn off kCheckLocks when profiling the GC since it slows the GC down by up to 40%.
79static constexpr bool kCheckLocks = kDebugLocking;
80static constexpr bool kVerifyRootsMarked = kIsDebugBuild;
81
82// If true, revoke the rosalloc thread-local buffers at the
83// checkpoint, as opposed to during the pause.
84static constexpr bool kRevokeRosAllocThreadLocalBuffersAtCheckpoint = true;
85
86void MarkSweep::BindBitmaps() {
87  TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
88  WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
89  // Mark all of the spaces we never collect as immune.
90  for (const auto& space : GetHeap()->GetContinuousSpaces()) {
91    if (space->GetGcRetentionPolicy() == space::kGcRetentionPolicyNeverCollect) {
92      CHECK(immune_region_.AddContinuousSpace(space)) << "Failed to add space " << *space;
93    }
94  }
95}
96
97MarkSweep::MarkSweep(Heap* heap, bool is_concurrent, const std::string& name_prefix)
98    : GarbageCollector(heap,
99                       name_prefix +
100                       (is_concurrent ? "concurrent mark sweep": "mark sweep")),
101      current_space_bitmap_(nullptr), mark_bitmap_(nullptr), mark_stack_(nullptr),
102      gc_barrier_(new Barrier(0)),
103      mark_stack_lock_("mark sweep mark stack lock", kMarkSweepMarkStackLock),
104      is_concurrent_(is_concurrent), live_stack_freeze_size_(0) {
105  std::string error_msg;
106  MemMap* mem_map = MemMap::MapAnonymous(
107      "mark sweep sweep array free buffer", nullptr,
108      RoundUp(kSweepArrayChunkFreeSize * sizeof(mirror::Object*), kPageSize),
109      PROT_READ | PROT_WRITE, false, &error_msg);
110  CHECK(mem_map != nullptr) << "Couldn't allocate sweep array free buffer: " << error_msg;
111  sweep_array_free_buffer_mem_map_.reset(mem_map);
112}
113
114void MarkSweep::InitializePhase() {
115  TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
116  mark_stack_ = heap_->GetMarkStack();
117  DCHECK(mark_stack_ != nullptr);
118  immune_region_.Reset();
119  class_count_.StoreRelaxed(0);
120  array_count_.StoreRelaxed(0);
121  other_count_.StoreRelaxed(0);
122  large_object_test_.StoreRelaxed(0);
123  large_object_mark_.StoreRelaxed(0);
124  overhead_time_ .StoreRelaxed(0);
125  work_chunks_created_.StoreRelaxed(0);
126  work_chunks_deleted_.StoreRelaxed(0);
127  reference_count_.StoreRelaxed(0);
128  mark_null_count_.StoreRelaxed(0);
129  mark_immune_count_.StoreRelaxed(0);
130  mark_fastpath_count_.StoreRelaxed(0);
131  mark_slowpath_count_.StoreRelaxed(0);
132  {
133    // TODO: I don't think we should need heap bitmap lock to Get the mark bitmap.
134    ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
135    mark_bitmap_ = heap_->GetMarkBitmap();
136  }
137  if (!GetCurrentIteration()->GetClearSoftReferences()) {
138    // Always clear soft references if a non-sticky collection.
139    GetCurrentIteration()->SetClearSoftReferences(GetGcType() != collector::kGcTypeSticky);
140  }
141}
142
143void MarkSweep::RunPhases() {
144  Thread* self = Thread::Current();
145  InitializePhase();
146  Locks::mutator_lock_->AssertNotHeld(self);
147  if (IsConcurrent()) {
148    GetHeap()->PreGcVerification(this);
149    {
150      ReaderMutexLock mu(self, *Locks::mutator_lock_);
151      MarkingPhase();
152    }
153    ScopedPause pause(this);
154    GetHeap()->PrePauseRosAllocVerification(this);
155    PausePhase();
156    RevokeAllThreadLocalBuffers();
157  } else {
158    ScopedPause pause(this);
159    GetHeap()->PreGcVerificationPaused(this);
160    MarkingPhase();
161    GetHeap()->PrePauseRosAllocVerification(this);
162    PausePhase();
163    RevokeAllThreadLocalBuffers();
164  }
165  {
166    // Sweeping always done concurrently, even for non concurrent mark sweep.
167    ReaderMutexLock mu(self, *Locks::mutator_lock_);
168    ReclaimPhase();
169  }
170  GetHeap()->PostGcVerification(this);
171  FinishPhase();
172}
173
174void MarkSweep::ProcessReferences(Thread* self) {
175  WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
176  GetHeap()->GetReferenceProcessor()->ProcessReferences(
177      true, GetTimings(), GetCurrentIteration()->GetClearSoftReferences(),
178      &HeapReferenceMarkedCallback, &MarkObjectCallback, &ProcessMarkStackCallback, this);
179}
180
181void MarkSweep::PausePhase() {
182  TimingLogger::ScopedTiming t("(Paused)PausePhase", GetTimings());
183  Thread* self = Thread::Current();
184  Locks::mutator_lock_->AssertExclusiveHeld(self);
185  if (IsConcurrent()) {
186    // Handle the dirty objects if we are a concurrent GC.
187    WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
188    // Re-mark root set.
189    ReMarkRoots();
190    // Scan dirty objects, this is only required if we are not doing concurrent GC.
191    RecursiveMarkDirtyObjects(true, accounting::CardTable::kCardDirty);
192  }
193  {
194    TimingLogger::ScopedTiming t2("SwapStacks", GetTimings());
195    WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
196    heap_->SwapStacks(self);
197    live_stack_freeze_size_ = heap_->GetLiveStack()->Size();
198    // Need to revoke all the thread local allocation stacks since we just swapped the allocation
199    // stacks and don't want anybody to allocate into the live stack.
200    RevokeAllThreadLocalAllocationStacks(self);
201  }
202  heap_->PreSweepingGcVerification(this);
203  // Disallow new system weaks to prevent a race which occurs when someone adds a new system
204  // weak before we sweep them. Since this new system weak may not be marked, the GC may
205  // incorrectly sweep it. This also fixes a race where interning may attempt to return a strong
206  // reference to a string that is about to be swept.
207  Runtime::Current()->DisallowNewSystemWeaks();
208  // Enable the reference processing slow path, needs to be done with mutators paused since there
209  // is no lock in the GetReferent fast path.
210  GetHeap()->GetReferenceProcessor()->EnableSlowPath();
211}
212
213void MarkSweep::PreCleanCards() {
214  // Don't do this for non concurrent GCs since they don't have any dirty cards.
215  if (kPreCleanCards && IsConcurrent()) {
216    TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
217    Thread* self = Thread::Current();
218    CHECK(!Locks::mutator_lock_->IsExclusiveHeld(self));
219    // Process dirty cards and add dirty cards to mod union tables, also ages cards.
220    heap_->ProcessCards(GetTimings(), false);
221    // The checkpoint root marking is required to avoid a race condition which occurs if the
222    // following happens during a reference write:
223    // 1. mutator dirties the card (write barrier)
224    // 2. GC ages the card (the above ProcessCards call)
225    // 3. GC scans the object (the RecursiveMarkDirtyObjects call below)
226    // 4. mutator writes the value (corresponding to the write barrier in 1.)
227    // This causes the GC to age the card but not necessarily mark the reference which the mutator
228    // wrote into the object stored in the card.
229    // Having the checkpoint fixes this issue since it ensures that the card mark and the
230    // reference write are visible to the GC before the card is scanned (this is due to locks being
231    // acquired / released in the checkpoint code).
232    // The other roots are also marked to help reduce the pause.
233    MarkRootsCheckpoint(self, false);
234    MarkNonThreadRoots();
235    MarkConcurrentRoots(
236        static_cast<VisitRootFlags>(kVisitRootFlagClearRootLog | kVisitRootFlagNewRoots));
237    // Process the newly aged cards.
238    RecursiveMarkDirtyObjects(false, accounting::CardTable::kCardDirty - 1);
239    // TODO: Empty allocation stack to reduce the number of objects we need to test / mark as live
240    // in the next GC.
241  }
242}
243
244void MarkSweep::RevokeAllThreadLocalAllocationStacks(Thread* self) {
245  if (kUseThreadLocalAllocationStack) {
246    TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
247    Locks::mutator_lock_->AssertExclusiveHeld(self);
248    heap_->RevokeAllThreadLocalAllocationStacks(self);
249  }
250}
251
252void MarkSweep::MarkingPhase() {
253  TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
254  Thread* self = Thread::Current();
255  BindBitmaps();
256  FindDefaultSpaceBitmap();
257  // Process dirty cards and add dirty cards to mod union tables.
258  heap_->ProcessCards(GetTimings(), false);
259  WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
260  MarkRoots(self);
261  MarkReachableObjects();
262  // Pre-clean dirtied cards to reduce pauses.
263  PreCleanCards();
264}
265
266void MarkSweep::UpdateAndMarkModUnion() {
267  for (const auto& space : heap_->GetContinuousSpaces()) {
268    if (immune_region_.ContainsSpace(space)) {
269      const char* name = space->IsZygoteSpace() ? "UpdateAndMarkZygoteModUnionTable" :
270          "UpdateAndMarkImageModUnionTable";
271      TimingLogger::ScopedTiming t(name, GetTimings());
272      accounting::ModUnionTable* mod_union_table = heap_->FindModUnionTableFromSpace(space);
273      CHECK(mod_union_table != nullptr);
274      mod_union_table->UpdateAndMarkReferences(MarkHeapReferenceCallback, this);
275    }
276  }
277}
278
279void MarkSweep::MarkReachableObjects() {
280  UpdateAndMarkModUnion();
281  // Recursively mark all the non-image bits set in the mark bitmap.
282  RecursiveMark();
283}
284
285void MarkSweep::ReclaimPhase() {
286  TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
287  Thread* self = Thread::Current();
288  // Process the references concurrently.
289  ProcessReferences(self);
290  SweepSystemWeaks(self);
291  Runtime::Current()->AllowNewSystemWeaks();
292  {
293    WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
294    // Reclaim unmarked objects.
295    Sweep(false);
296    // Swap the live and mark bitmaps for each space which we modified space. This is an
297    // optimization that enables us to not clear live bits inside of the sweep. Only swaps unbound
298    // bitmaps.
299    SwapBitmaps();
300    // Unbind the live and mark bitmaps.
301    GetHeap()->UnBindBitmaps();
302  }
303}
304
305void MarkSweep::FindDefaultSpaceBitmap() {
306  TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
307  for (const auto& space : GetHeap()->GetContinuousSpaces()) {
308    accounting::ContinuousSpaceBitmap* bitmap = space->GetMarkBitmap();
309    // We want to have the main space instead of non moving if possible.
310    if (bitmap != nullptr &&
311        space->GetGcRetentionPolicy() == space::kGcRetentionPolicyAlwaysCollect) {
312      current_space_bitmap_ = bitmap;
313      // If we are not the non moving space exit the loop early since this will be good enough.
314      if (space != heap_->GetNonMovingSpace()) {
315        break;
316      }
317    }
318  }
319  CHECK(current_space_bitmap_ != nullptr) << "Could not find a default mark bitmap\n"
320      << heap_->DumpSpaces();
321}
322
323void MarkSweep::ExpandMarkStack() {
324  ResizeMarkStack(mark_stack_->Capacity() * 2);
325}
326
327void MarkSweep::ResizeMarkStack(size_t new_size) {
328  // Rare case, no need to have Thread::Current be a parameter.
329  if (UNLIKELY(mark_stack_->Size() < mark_stack_->Capacity())) {
330    // Someone else acquired the lock and expanded the mark stack before us.
331    return;
332  }
333  std::vector<StackReference<Object>> temp(mark_stack_->Begin(), mark_stack_->End());
334  CHECK_LE(mark_stack_->Size(), new_size);
335  mark_stack_->Resize(new_size);
336  for (auto& obj : temp) {
337    mark_stack_->PushBack(obj.AsMirrorPtr());
338  }
339}
340
341inline void MarkSweep::MarkObjectNonNullParallel(Object* obj) {
342  DCHECK(obj != nullptr);
343  if (MarkObjectParallel(obj)) {
344    MutexLock mu(Thread::Current(), mark_stack_lock_);
345    if (UNLIKELY(mark_stack_->Size() >= mark_stack_->Capacity())) {
346      ExpandMarkStack();
347    }
348    // The object must be pushed on to the mark stack.
349    mark_stack_->PushBack(obj);
350  }
351}
352
353mirror::Object* MarkSweep::MarkObjectCallback(mirror::Object* obj, void* arg) {
354  MarkSweep* mark_sweep = reinterpret_cast<MarkSweep*>(arg);
355  mark_sweep->MarkObject(obj);
356  return obj;
357}
358
359void MarkSweep::MarkHeapReferenceCallback(mirror::HeapReference<mirror::Object>* ref, void* arg) {
360  reinterpret_cast<MarkSweep*>(arg)->MarkObject(ref->AsMirrorPtr());
361}
362
363bool MarkSweep::HeapReferenceMarkedCallback(mirror::HeapReference<mirror::Object>* ref, void* arg) {
364  return reinterpret_cast<MarkSweep*>(arg)->IsMarked(ref->AsMirrorPtr());
365}
366
367class MarkSweepMarkObjectSlowPath {
368 public:
369  explicit MarkSweepMarkObjectSlowPath(MarkSweep* mark_sweep) : mark_sweep_(mark_sweep) {
370  }
371
372  void operator()(const Object* obj) const ALWAYS_INLINE {
373    if (kProfileLargeObjects) {
374      // TODO: Differentiate between marking and testing somehow.
375      ++mark_sweep_->large_object_test_;
376      ++mark_sweep_->large_object_mark_;
377    }
378    space::LargeObjectSpace* large_object_space = mark_sweep_->GetHeap()->GetLargeObjectsSpace();
379    if (UNLIKELY(obj == nullptr || !IsAligned<kPageSize>(obj) ||
380                 (kIsDebugBuild && large_object_space != nullptr &&
381                     !large_object_space->Contains(obj)))) {
382      LOG(ERROR) << "Tried to mark " << obj << " not contained by any spaces";
383      LOG(ERROR) << "Attempting see if it's a bad root";
384      mark_sweep_->VerifyRoots();
385      LOG(FATAL) << "Can't mark invalid object";
386    }
387  }
388
389 private:
390  MarkSweep* const mark_sweep_;
391};
392
393inline void MarkSweep::MarkObjectNonNull(Object* obj) {
394  DCHECK(obj != nullptr);
395  if (kUseBakerOrBrooksReadBarrier) {
396    // Verify all the objects have the correct pointer installed.
397    obj->AssertReadBarrierPointer();
398  }
399  if (immune_region_.ContainsObject(obj)) {
400    if (kCountMarkedObjects) {
401      ++mark_immune_count_;
402    }
403    DCHECK(mark_bitmap_->Test(obj));
404  } else if (LIKELY(current_space_bitmap_->HasAddress(obj))) {
405    if (kCountMarkedObjects) {
406      ++mark_fastpath_count_;
407    }
408    if (UNLIKELY(!current_space_bitmap_->Set(obj))) {
409      PushOnMarkStack(obj);  // This object was not previously marked.
410    }
411  } else {
412    if (kCountMarkedObjects) {
413      ++mark_slowpath_count_;
414    }
415    MarkSweepMarkObjectSlowPath visitor(this);
416    // TODO: We already know that the object is not in the current_space_bitmap_ but MarkBitmap::Set
417    // will check again.
418    if (!mark_bitmap_->Set(obj, visitor)) {
419      PushOnMarkStack(obj);  // Was not already marked, push.
420    }
421  }
422}
423
424inline void MarkSweep::PushOnMarkStack(Object* obj) {
425  if (UNLIKELY(mark_stack_->Size() >= mark_stack_->Capacity())) {
426    // Lock is not needed but is here anyways to please annotalysis.
427    MutexLock mu(Thread::Current(), mark_stack_lock_);
428    ExpandMarkStack();
429  }
430  // The object must be pushed on to the mark stack.
431  mark_stack_->PushBack(obj);
432}
433
434inline bool MarkSweep::MarkObjectParallel(const Object* obj) {
435  DCHECK(obj != nullptr);
436  if (kUseBakerOrBrooksReadBarrier) {
437    // Verify all the objects have the correct pointer installed.
438    obj->AssertReadBarrierPointer();
439  }
440  if (immune_region_.ContainsObject(obj)) {
441    DCHECK(IsMarked(obj));
442    return false;
443  }
444  // Try to take advantage of locality of references within a space, failing this find the space
445  // the hard way.
446  accounting::ContinuousSpaceBitmap* object_bitmap = current_space_bitmap_;
447  if (LIKELY(object_bitmap->HasAddress(obj))) {
448    return !object_bitmap->AtomicTestAndSet(obj);
449  }
450  MarkSweepMarkObjectSlowPath visitor(this);
451  return !mark_bitmap_->AtomicTestAndSet(obj, visitor);
452}
453
454// Used to mark objects when processing the mark stack. If an object is null, it is not marked.
455inline void MarkSweep::MarkObject(Object* obj) {
456  if (obj != nullptr) {
457    MarkObjectNonNull(obj);
458  } else if (kCountMarkedObjects) {
459    ++mark_null_count_;
460  }
461}
462
463void MarkSweep::MarkRootParallelCallback(Object** root, void* arg, const RootInfo& /*root_info*/) {
464  reinterpret_cast<MarkSweep*>(arg)->MarkObjectNonNullParallel(*root);
465}
466
467void MarkSweep::VerifyRootMarked(Object** root, void* arg, const RootInfo& /*root_info*/) {
468  CHECK(reinterpret_cast<MarkSweep*>(arg)->IsMarked(*root));
469}
470
471void MarkSweep::MarkRootCallback(Object** root, void* arg, const RootInfo& /*root_info*/) {
472  reinterpret_cast<MarkSweep*>(arg)->MarkObjectNonNull(*root);
473}
474
475void MarkSweep::VerifyRootCallback(Object** root, void* arg, const RootInfo& root_info) {
476  reinterpret_cast<MarkSweep*>(arg)->VerifyRoot(*root, root_info);
477}
478
479void MarkSweep::VerifyRoot(const Object* root, const RootInfo& root_info) {
480  // See if the root is on any space bitmap.
481  if (heap_->GetLiveBitmap()->GetContinuousSpaceBitmap(root) == nullptr) {
482    space::LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
483    if (large_object_space != nullptr && !large_object_space->Contains(root)) {
484      LOG(ERROR) << "Found invalid root: " << root << " ";
485      root_info.Describe(LOG(ERROR));
486    }
487  }
488}
489
490void MarkSweep::VerifyRoots() {
491  Runtime::Current()->GetThreadList()->VisitRoots(VerifyRootCallback, this);
492}
493
494void MarkSweep::MarkRoots(Thread* self) {
495  TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
496  if (Locks::mutator_lock_->IsExclusiveHeld(self)) {
497    // If we exclusively hold the mutator lock, all threads must be suspended.
498    Runtime::Current()->VisitRoots(MarkRootCallback, this);
499    RevokeAllThreadLocalAllocationStacks(self);
500  } else {
501    MarkRootsCheckpoint(self, kRevokeRosAllocThreadLocalBuffersAtCheckpoint);
502    // At this point the live stack should no longer have any mutators which push into it.
503    MarkNonThreadRoots();
504    MarkConcurrentRoots(
505        static_cast<VisitRootFlags>(kVisitRootFlagAllRoots | kVisitRootFlagStartLoggingNewRoots));
506  }
507}
508
509void MarkSweep::MarkNonThreadRoots() {
510  TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
511  Runtime::Current()->VisitNonThreadRoots(MarkRootCallback, this);
512}
513
514void MarkSweep::MarkConcurrentRoots(VisitRootFlags flags) {
515  TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
516  // Visit all runtime roots and clear dirty flags.
517  Runtime::Current()->VisitConcurrentRoots(MarkRootCallback, this, flags);
518}
519
520class ScanObjectVisitor {
521 public:
522  explicit ScanObjectVisitor(MarkSweep* const mark_sweep) ALWAYS_INLINE
523      : mark_sweep_(mark_sweep) {}
524
525  void operator()(Object* obj) const ALWAYS_INLINE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
526      EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
527    if (kCheckLocks) {
528      Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
529      Locks::heap_bitmap_lock_->AssertExclusiveHeld(Thread::Current());
530    }
531    mark_sweep_->ScanObject(obj);
532  }
533
534 private:
535  MarkSweep* const mark_sweep_;
536};
537
538class DelayReferenceReferentVisitor {
539 public:
540  explicit DelayReferenceReferentVisitor(MarkSweep* collector) : collector_(collector) {
541  }
542
543  void operator()(mirror::Class* klass, mirror::Reference* ref) const
544      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
545      EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
546    collector_->DelayReferenceReferent(klass, ref);
547  }
548
549 private:
550  MarkSweep* const collector_;
551};
552
553template <bool kUseFinger = false>
554class MarkStackTask : public Task {
555 public:
556  MarkStackTask(ThreadPool* thread_pool, MarkSweep* mark_sweep, size_t mark_stack_size,
557                StackReference<Object>* mark_stack)
558      : mark_sweep_(mark_sweep),
559        thread_pool_(thread_pool),
560        mark_stack_pos_(mark_stack_size) {
561    // We may have to copy part of an existing mark stack when another mark stack overflows.
562    if (mark_stack_size != 0) {
563      DCHECK(mark_stack != NULL);
564      // TODO: Check performance?
565      std::copy(mark_stack, mark_stack + mark_stack_size, mark_stack_);
566    }
567    if (kCountTasks) {
568      ++mark_sweep_->work_chunks_created_;
569    }
570  }
571
572  static const size_t kMaxSize = 1 * KB;
573
574 protected:
575  class MarkObjectParallelVisitor {
576   public:
577    explicit MarkObjectParallelVisitor(MarkStackTask<kUseFinger>* chunk_task,
578                                       MarkSweep* mark_sweep) ALWAYS_INLINE
579            : chunk_task_(chunk_task), mark_sweep_(mark_sweep) {}
580
581    void operator()(Object* obj, MemberOffset offset, bool /* static */) const ALWAYS_INLINE
582        SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
583      mirror::Object* ref = obj->GetFieldObject<mirror::Object>(offset);
584      if (ref != nullptr && mark_sweep_->MarkObjectParallel(ref)) {
585        if (kUseFinger) {
586          android_memory_barrier();
587          if (reinterpret_cast<uintptr_t>(ref) >=
588              static_cast<uintptr_t>(mark_sweep_->atomic_finger_.LoadRelaxed())) {
589            return;
590          }
591        }
592        chunk_task_->MarkStackPush(ref);
593      }
594    }
595
596   private:
597    MarkStackTask<kUseFinger>* const chunk_task_;
598    MarkSweep* const mark_sweep_;
599  };
600
601  class ScanObjectParallelVisitor {
602   public:
603    explicit ScanObjectParallelVisitor(MarkStackTask<kUseFinger>* chunk_task) ALWAYS_INLINE
604        : chunk_task_(chunk_task) {}
605
606    // No thread safety analysis since multiple threads will use this visitor.
607    void operator()(Object* obj) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
608        EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
609      MarkSweep* const mark_sweep = chunk_task_->mark_sweep_;
610      MarkObjectParallelVisitor mark_visitor(chunk_task_, mark_sweep);
611      DelayReferenceReferentVisitor ref_visitor(mark_sweep);
612      mark_sweep->ScanObjectVisit(obj, mark_visitor, ref_visitor);
613    }
614
615   private:
616    MarkStackTask<kUseFinger>* const chunk_task_;
617  };
618
619  virtual ~MarkStackTask() {
620    // Make sure that we have cleared our mark stack.
621    DCHECK_EQ(mark_stack_pos_, 0U);
622    if (kCountTasks) {
623      ++mark_sweep_->work_chunks_deleted_;
624    }
625  }
626
627  MarkSweep* const mark_sweep_;
628  ThreadPool* const thread_pool_;
629  // Thread local mark stack for this task.
630  StackReference<Object> mark_stack_[kMaxSize];
631  // Mark stack position.
632  size_t mark_stack_pos_;
633
634  ALWAYS_INLINE void MarkStackPush(Object* obj) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
635    if (UNLIKELY(mark_stack_pos_ == kMaxSize)) {
636      // Mark stack overflow, give 1/2 the stack to the thread pool as a new work task.
637      mark_stack_pos_ /= 2;
638      auto* task = new MarkStackTask(thread_pool_, mark_sweep_, kMaxSize - mark_stack_pos_,
639                                     mark_stack_ + mark_stack_pos_);
640      thread_pool_->AddTask(Thread::Current(), task);
641    }
642    DCHECK(obj != nullptr);
643    DCHECK_LT(mark_stack_pos_, kMaxSize);
644    mark_stack_[mark_stack_pos_++].Assign(obj);
645  }
646
647  virtual void Finalize() {
648    delete this;
649  }
650
651  // Scans all of the objects
652  virtual void Run(Thread* self) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
653      EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
654    UNUSED(self);
655    ScanObjectParallelVisitor visitor(this);
656    // TODO: Tune this.
657    static const size_t kFifoSize = 4;
658    BoundedFifoPowerOfTwo<Object*, kFifoSize> prefetch_fifo;
659    for (;;) {
660      Object* obj = nullptr;
661      if (kUseMarkStackPrefetch) {
662        while (mark_stack_pos_ != 0 && prefetch_fifo.size() < kFifoSize) {
663          Object* const mark_stack_obj = mark_stack_[--mark_stack_pos_].AsMirrorPtr();
664          DCHECK(mark_stack_obj != nullptr);
665          __builtin_prefetch(mark_stack_obj);
666          prefetch_fifo.push_back(mark_stack_obj);
667        }
668        if (UNLIKELY(prefetch_fifo.empty())) {
669          break;
670        }
671        obj = prefetch_fifo.front();
672        prefetch_fifo.pop_front();
673      } else {
674        if (UNLIKELY(mark_stack_pos_ == 0)) {
675          break;
676        }
677        obj = mark_stack_[--mark_stack_pos_].AsMirrorPtr();
678      }
679      DCHECK(obj != nullptr);
680      visitor(obj);
681    }
682  }
683};
684
685class CardScanTask : public MarkStackTask<false> {
686 public:
687  CardScanTask(ThreadPool* thread_pool, MarkSweep* mark_sweep,
688               accounting::ContinuousSpaceBitmap* bitmap,
689               uint8_t* begin, uint8_t* end, uint8_t minimum_age, size_t mark_stack_size,
690               StackReference<Object>* mark_stack_obj, bool clear_card)
691      : MarkStackTask<false>(thread_pool, mark_sweep, mark_stack_size, mark_stack_obj),
692        bitmap_(bitmap),
693        begin_(begin),
694        end_(end),
695        minimum_age_(minimum_age), clear_card_(clear_card) {
696  }
697
698 protected:
699  accounting::ContinuousSpaceBitmap* const bitmap_;
700  uint8_t* const begin_;
701  uint8_t* const end_;
702  const uint8_t minimum_age_;
703  const bool clear_card_;
704
705  virtual void Finalize() {
706    delete this;
707  }
708
709  virtual void Run(Thread* self) NO_THREAD_SAFETY_ANALYSIS {
710    ScanObjectParallelVisitor visitor(this);
711    accounting::CardTable* card_table = mark_sweep_->GetHeap()->GetCardTable();
712    size_t cards_scanned = clear_card_ ?
713                           card_table->Scan<true>(bitmap_, begin_, end_, visitor, minimum_age_) :
714                           card_table->Scan<false>(bitmap_, begin_, end_, visitor, minimum_age_);
715    VLOG(heap) << "Parallel scanning cards " << reinterpret_cast<void*>(begin_) << " - "
716        << reinterpret_cast<void*>(end_) << " = " << cards_scanned;
717    // Finish by emptying our local mark stack.
718    MarkStackTask::Run(self);
719  }
720};
721
722size_t MarkSweep::GetThreadCount(bool paused) const {
723  if (heap_->GetThreadPool() == nullptr || !heap_->CareAboutPauseTimes()) {
724    return 1;
725  }
726  if (paused) {
727    return heap_->GetParallelGCThreadCount() + 1;
728  } else {
729    return heap_->GetConcGCThreadCount() + 1;
730  }
731}
732
733void MarkSweep::ScanGrayObjects(bool paused, uint8_t minimum_age) {
734  accounting::CardTable* card_table = GetHeap()->GetCardTable();
735  ThreadPool* thread_pool = GetHeap()->GetThreadPool();
736  size_t thread_count = GetThreadCount(paused);
737  // The parallel version with only one thread is faster for card scanning, TODO: fix.
738  if (kParallelCardScan && thread_count > 1) {
739    Thread* self = Thread::Current();
740    // Can't have a different split for each space since multiple spaces can have their cards being
741    // scanned at the same time.
742    TimingLogger::ScopedTiming t(paused ? "(Paused)ScanGrayObjects" : __FUNCTION__,
743        GetTimings());
744    // Try to take some of the mark stack since we can pass this off to the worker tasks.
745    StackReference<Object>* mark_stack_begin = mark_stack_->Begin();
746    StackReference<Object>* mark_stack_end = mark_stack_->End();
747    const size_t mark_stack_size = mark_stack_end - mark_stack_begin;
748    // Estimated number of work tasks we will create.
749    const size_t mark_stack_tasks = GetHeap()->GetContinuousSpaces().size() * thread_count;
750    DCHECK_NE(mark_stack_tasks, 0U);
751    const size_t mark_stack_delta = std::min(CardScanTask::kMaxSize / 2,
752                                             mark_stack_size / mark_stack_tasks + 1);
753    for (const auto& space : GetHeap()->GetContinuousSpaces()) {
754      if (space->GetMarkBitmap() == nullptr) {
755        continue;
756      }
757      uint8_t* card_begin = space->Begin();
758      uint8_t* card_end = space->End();
759      // Align up the end address. For example, the image space's end
760      // may not be card-size-aligned.
761      card_end = AlignUp(card_end, accounting::CardTable::kCardSize);
762      DCHECK(IsAligned<accounting::CardTable::kCardSize>(card_begin));
763      DCHECK(IsAligned<accounting::CardTable::kCardSize>(card_end));
764      // Calculate how many bytes of heap we will scan,
765      const size_t address_range = card_end - card_begin;
766      // Calculate how much address range each task gets.
767      const size_t card_delta = RoundUp(address_range / thread_count + 1,
768                                        accounting::CardTable::kCardSize);
769      // If paused and the space is neither zygote nor image space, we could clear the dirty
770      // cards to avoid accumulating them to increase card scanning load in the following GC
771      // cycles. We need to keep dirty cards of image space and zygote space in order to track
772      // references to the other spaces.
773      bool clear_card = paused && !space->IsZygoteSpace() && !space->IsImageSpace();
774      // Create the worker tasks for this space.
775      while (card_begin != card_end) {
776        // Add a range of cards.
777        size_t addr_remaining = card_end - card_begin;
778        size_t card_increment = std::min(card_delta, addr_remaining);
779        // Take from the back of the mark stack.
780        size_t mark_stack_remaining = mark_stack_end - mark_stack_begin;
781        size_t mark_stack_increment = std::min(mark_stack_delta, mark_stack_remaining);
782        mark_stack_end -= mark_stack_increment;
783        mark_stack_->PopBackCount(static_cast<int32_t>(mark_stack_increment));
784        DCHECK_EQ(mark_stack_end, mark_stack_->End());
785        // Add the new task to the thread pool.
786        auto* task = new CardScanTask(thread_pool, this, space->GetMarkBitmap(), card_begin,
787                                      card_begin + card_increment, minimum_age,
788                                      mark_stack_increment, mark_stack_end, clear_card);
789        thread_pool->AddTask(self, task);
790        card_begin += card_increment;
791      }
792    }
793
794    // Note: the card scan below may dirty new cards (and scan them)
795    // as a side effect when a Reference object is encountered and
796    // queued during the marking. See b/11465268.
797    thread_pool->SetMaxActiveWorkers(thread_count - 1);
798    thread_pool->StartWorkers(self);
799    thread_pool->Wait(self, true, true);
800    thread_pool->StopWorkers(self);
801  } else {
802    for (const auto& space : GetHeap()->GetContinuousSpaces()) {
803      if (space->GetMarkBitmap() != nullptr) {
804        // Image spaces are handled properly since live == marked for them.
805        const char* name = nullptr;
806        switch (space->GetGcRetentionPolicy()) {
807        case space::kGcRetentionPolicyNeverCollect:
808          name = paused ? "(Paused)ScanGrayImageSpaceObjects" : "ScanGrayImageSpaceObjects";
809          break;
810        case space::kGcRetentionPolicyFullCollect:
811          name = paused ? "(Paused)ScanGrayZygoteSpaceObjects" : "ScanGrayZygoteSpaceObjects";
812          break;
813        case space::kGcRetentionPolicyAlwaysCollect:
814          name = paused ? "(Paused)ScanGrayAllocSpaceObjects" : "ScanGrayAllocSpaceObjects";
815          break;
816        default:
817          LOG(FATAL) << "Unreachable";
818          UNREACHABLE();
819        }
820        TimingLogger::ScopedTiming t(name, GetTimings());
821        ScanObjectVisitor visitor(this);
822        bool clear_card = paused && !space->IsZygoteSpace() && !space->IsImageSpace();
823        if (clear_card) {
824          card_table->Scan<true>(space->GetMarkBitmap(), space->Begin(), space->End(), visitor,
825                                 minimum_age);
826        } else {
827          card_table->Scan<false>(space->GetMarkBitmap(), space->Begin(), space->End(), visitor,
828                                  minimum_age);
829        }
830      }
831    }
832  }
833}
834
835class RecursiveMarkTask : public MarkStackTask<false> {
836 public:
837  RecursiveMarkTask(ThreadPool* thread_pool, MarkSweep* mark_sweep,
838                    accounting::ContinuousSpaceBitmap* bitmap, uintptr_t begin, uintptr_t end)
839      : MarkStackTask<false>(thread_pool, mark_sweep, 0, NULL), bitmap_(bitmap), begin_(begin),
840        end_(end) {
841  }
842
843 protected:
844  accounting::ContinuousSpaceBitmap* const bitmap_;
845  const uintptr_t begin_;
846  const uintptr_t end_;
847
848  virtual void Finalize() {
849    delete this;
850  }
851
852  // Scans all of the objects
853  virtual void Run(Thread* self) NO_THREAD_SAFETY_ANALYSIS {
854    ScanObjectParallelVisitor visitor(this);
855    bitmap_->VisitMarkedRange(begin_, end_, visitor);
856    // Finish by emptying our local mark stack.
857    MarkStackTask::Run(self);
858  }
859};
860
861// Populates the mark stack based on the set of marked objects and
862// recursively marks until the mark stack is emptied.
863void MarkSweep::RecursiveMark() {
864  TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
865  // RecursiveMark will build the lists of known instances of the Reference classes. See
866  // DelayReferenceReferent for details.
867  if (kUseRecursiveMark) {
868    const bool partial = GetGcType() == kGcTypePartial;
869    ScanObjectVisitor scan_visitor(this);
870    auto* self = Thread::Current();
871    ThreadPool* thread_pool = heap_->GetThreadPool();
872    size_t thread_count = GetThreadCount(false);
873    const bool parallel = kParallelRecursiveMark && thread_count > 1;
874    mark_stack_->Reset();
875    for (const auto& space : GetHeap()->GetContinuousSpaces()) {
876      if ((space->GetGcRetentionPolicy() == space::kGcRetentionPolicyAlwaysCollect) ||
877          (!partial && space->GetGcRetentionPolicy() == space::kGcRetentionPolicyFullCollect)) {
878        current_space_bitmap_ = space->GetMarkBitmap();
879        if (current_space_bitmap_ == nullptr) {
880          continue;
881        }
882        if (parallel) {
883          // We will use the mark stack the future.
884          // CHECK(mark_stack_->IsEmpty());
885          // This function does not handle heap end increasing, so we must use the space end.
886          uintptr_t begin = reinterpret_cast<uintptr_t>(space->Begin());
887          uintptr_t end = reinterpret_cast<uintptr_t>(space->End());
888          atomic_finger_.StoreRelaxed(AtomicInteger::MaxValue());
889
890          // Create a few worker tasks.
891          const size_t n = thread_count * 2;
892          while (begin != end) {
893            uintptr_t start = begin;
894            uintptr_t delta = (end - begin) / n;
895            delta = RoundUp(delta, KB);
896            if (delta < 16 * KB) delta = end - begin;
897            begin += delta;
898            auto* task = new RecursiveMarkTask(thread_pool, this, current_space_bitmap_, start,
899                                               begin);
900            thread_pool->AddTask(self, task);
901          }
902          thread_pool->SetMaxActiveWorkers(thread_count - 1);
903          thread_pool->StartWorkers(self);
904          thread_pool->Wait(self, true, true);
905          thread_pool->StopWorkers(self);
906        } else {
907          // This function does not handle heap end increasing, so we must use the space end.
908          uintptr_t begin = reinterpret_cast<uintptr_t>(space->Begin());
909          uintptr_t end = reinterpret_cast<uintptr_t>(space->End());
910          current_space_bitmap_->VisitMarkedRange(begin, end, scan_visitor);
911        }
912      }
913    }
914  }
915  ProcessMarkStack(false);
916}
917
918mirror::Object* MarkSweep::IsMarkedCallback(mirror::Object* object, void* arg) {
919  if (reinterpret_cast<MarkSweep*>(arg)->IsMarked(object)) {
920    return object;
921  }
922  return nullptr;
923}
924
925void MarkSweep::RecursiveMarkDirtyObjects(bool paused, uint8_t minimum_age) {
926  ScanGrayObjects(paused, minimum_age);
927  ProcessMarkStack(paused);
928}
929
930void MarkSweep::ReMarkRoots() {
931  TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
932  Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
933  Runtime::Current()->VisitRoots(
934      MarkRootCallback, this, static_cast<VisitRootFlags>(kVisitRootFlagNewRoots |
935                                                          kVisitRootFlagStopLoggingNewRoots |
936                                                          kVisitRootFlagClearRootLog));
937  if (kVerifyRootsMarked) {
938    TimingLogger::ScopedTiming t2("(Paused)VerifyRoots", GetTimings());
939    Runtime::Current()->VisitRoots(VerifyRootMarked, this);
940  }
941}
942
943void MarkSweep::SweepSystemWeaks(Thread* self) {
944  TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
945  WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
946  Runtime::Current()->SweepSystemWeaks(IsMarkedCallback, this);
947}
948
949mirror::Object* MarkSweep::VerifySystemWeakIsLiveCallback(Object* obj, void* arg) {
950  reinterpret_cast<MarkSweep*>(arg)->VerifyIsLive(obj);
951  // We don't actually want to sweep the object, so lets return "marked"
952  return obj;
953}
954
955void MarkSweep::VerifyIsLive(const Object* obj) {
956  if (!heap_->GetLiveBitmap()->Test(obj)) {
957    // TODO: Consider live stack? Has this code bitrotted?
958    CHECK(!heap_->allocation_stack_->Contains(obj))
959        << "Found dead object " << obj << "\n" << heap_->DumpSpaces();
960  }
961}
962
963void MarkSweep::VerifySystemWeaks() {
964  TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
965  // Verify system weaks, uses a special object visitor which returns the input object.
966  Runtime::Current()->SweepSystemWeaks(VerifySystemWeakIsLiveCallback, this);
967}
968
969class CheckpointMarkThreadRoots : public Closure {
970 public:
971  explicit CheckpointMarkThreadRoots(MarkSweep* mark_sweep,
972                                     bool revoke_ros_alloc_thread_local_buffers_at_checkpoint)
973      : mark_sweep_(mark_sweep),
974        revoke_ros_alloc_thread_local_buffers_at_checkpoint_(
975            revoke_ros_alloc_thread_local_buffers_at_checkpoint) {
976  }
977
978  virtual void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
979    ATRACE_BEGIN("Marking thread roots");
980    // Note: self is not necessarily equal to thread since thread may be suspended.
981    Thread* self = Thread::Current();
982    CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
983        << thread->GetState() << " thread " << thread << " self " << self;
984    thread->VisitRoots(MarkSweep::MarkRootParallelCallback, mark_sweep_);
985    ATRACE_END();
986    if (revoke_ros_alloc_thread_local_buffers_at_checkpoint_) {
987      ATRACE_BEGIN("RevokeRosAllocThreadLocalBuffers");
988      mark_sweep_->GetHeap()->RevokeRosAllocThreadLocalBuffers(thread);
989      ATRACE_END();
990    }
991    mark_sweep_->GetBarrier().Pass(self);
992  }
993
994 private:
995  MarkSweep* const mark_sweep_;
996  const bool revoke_ros_alloc_thread_local_buffers_at_checkpoint_;
997};
998
999void MarkSweep::MarkRootsCheckpoint(Thread* self,
1000                                    bool revoke_ros_alloc_thread_local_buffers_at_checkpoint) {
1001  TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
1002  CheckpointMarkThreadRoots check_point(this, revoke_ros_alloc_thread_local_buffers_at_checkpoint);
1003  ThreadList* thread_list = Runtime::Current()->GetThreadList();
1004  // Request the check point is run on all threads returning a count of the threads that must
1005  // run through the barrier including self.
1006  size_t barrier_count = thread_list->RunCheckpoint(&check_point);
1007  // Release locks then wait for all mutator threads to pass the barrier.
1008  // TODO: optimize to not release locks when there are no threads to wait for.
1009  Locks::heap_bitmap_lock_->ExclusiveUnlock(self);
1010  Locks::mutator_lock_->SharedUnlock(self);
1011  {
1012    ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
1013    gc_barrier_->Increment(self, barrier_count);
1014  }
1015  Locks::mutator_lock_->SharedLock(self);
1016  Locks::heap_bitmap_lock_->ExclusiveLock(self);
1017}
1018
1019void MarkSweep::SweepArray(accounting::ObjectStack* allocations, bool swap_bitmaps) {
1020  TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
1021  Thread* self = Thread::Current();
1022  mirror::Object** chunk_free_buffer = reinterpret_cast<mirror::Object**>(
1023      sweep_array_free_buffer_mem_map_->BaseBegin());
1024  size_t chunk_free_pos = 0;
1025  ObjectBytePair freed;
1026  ObjectBytePair freed_los;
1027  // How many objects are left in the array, modified after each space is swept.
1028  StackReference<Object>* objects = allocations->Begin();
1029  size_t count = allocations->Size();
1030  // Change the order to ensure that the non-moving space last swept as an optimization.
1031  std::vector<space::ContinuousSpace*> sweep_spaces;
1032  space::ContinuousSpace* non_moving_space = nullptr;
1033  for (space::ContinuousSpace* space : heap_->GetContinuousSpaces()) {
1034    if (space->IsAllocSpace() && !immune_region_.ContainsSpace(space) &&
1035        space->GetLiveBitmap() != nullptr) {
1036      if (space == heap_->GetNonMovingSpace()) {
1037        non_moving_space = space;
1038      } else {
1039        sweep_spaces.push_back(space);
1040      }
1041    }
1042  }
1043  // Unlikely to sweep a significant amount of non_movable objects, so we do these after the after
1044  // the other alloc spaces as an optimization.
1045  if (non_moving_space != nullptr) {
1046    sweep_spaces.push_back(non_moving_space);
1047  }
1048  // Start by sweeping the continuous spaces.
1049  for (space::ContinuousSpace* space : sweep_spaces) {
1050    space::AllocSpace* alloc_space = space->AsAllocSpace();
1051    accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
1052    accounting::ContinuousSpaceBitmap* mark_bitmap = space->GetMarkBitmap();
1053    if (swap_bitmaps) {
1054      std::swap(live_bitmap, mark_bitmap);
1055    }
1056    StackReference<Object>* out = objects;
1057    for (size_t i = 0; i < count; ++i) {
1058      Object* const obj = objects[i].AsMirrorPtr();
1059      if (kUseThreadLocalAllocationStack && obj == nullptr) {
1060        continue;
1061      }
1062      if (space->HasAddress(obj)) {
1063        // This object is in the space, remove it from the array and add it to the sweep buffer
1064        // if needed.
1065        if (!mark_bitmap->Test(obj)) {
1066          if (chunk_free_pos >= kSweepArrayChunkFreeSize) {
1067            TimingLogger::ScopedTiming t2("FreeList", GetTimings());
1068            freed.objects += chunk_free_pos;
1069            freed.bytes += alloc_space->FreeList(self, chunk_free_pos, chunk_free_buffer);
1070            chunk_free_pos = 0;
1071          }
1072          chunk_free_buffer[chunk_free_pos++] = obj;
1073        }
1074      } else {
1075        (out++)->Assign(obj);
1076      }
1077    }
1078    if (chunk_free_pos > 0) {
1079      TimingLogger::ScopedTiming t2("FreeList", GetTimings());
1080      freed.objects += chunk_free_pos;
1081      freed.bytes += alloc_space->FreeList(self, chunk_free_pos, chunk_free_buffer);
1082      chunk_free_pos = 0;
1083    }
1084    // All of the references which space contained are no longer in the allocation stack, update
1085    // the count.
1086    count = out - objects;
1087  }
1088  // Handle the large object space.
1089  space::LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
1090  if (large_object_space != nullptr) {
1091    accounting::LargeObjectBitmap* large_live_objects = large_object_space->GetLiveBitmap();
1092    accounting::LargeObjectBitmap* large_mark_objects = large_object_space->GetMarkBitmap();
1093    if (swap_bitmaps) {
1094      std::swap(large_live_objects, large_mark_objects);
1095    }
1096    for (size_t i = 0; i < count; ++i) {
1097      Object* const obj = objects[i].AsMirrorPtr();
1098      // Handle large objects.
1099      if (kUseThreadLocalAllocationStack && obj == nullptr) {
1100        continue;
1101      }
1102      if (!large_mark_objects->Test(obj)) {
1103        ++freed_los.objects;
1104        freed_los.bytes += large_object_space->Free(self, obj);
1105      }
1106    }
1107  }
1108  {
1109    TimingLogger::ScopedTiming t2("RecordFree", GetTimings());
1110    RecordFree(freed);
1111    RecordFreeLOS(freed_los);
1112    t2.NewTiming("ResetStack");
1113    allocations->Reset();
1114  }
1115  sweep_array_free_buffer_mem_map_->MadviseDontNeedAndZero();
1116}
1117
1118void MarkSweep::Sweep(bool swap_bitmaps) {
1119  TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
1120  // Ensure that nobody inserted items in the live stack after we swapped the stacks.
1121  CHECK_GE(live_stack_freeze_size_, GetHeap()->GetLiveStack()->Size());
1122  {
1123    TimingLogger::ScopedTiming t2("MarkAllocStackAsLive", GetTimings());
1124    // Mark everything allocated since the last as GC live so that we can sweep concurrently,
1125    // knowing that new allocations won't be marked as live.
1126    accounting::ObjectStack* live_stack = heap_->GetLiveStack();
1127    heap_->MarkAllocStackAsLive(live_stack);
1128    live_stack->Reset();
1129    DCHECK(mark_stack_->IsEmpty());
1130  }
1131  for (const auto& space : GetHeap()->GetContinuousSpaces()) {
1132    if (space->IsContinuousMemMapAllocSpace()) {
1133      space::ContinuousMemMapAllocSpace* alloc_space = space->AsContinuousMemMapAllocSpace();
1134      TimingLogger::ScopedTiming split(
1135          alloc_space->IsZygoteSpace() ? "SweepZygoteSpace" : "SweepMallocSpace", GetTimings());
1136      RecordFree(alloc_space->Sweep(swap_bitmaps));
1137    }
1138  }
1139  SweepLargeObjects(swap_bitmaps);
1140}
1141
1142void MarkSweep::SweepLargeObjects(bool swap_bitmaps) {
1143  space::LargeObjectSpace* los = heap_->GetLargeObjectsSpace();
1144  if (los != nullptr) {
1145    TimingLogger::ScopedTiming split(__FUNCTION__, GetTimings());
1146    RecordFreeLOS(los->Sweep(swap_bitmaps));
1147  }
1148}
1149
1150// Process the "referent" field in a java.lang.ref.Reference.  If the referent has not yet been
1151// marked, put it on the appropriate list in the heap for later processing.
1152void MarkSweep::DelayReferenceReferent(mirror::Class* klass, mirror::Reference* ref) {
1153  if (kCountJavaLangRefs) {
1154    ++reference_count_;
1155  }
1156  heap_->GetReferenceProcessor()->DelayReferenceReferent(klass, ref, &HeapReferenceMarkedCallback,
1157                                                         this);
1158}
1159
1160class MarkObjectVisitor {
1161 public:
1162  explicit MarkObjectVisitor(MarkSweep* const mark_sweep) ALWAYS_INLINE : mark_sweep_(mark_sweep) {
1163  }
1164
1165  void operator()(Object* obj, MemberOffset offset, bool /* is_static */) const
1166      ALWAYS_INLINE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1167      EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
1168    if (kCheckLocks) {
1169      Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
1170      Locks::heap_bitmap_lock_->AssertExclusiveHeld(Thread::Current());
1171    }
1172    mark_sweep_->MarkObject(obj->GetFieldObject<mirror::Object>(offset));
1173  }
1174
1175 private:
1176  MarkSweep* const mark_sweep_;
1177};
1178
1179// Scans an object reference.  Determines the type of the reference
1180// and dispatches to a specialized scanning routine.
1181void MarkSweep::ScanObject(Object* obj) {
1182  MarkObjectVisitor mark_visitor(this);
1183  DelayReferenceReferentVisitor ref_visitor(this);
1184  ScanObjectVisit(obj, mark_visitor, ref_visitor);
1185}
1186
1187void MarkSweep::ProcessMarkStackCallback(void* arg) {
1188  reinterpret_cast<MarkSweep*>(arg)->ProcessMarkStack(false);
1189}
1190
1191void MarkSweep::ProcessMarkStackParallel(size_t thread_count) {
1192  Thread* self = Thread::Current();
1193  ThreadPool* thread_pool = GetHeap()->GetThreadPool();
1194  const size_t chunk_size = std::min(mark_stack_->Size() / thread_count + 1,
1195                                     static_cast<size_t>(MarkStackTask<false>::kMaxSize));
1196  CHECK_GT(chunk_size, 0U);
1197  // Split the current mark stack up into work tasks.
1198  for (auto* it = mark_stack_->Begin(), *end = mark_stack_->End(); it < end; ) {
1199    const size_t delta = std::min(static_cast<size_t>(end - it), chunk_size);
1200    thread_pool->AddTask(self, new MarkStackTask<false>(thread_pool, this, delta, it));
1201    it += delta;
1202  }
1203  thread_pool->SetMaxActiveWorkers(thread_count - 1);
1204  thread_pool->StartWorkers(self);
1205  thread_pool->Wait(self, true, true);
1206  thread_pool->StopWorkers(self);
1207  mark_stack_->Reset();
1208  CHECK_EQ(work_chunks_created_.LoadSequentiallyConsistent(),
1209           work_chunks_deleted_.LoadSequentiallyConsistent())
1210      << " some of the work chunks were leaked";
1211}
1212
1213// Scan anything that's on the mark stack.
1214void MarkSweep::ProcessMarkStack(bool paused) {
1215  TimingLogger::ScopedTiming t(paused ? "(Paused)ProcessMarkStack" : __FUNCTION__, GetTimings());
1216  size_t thread_count = GetThreadCount(paused);
1217  if (kParallelProcessMarkStack && thread_count > 1 &&
1218      mark_stack_->Size() >= kMinimumParallelMarkStackSize) {
1219    ProcessMarkStackParallel(thread_count);
1220  } else {
1221    // TODO: Tune this.
1222    static const size_t kFifoSize = 4;
1223    BoundedFifoPowerOfTwo<Object*, kFifoSize> prefetch_fifo;
1224    for (;;) {
1225      Object* obj = NULL;
1226      if (kUseMarkStackPrefetch) {
1227        while (!mark_stack_->IsEmpty() && prefetch_fifo.size() < kFifoSize) {
1228          Object* mark_stack_obj = mark_stack_->PopBack();
1229          DCHECK(mark_stack_obj != NULL);
1230          __builtin_prefetch(mark_stack_obj);
1231          prefetch_fifo.push_back(mark_stack_obj);
1232        }
1233        if (prefetch_fifo.empty()) {
1234          break;
1235        }
1236        obj = prefetch_fifo.front();
1237        prefetch_fifo.pop_front();
1238      } else {
1239        if (mark_stack_->IsEmpty()) {
1240          break;
1241        }
1242        obj = mark_stack_->PopBack();
1243      }
1244      DCHECK(obj != nullptr);
1245      ScanObject(obj);
1246    }
1247  }
1248}
1249
1250inline bool MarkSweep::IsMarked(const Object* object) const {
1251  if (immune_region_.ContainsObject(object)) {
1252    return true;
1253  }
1254  if (current_space_bitmap_->HasAddress(object)) {
1255    return current_space_bitmap_->Test(object);
1256  }
1257  return mark_bitmap_->Test(object);
1258}
1259
1260void MarkSweep::FinishPhase() {
1261  TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
1262  if (kCountScannedTypes) {
1263    VLOG(gc) << "MarkSweep scanned classes=" << class_count_.LoadRelaxed()
1264        << " arrays=" << array_count_.LoadRelaxed() << " other=" << other_count_.LoadRelaxed();
1265  }
1266  if (kCountTasks) {
1267    VLOG(gc) << "Total number of work chunks allocated: " << work_chunks_created_.LoadRelaxed();
1268  }
1269  if (kMeasureOverhead) {
1270    VLOG(gc) << "Overhead time " << PrettyDuration(overhead_time_.LoadRelaxed());
1271  }
1272  if (kProfileLargeObjects) {
1273    VLOG(gc) << "Large objects tested " << large_object_test_.LoadRelaxed()
1274        << " marked " << large_object_mark_.LoadRelaxed();
1275  }
1276  if (kCountJavaLangRefs) {
1277    VLOG(gc) << "References scanned " << reference_count_.LoadRelaxed();
1278  }
1279  if (kCountMarkedObjects) {
1280    VLOG(gc) << "Marked: null=" << mark_null_count_.LoadRelaxed()
1281        << " immune=" <<  mark_immune_count_.LoadRelaxed()
1282        << " fastpath=" << mark_fastpath_count_.LoadRelaxed()
1283        << " slowpath=" << mark_slowpath_count_.LoadRelaxed();
1284  }
1285  CHECK(mark_stack_->IsEmpty());  // Ensure that the mark stack is empty.
1286  mark_stack_->Reset();
1287  WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
1288  heap_->ClearMarkedObjects();
1289}
1290
1291void MarkSweep::RevokeAllThreadLocalBuffers() {
1292  if (kRevokeRosAllocThreadLocalBuffersAtCheckpoint && IsConcurrent()) {
1293    // If concurrent, rosalloc thread-local buffers are revoked at the
1294    // thread checkpoint. Bump pointer space thread-local buffers must
1295    // not be in use.
1296    GetHeap()->AssertAllBumpPointerSpaceThreadLocalBuffersAreRevoked();
1297  } else {
1298    TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
1299    GetHeap()->RevokeAllThreadLocalBuffers();
1300  }
1301}
1302
1303}  // namespace collector
1304}  // namespace gc
1305}  // namespace art
1306