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