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