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