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 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*), gPageSize),
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(self, GetTimings());
181 }
182
PausePhase()183 void MarkSweep::PausePhase() {
184 TimingLogger::ScopedTiming t("(Paused)PausePhase", GetTimings());
185 Thread* self = Thread::Current();
186 Locks::mutator_lock_->AssertExclusiveHeld(self);
187 if (IsConcurrent()) {
188 // Handle the dirty objects if we are a concurrent GC.
189 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
190 // Re-mark root set.
191 ReMarkRoots();
192 // Scan dirty objects, this is only required if we are doing concurrent GC.
193 RecursiveMarkDirtyObjects(true, accounting::CardTable::kCardDirty);
194 }
195 {
196 TimingLogger::ScopedTiming t2("SwapStacks", GetTimings());
197 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
198 heap_->SwapStacks();
199 live_stack_freeze_size_ = heap_->GetLiveStack()->Size();
200 // Need to revoke all the thread local allocation stacks since we just swapped the allocation
201 // stacks and don't want anybody to allocate into the live stack.
202 RevokeAllThreadLocalAllocationStacks(self);
203 }
204 heap_->PreSweepingGcVerification(this);
205 // Disallow new system weaks to prevent a race which occurs when someone adds a new system
206 // weak before we sweep them. Since this new system weak may not be marked, the GC may
207 // incorrectly sweep it. This also fixes a race where interning may attempt to return a strong
208 // reference to a string that is about to be swept.
209 Runtime::Current()->DisallowNewSystemWeaks();
210 // Enable the reference processing slow path, needs to be done with mutators paused since there
211 // is no lock in the GetReferent fast path.
212 ReferenceProcessor* rp = GetHeap()->GetReferenceProcessor();
213 rp->Setup(self, this, /*concurrent=*/true, GetCurrentIteration()->GetClearSoftReferences());
214 rp->EnableSlowPath();
215 }
216
PreCleanCards()217 void MarkSweep::PreCleanCards() {
218 // Don't do this for non concurrent GCs since they don't have any dirty cards.
219 if (kPreCleanCards && IsConcurrent()) {
220 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
221 Thread* self = Thread::Current();
222 CHECK(!Locks::mutator_lock_->IsExclusiveHeld(self));
223 // Process dirty cards and add dirty cards to mod union tables, also ages cards.
224 heap_->ProcessCards(GetTimings(), false, true, false);
225 // The checkpoint root marking is required to avoid a race condition which occurs if the
226 // following happens during a reference write:
227 // 1. mutator dirties the card (write barrier)
228 // 2. GC ages the card (the above ProcessCards call)
229 // 3. GC scans the object (the RecursiveMarkDirtyObjects call below)
230 // 4. mutator writes the value (corresponding to the write barrier in 1.)
231 // This causes the GC to age the card but not necessarily mark the reference which the mutator
232 // wrote into the object stored in the card.
233 // Having the checkpoint fixes this issue since it ensures that the card mark and the
234 // reference write are visible to the GC before the card is scanned (this is due to locks being
235 // acquired / released in the checkpoint code).
236 // The other roots are also marked to help reduce the pause.
237 MarkRootsCheckpoint(self, false);
238 MarkNonThreadRoots();
239 MarkConcurrentRoots(
240 static_cast<VisitRootFlags>(kVisitRootFlagClearRootLog | kVisitRootFlagNewRoots));
241 // Process the newly aged cards.
242 RecursiveMarkDirtyObjects(false, accounting::CardTable::kCardDirty - 1);
243 // TODO: Empty allocation stack to reduce the number of objects we need to test / mark as live
244 // in the next GC.
245 }
246 }
247
RevokeAllThreadLocalAllocationStacks(Thread * self)248 void MarkSweep::RevokeAllThreadLocalAllocationStacks(Thread* self) {
249 if (kUseThreadLocalAllocationStack) {
250 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
251 Locks::mutator_lock_->AssertExclusiveHeld(self);
252 heap_->RevokeAllThreadLocalAllocationStacks(self);
253 }
254 }
255
MarkingPhase()256 void MarkSweep::MarkingPhase() {
257 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
258 Thread* self = Thread::Current();
259 BindBitmaps();
260 FindDefaultSpaceBitmap();
261 // Process dirty cards and add dirty cards to mod union tables.
262 // If the GC type is non sticky, then we just clear the cards of the
263 // alloc space instead of aging them.
264 //
265 // Note that it is fine to clear the cards of the alloc space here,
266 // in the case of a concurrent (non-sticky) mark-sweep GC (whose
267 // marking phase _is_ performed concurrently with mutator threads
268 // running and possibly dirtying cards), as the whole alloc space
269 // will be traced in that case, starting *after* this call to
270 // Heap::ProcessCards (see calls to MarkSweep::MarkRoots and
271 // MarkSweep::MarkReachableObjects). References held by objects on
272 // cards that became dirty *after* the actual marking work started
273 // will be marked in the pause (see MarkSweep::PausePhase), in a
274 // *non-concurrent* way to prevent races with mutator threads.
275 //
276 // TODO: Do we need some sort of fence between the call to
277 // Heap::ProcessCard and the calls to MarkSweep::MarkRoot /
278 // MarkSweep::MarkReachableObjects below to make sure write
279 // operations in the card table clearing the alloc space's dirty
280 // cards (during the call to Heap::ProcessCard) are not reordered
281 // *after* marking actually starts?
282 heap_->ProcessCards(GetTimings(),
283 /* use_rem_sets= */ false,
284 /* process_alloc_space_cards= */ true,
285 /* clear_alloc_space_cards= */ GetGcType() != kGcTypeSticky);
286 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
287 MarkRoots(self);
288 MarkReachableObjects();
289 // Pre-clean dirtied cards to reduce pauses.
290 PreCleanCards();
291 }
292
293 class MarkSweep::ScanObjectVisitor {
294 public:
ScanObjectVisitor(MarkSweep * const mark_sweep)295 explicit ScanObjectVisitor(MarkSweep* const mark_sweep) ALWAYS_INLINE
296 : mark_sweep_(mark_sweep) {}
297
operator ()(ObjPtr<mirror::Object> obj) const298 void operator()(ObjPtr<mirror::Object> obj) const
299 ALWAYS_INLINE
300 REQUIRES(Locks::heap_bitmap_lock_)
301 REQUIRES_SHARED(Locks::mutator_lock_) {
302 if (kCheckLocks) {
303 Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
304 Locks::heap_bitmap_lock_->AssertExclusiveHeld(Thread::Current());
305 }
306 mark_sweep_->ScanObject(obj.Ptr());
307 }
308
309 private:
310 MarkSweep* const mark_sweep_;
311 };
312
UpdateAndMarkModUnion()313 void MarkSweep::UpdateAndMarkModUnion() {
314 for (const auto& space : immune_spaces_.GetSpaces()) {
315 const char* name = space->IsZygoteSpace()
316 ? "UpdateAndMarkZygoteModUnionTable"
317 : "UpdateAndMarkImageModUnionTable";
318 DCHECK(space->IsZygoteSpace() || space->IsImageSpace()) << *space;
319 TimingLogger::ScopedTiming t(name, GetTimings());
320 accounting::ModUnionTable* mod_union_table = heap_->FindModUnionTableFromSpace(space);
321 if (mod_union_table != nullptr) {
322 mod_union_table->UpdateAndMarkReferences(this);
323 } else {
324 // No mod-union table, scan all the live bits. This can only occur for app images.
325 space->GetLiveBitmap()->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()),
326 reinterpret_cast<uintptr_t>(space->End()),
327 ScanObjectVisitor(this));
328 }
329 }
330 }
331
MarkReachableObjects()332 void MarkSweep::MarkReachableObjects() {
333 UpdateAndMarkModUnion();
334 // Recursively mark all the non-image bits set in the mark bitmap.
335 RecursiveMark();
336 }
337
ReclaimPhase()338 void MarkSweep::ReclaimPhase() {
339 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
340 Thread* const self = Thread::Current();
341 // Process the references concurrently.
342 ProcessReferences(self);
343 // There is no need to sweep interpreter caches as this GC doesn't move
344 // objects and hence would be a nop.
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)418 bool MarkSweep::IsNullOrMarkedHeapReference(mirror::HeapReference<mirror::Object>* ref,
419 [[maybe_unused]] bool do_atomic_update) {
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 ||
444 !IsAlignedParam(obj, space::LargeObjectSpace::ObjectAlignment()) ||
445 (kIsDebugBuild && large_object_space != nullptr &&
446 !large_object_space->Contains(obj)))) {
447 // Lowest priority logging first:
448 PrintFileToLog("/proc/self/maps", LogSeverity::FATAL_WITHOUT_ABORT);
449 MemMap::DumpMaps(LOG_STREAM(FATAL_WITHOUT_ABORT), /* terse= */ true);
450 // Buffer the output in the string stream since it is more important than the stack traces
451 // and we want it to have log priority. The stack traces are printed from Runtime::Abort
452 // which is called from LOG(FATAL) but before the abort message.
453 std::ostringstream oss;
454 oss << "Tried to mark " << obj << " not contained by any spaces" << std::endl;
455 if (holder_ != nullptr) {
456 size_t holder_size = holder_->SizeOf();
457 ArtField* field = holder_->FindFieldByOffset(offset_);
458 oss << "Field info: "
459 << " holder=" << holder_
460 << " holder is "
461 << (mark_sweep_->GetHeap()->IsLiveObjectLocked(holder_)
462 ? "alive" : "dead")
463 << " holder_size=" << holder_size
464 << " holder_type=" << holder_->PrettyTypeOf()
465 << " offset=" << offset_.Uint32Value()
466 << " field=" << (field != nullptr ? field->GetName() : "nullptr")
467 << " field_type="
468 << (field != nullptr ? field->GetTypeDescriptor() : "")
469 << " first_ref_field_offset="
470 << (holder_->IsClass()
471 ? holder_->AsClass()->GetFirstReferenceStaticFieldOffset(
472 kRuntimePointerSize)
473 : holder_->GetClass()->GetFirstReferenceInstanceFieldOffset())
474 << " num_of_ref_fields="
475 << (holder_->IsClass()
476 ? holder_->AsClass()->NumReferenceStaticFields()
477 : holder_->GetClass()->NumReferenceInstanceFields())
478 << std::endl;
479 // Print the memory content of the holder.
480 for (size_t i = 0; i < holder_size / sizeof(uint32_t); ++i) {
481 uint32_t* p = reinterpret_cast<uint32_t*>(holder_);
482 oss << &p[i] << ": " << "holder+" << (i * sizeof(uint32_t)) << " = " << std::hex << p[i]
483 << std::endl;
484 }
485 }
486 oss << "Attempting see if it's a bad thread root" << std::endl;
487 mark_sweep_->VerifySuspendedThreadRoots(oss);
488 LOG(FATAL) << oss.str();
489 }
490 }
491
492 private:
493 MarkSweep* const mark_sweep_;
494 mirror::Object* const holder_;
495 MemberOffset offset_;
496 };
497
MarkObjectNonNull(mirror::Object * obj,mirror::Object * holder,MemberOffset offset)498 inline void MarkSweep::MarkObjectNonNull(mirror::Object* obj,
499 mirror::Object* holder,
500 MemberOffset offset) {
501 DCHECK(obj != nullptr);
502 if (kUseBakerReadBarrier) {
503 // Verify all the objects have the correct state installed.
504 obj->AssertReadBarrierState();
505 }
506 if (immune_spaces_.IsInImmuneRegion(obj)) {
507 if (kCountMarkedObjects) {
508 ++mark_immune_count_;
509 }
510 DCHECK(mark_bitmap_->Test(obj));
511 } else if (LIKELY(current_space_bitmap_->HasAddress(obj))) {
512 if (kCountMarkedObjects) {
513 ++mark_fastpath_count_;
514 }
515 if (UNLIKELY(!current_space_bitmap_->Set(obj))) {
516 PushOnMarkStack(obj); // This object was not previously marked.
517 }
518 } else {
519 if (kCountMarkedObjects) {
520 ++mark_slowpath_count_;
521 }
522 MarkObjectSlowPath visitor(this, holder, offset);
523 // TODO: We already know that the object is not in the current_space_bitmap_ but MarkBitmap::Set
524 // will check again.
525 if (!mark_bitmap_->Set(obj, visitor)) {
526 PushOnMarkStack(obj); // Was not already marked, push.
527 }
528 }
529 }
530
PushOnMarkStack(mirror::Object * obj)531 inline void MarkSweep::PushOnMarkStack(mirror::Object* obj) {
532 if (UNLIKELY(mark_stack_->Size() >= mark_stack_->Capacity())) {
533 // Lock is not needed but is here anyways to please annotalysis.
534 MutexLock mu(Thread::Current(), mark_stack_lock_);
535 ExpandMarkStack();
536 }
537 // The object must be pushed on to the mark stack.
538 mark_stack_->PushBack(obj);
539 }
540
MarkObjectParallel(mirror::Object * obj)541 inline bool MarkSweep::MarkObjectParallel(mirror::Object* obj) {
542 DCHECK(obj != nullptr);
543 if (kUseBakerReadBarrier) {
544 // Verify all the objects have the correct state installed.
545 obj->AssertReadBarrierState();
546 }
547 if (immune_spaces_.IsInImmuneRegion(obj)) {
548 DCHECK(IsMarked(obj) != nullptr);
549 return false;
550 }
551 // Try to take advantage of locality of references within a space, failing this find the space
552 // the hard way.
553 accounting::ContinuousSpaceBitmap* object_bitmap = current_space_bitmap_;
554 if (LIKELY(object_bitmap->HasAddress(obj))) {
555 return !object_bitmap->AtomicTestAndSet(obj);
556 }
557 MarkObjectSlowPath visitor(this);
558 return !mark_bitmap_->AtomicTestAndSet(obj, visitor);
559 }
560
MarkHeapReference(mirror::HeapReference<mirror::Object> * ref,bool do_atomic_update)561 void MarkSweep::MarkHeapReference(mirror::HeapReference<mirror::Object>* ref,
562 [[maybe_unused]] bool do_atomic_update) {
563 MarkObject(ref->AsMirrorPtr(), nullptr, MemberOffset(0));
564 }
565
566 // 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)567 inline void MarkSweep::MarkObject(mirror::Object* obj,
568 mirror::Object* holder,
569 MemberOffset offset) {
570 if (obj != nullptr) {
571 MarkObjectNonNull(obj, holder, offset);
572 } else if (kCountMarkedObjects) {
573 ++mark_null_count_;
574 }
575 }
576
577 class MarkSweep::VerifyRootMarkedVisitor : public SingleRootVisitor {
578 public:
VerifyRootMarkedVisitor(MarkSweep * collector)579 explicit VerifyRootMarkedVisitor(MarkSweep* collector) : collector_(collector) { }
580
VisitRoot(mirror::Object * root,const RootInfo & info)581 void VisitRoot(mirror::Object* root, const RootInfo& info) override
582 REQUIRES_SHARED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
583 CHECK(collector_->IsMarked(root) != nullptr) << info.ToString();
584 }
585
586 private:
587 MarkSweep* const collector_;
588 };
589
VisitRoots(mirror::Object *** roots,size_t count,const RootInfo & info)590 void MarkSweep::VisitRoots(mirror::Object*** roots,
591 size_t count,
592 [[maybe_unused]] const RootInfo& info) {
593 for (size_t i = 0; i < count; ++i) {
594 MarkObjectNonNull(*roots[i]);
595 }
596 }
597
VisitRoots(mirror::CompressedReference<mirror::Object> ** roots,size_t count,const RootInfo & info)598 void MarkSweep::VisitRoots(mirror::CompressedReference<mirror::Object>** roots,
599 size_t count,
600 [[maybe_unused]] const RootInfo& info) {
601 for (size_t i = 0; i < count; ++i) {
602 MarkObjectNonNull(roots[i]->AsMirrorPtr());
603 }
604 }
605
606 class MarkSweep::VerifyRootVisitor : public SingleRootVisitor {
607 public:
VerifyRootVisitor(std::ostream & os)608 explicit VerifyRootVisitor(std::ostream& os) : os_(os) {}
609
VisitRoot(mirror::Object * root,const RootInfo & info)610 void VisitRoot(mirror::Object* root, const RootInfo& info) override
611 REQUIRES_SHARED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
612 // See if the root is on any space bitmap.
613 auto* heap = Runtime::Current()->GetHeap();
614 if (heap->GetLiveBitmap()->GetContinuousSpaceBitmap(root) == nullptr) {
615 space::LargeObjectSpace* large_object_space = heap->GetLargeObjectsSpace();
616 if (large_object_space != nullptr && !large_object_space->Contains(root)) {
617 os_ << "Found invalid root: " << root << " " << info << std::endl;
618 }
619 }
620 }
621
622 private:
623 std::ostream& os_;
624 };
625
VerifySuspendedThreadRoots(std::ostream & os)626 void MarkSweep::VerifySuspendedThreadRoots(std::ostream& os) {
627 VerifyRootVisitor visitor(os);
628 Runtime::Current()->GetThreadList()->VisitRootsForSuspendedThreads(&visitor);
629 }
630
MarkRoots(Thread * self)631 void MarkSweep::MarkRoots(Thread* self) {
632 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
633 if (Locks::mutator_lock_->IsExclusiveHeld(self)) {
634 // If we exclusively hold the mutator lock, all threads must be suspended.
635 Runtime::Current()->VisitRoots(this);
636 RevokeAllThreadLocalAllocationStacks(self);
637 } else {
638 MarkRootsCheckpoint(self, kRevokeRosAllocThreadLocalBuffersAtCheckpoint);
639 // At this point the live stack should no longer have any mutators which push into it.
640 MarkNonThreadRoots();
641 MarkConcurrentRoots(
642 static_cast<VisitRootFlags>(kVisitRootFlagAllRoots | kVisitRootFlagStartLoggingNewRoots));
643 }
644 }
645
MarkNonThreadRoots()646 void MarkSweep::MarkNonThreadRoots() {
647 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
648 Runtime::Current()->VisitNonThreadRoots(this);
649 }
650
MarkConcurrentRoots(VisitRootFlags flags)651 void MarkSweep::MarkConcurrentRoots(VisitRootFlags flags) {
652 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
653 // Visit all runtime roots and clear dirty flags.
654 Runtime::Current()->VisitConcurrentRoots(this, flags);
655 }
656
657 class MarkSweep::DelayReferenceReferentVisitor {
658 public:
DelayReferenceReferentVisitor(MarkSweep * collector)659 explicit DelayReferenceReferentVisitor(MarkSweep* collector) : collector_(collector) {}
660
operator ()(ObjPtr<mirror::Class> klass,ObjPtr<mirror::Reference> ref) const661 void operator()(ObjPtr<mirror::Class> klass, ObjPtr<mirror::Reference> ref) const
662 REQUIRES(Locks::heap_bitmap_lock_)
663 REQUIRES_SHARED(Locks::mutator_lock_) {
664 collector_->DelayReferenceReferent(klass, ref);
665 }
666
667 private:
668 MarkSweep* const collector_;
669 };
670
671 template <bool kUseFinger = false>
672 class MarkSweep::MarkStackTask : public Task {
673 public:
MarkStackTask(ThreadPool * thread_pool,MarkSweep * mark_sweep,size_t mark_stack_size,StackReference<mirror::Object> * mark_stack)674 MarkStackTask(ThreadPool* thread_pool,
675 MarkSweep* mark_sweep,
676 size_t mark_stack_size,
677 StackReference<mirror::Object>* mark_stack)
678 : mark_sweep_(mark_sweep),
679 thread_pool_(thread_pool),
680 mark_stack_pos_(mark_stack_size) {
681 // We may have to copy part of an existing mark stack when another mark stack overflows.
682 if (mark_stack_size != 0) {
683 DCHECK(mark_stack != nullptr);
684 // TODO: Check performance?
685 std::copy(mark_stack, mark_stack + mark_stack_size, mark_stack_);
686 }
687 if (kCountTasks) {
688 ++mark_sweep_->work_chunks_created_;
689 }
690 }
691
692 static constexpr size_t kMaxSize = 1 * KB;
693
694 protected:
695 class MarkObjectParallelVisitor {
696 public:
MarkObjectParallelVisitor(MarkStackTask<kUseFinger> * chunk_task,MarkSweep * mark_sweep)697 ALWAYS_INLINE MarkObjectParallelVisitor(MarkStackTask<kUseFinger>* chunk_task,
698 MarkSweep* mark_sweep)
699 : chunk_task_(chunk_task), mark_sweep_(mark_sweep) {}
700
operator ()(mirror::Object * obj,MemberOffset offset,bool is_static) const701 ALWAYS_INLINE void operator()(mirror::Object* obj,
702 MemberOffset offset,
703 [[maybe_unused]] bool is_static) const
704 REQUIRES_SHARED(Locks::mutator_lock_) {
705 Mark(obj->GetFieldObject<mirror::Object>(offset));
706 }
707
VisitRootIfNonNull(mirror::CompressedReference<mirror::Object> * root) const708 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
709 REQUIRES_SHARED(Locks::mutator_lock_) {
710 if (!root->IsNull()) {
711 VisitRoot(root);
712 }
713 }
714
VisitRoot(mirror::CompressedReference<mirror::Object> * root) const715 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
716 REQUIRES_SHARED(Locks::mutator_lock_) {
717 if (kCheckLocks) {
718 Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
719 Locks::heap_bitmap_lock_->AssertExclusiveHeld(Thread::Current());
720 }
721 Mark(root->AsMirrorPtr());
722 }
723
724 private:
Mark(mirror::Object * ref) const725 ALWAYS_INLINE void Mark(mirror::Object* ref) const REQUIRES_SHARED(Locks::mutator_lock_) {
726 if (ref != nullptr && mark_sweep_->MarkObjectParallel(ref)) {
727 if (kUseFinger) {
728 std::atomic_thread_fence(std::memory_order_seq_cst);
729 if (reinterpret_cast<uintptr_t>(ref) >=
730 static_cast<uintptr_t>(mark_sweep_->atomic_finger_.load(std::memory_order_relaxed))) {
731 return;
732 }
733 }
734 chunk_task_->MarkStackPush(ref);
735 }
736 }
737
738 MarkStackTask<kUseFinger>* const chunk_task_;
739 MarkSweep* const mark_sweep_;
740 };
741
742 class ScanObjectParallelVisitor {
743 public:
ScanObjectParallelVisitor(MarkStackTask<kUseFinger> * chunk_task)744 ALWAYS_INLINE explicit ScanObjectParallelVisitor(MarkStackTask<kUseFinger>* chunk_task)
745 : chunk_task_(chunk_task) {}
746
747 // No thread safety analysis since multiple threads will use this visitor.
operator ()(mirror::Object * obj) const748 void operator()(mirror::Object* obj) const
749 REQUIRES(Locks::heap_bitmap_lock_)
750 REQUIRES_SHARED(Locks::mutator_lock_) {
751 MarkSweep* const mark_sweep = chunk_task_->mark_sweep_;
752 MarkObjectParallelVisitor mark_visitor(chunk_task_, mark_sweep);
753 DelayReferenceReferentVisitor ref_visitor(mark_sweep);
754 mark_sweep->ScanObjectVisit(obj, mark_visitor, ref_visitor);
755 }
756
757 private:
758 MarkStackTask<kUseFinger>* const chunk_task_;
759 };
760
~MarkStackTask()761 virtual ~MarkStackTask() {
762 // Make sure that we have cleared our mark stack.
763 DCHECK_EQ(mark_stack_pos_, 0U);
764 if (kCountTasks) {
765 ++mark_sweep_->work_chunks_deleted_;
766 }
767 }
768
769 MarkSweep* const mark_sweep_;
770 ThreadPool* const thread_pool_;
771 // Thread local mark stack for this task.
772 StackReference<mirror::Object> mark_stack_[kMaxSize];
773 // Mark stack position.
774 size_t mark_stack_pos_;
775
MarkStackPush(mirror::Object * obj)776 ALWAYS_INLINE void MarkStackPush(mirror::Object* obj)
777 REQUIRES_SHARED(Locks::mutator_lock_) {
778 if (UNLIKELY(mark_stack_pos_ == kMaxSize)) {
779 // Mark stack overflow, give 1/2 the stack to the thread pool as a new work task.
780 mark_stack_pos_ /= 2;
781 auto* task = new MarkStackTask(thread_pool_,
782 mark_sweep_,
783 kMaxSize - mark_stack_pos_,
784 mark_stack_ + mark_stack_pos_);
785 thread_pool_->AddTask(Thread::Current(), task);
786 }
787 DCHECK(obj != nullptr);
788 DCHECK_LT(mark_stack_pos_, kMaxSize);
789 mark_stack_[mark_stack_pos_++].Assign(obj);
790 }
791
Finalize()792 void Finalize() override {
793 delete this;
794 }
795
796 // Scans all of the objects
Run(Thread * self)797 void Run([[maybe_unused]] Thread* self) override 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 }
970 TimingLogger::ScopedTiming t(name, GetTimings());
971 ScanObjectVisitor visitor(this);
972 bool clear_card = paused && !space->IsZygoteSpace() && !space->IsImageSpace();
973 if (clear_card) {
974 card_table->Scan<true>(space->GetMarkBitmap(),
975 space->Begin(),
976 space->End(),
977 visitor,
978 minimum_age);
979 } else {
980 card_table->Scan<false>(space->GetMarkBitmap(),
981 space->Begin(),
982 space->End(),
983 visitor,
984 minimum_age);
985 }
986 }
987 }
988 }
989 }
990
991 class MarkSweep::RecursiveMarkTask : public MarkStackTask<false> {
992 public:
RecursiveMarkTask(ThreadPool * thread_pool,MarkSweep * mark_sweep,accounting::ContinuousSpaceBitmap * bitmap,uintptr_t begin,uintptr_t end)993 RecursiveMarkTask(ThreadPool* thread_pool,
994 MarkSweep* mark_sweep,
995 accounting::ContinuousSpaceBitmap* bitmap,
996 uintptr_t begin,
997 uintptr_t end)
998 : MarkStackTask<false>(thread_pool, mark_sweep, 0, nullptr),
999 bitmap_(bitmap),
1000 begin_(begin),
1001 end_(end) {}
1002
1003 protected:
1004 accounting::ContinuousSpaceBitmap* const bitmap_;
1005 const uintptr_t begin_;
1006 const uintptr_t end_;
1007
Finalize()1008 void Finalize() override {
1009 delete this;
1010 }
1011
1012 // Scans all of the objects
Run(Thread * self)1013 void Run(Thread* self) override NO_THREAD_SAFETY_ANALYSIS {
1014 ScanObjectParallelVisitor visitor(this);
1015 bitmap_->VisitMarkedRange(begin_, end_, visitor);
1016 // Finish by emptying our local mark stack.
1017 MarkStackTask::Run(self);
1018 }
1019 };
1020
1021 // Populates the mark stack based on the set of marked objects and
1022 // recursively marks until the mark stack is emptied.
RecursiveMark()1023 void MarkSweep::RecursiveMark() {
1024 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
1025 // RecursiveMark will build the lists of known instances of the Reference classes. See
1026 // DelayReferenceReferent for details.
1027 if (kUseRecursiveMark) {
1028 const bool partial = GetGcType() == kGcTypePartial;
1029 ScanObjectVisitor scan_visitor(this);
1030 auto* self = Thread::Current();
1031 ThreadPool* thread_pool = heap_->GetThreadPool();
1032 size_t thread_count = GetThreadCount(false);
1033 const bool parallel = kParallelRecursiveMark && thread_count > 1;
1034 mark_stack_->Reset();
1035 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
1036 if ((space->GetGcRetentionPolicy() == space::kGcRetentionPolicyAlwaysCollect) ||
1037 (!partial && space->GetGcRetentionPolicy() == space::kGcRetentionPolicyFullCollect)) {
1038 current_space_bitmap_ = space->GetMarkBitmap();
1039 if (current_space_bitmap_ == nullptr) {
1040 continue;
1041 }
1042 if (parallel) {
1043 // We will use the mark stack the future.
1044 // CHECK(mark_stack_->IsEmpty());
1045 // This function does not handle heap end increasing, so we must use the space end.
1046 uintptr_t begin = reinterpret_cast<uintptr_t>(space->Begin());
1047 uintptr_t end = reinterpret_cast<uintptr_t>(space->End());
1048 atomic_finger_.store(AtomicInteger::MaxValue(), std::memory_order_relaxed);
1049
1050 // Create a few worker tasks.
1051 const size_t n = thread_count * 2;
1052 while (begin != end) {
1053 uintptr_t start = begin;
1054 uintptr_t delta = (end - begin) / n;
1055 delta = RoundUp(delta, KB);
1056 if (delta < 16 * KB) delta = end - begin;
1057 begin += delta;
1058 auto* task = new RecursiveMarkTask(thread_pool,
1059 this,
1060 current_space_bitmap_,
1061 start,
1062 begin);
1063 thread_pool->AddTask(self, task);
1064 }
1065 thread_pool->SetMaxActiveWorkers(thread_count - 1);
1066 thread_pool->StartWorkers(self);
1067 thread_pool->Wait(self, true, true);
1068 thread_pool->StopWorkers(self);
1069 } else {
1070 // This function does not handle heap end increasing, so we must use the space end.
1071 uintptr_t begin = reinterpret_cast<uintptr_t>(space->Begin());
1072 uintptr_t end = reinterpret_cast<uintptr_t>(space->End());
1073 current_space_bitmap_->VisitMarkedRange(begin, end, scan_visitor);
1074 }
1075 }
1076 }
1077 }
1078 ProcessMarkStack(false);
1079 }
1080
RecursiveMarkDirtyObjects(bool paused,uint8_t minimum_age)1081 void MarkSweep::RecursiveMarkDirtyObjects(bool paused, uint8_t minimum_age) {
1082 ScanGrayObjects(paused, minimum_age);
1083 ProcessMarkStack(paused);
1084 }
1085
ReMarkRoots()1086 void MarkSweep::ReMarkRoots() {
1087 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
1088 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
1089 Runtime::Current()->VisitRoots(this, static_cast<VisitRootFlags>(
1090 kVisitRootFlagNewRoots | kVisitRootFlagStopLoggingNewRoots | kVisitRootFlagClearRootLog));
1091 if (kVerifyRootsMarked) {
1092 TimingLogger::ScopedTiming t2("(Paused)VerifyRoots", GetTimings());
1093 VerifyRootMarkedVisitor visitor(this);
1094 Runtime::Current()->VisitRoots(&visitor);
1095 }
1096 }
1097
SweepSystemWeaks(Thread * self)1098 void MarkSweep::SweepSystemWeaks(Thread* self) {
1099 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
1100 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1101 Runtime::Current()->SweepSystemWeaks(this);
1102 }
1103
1104 class MarkSweep::VerifySystemWeakVisitor : public IsMarkedVisitor {
1105 public:
VerifySystemWeakVisitor(MarkSweep * mark_sweep)1106 explicit VerifySystemWeakVisitor(MarkSweep* mark_sweep) : mark_sweep_(mark_sweep) {}
1107
IsMarked(mirror::Object * obj)1108 mirror::Object* IsMarked(mirror::Object* obj) override
1109 REQUIRES_SHARED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1110 mark_sweep_->VerifyIsLive(obj);
1111 return obj;
1112 }
1113
1114 MarkSweep* const mark_sweep_;
1115 };
1116
VerifyIsLive(const mirror::Object * obj)1117 void MarkSweep::VerifyIsLive(const mirror::Object* obj) {
1118 if (!heap_->GetLiveBitmap()->Test(obj)) {
1119 // TODO: Consider live stack? Has this code bitrotted?
1120 CHECK(!heap_->allocation_stack_->Contains(obj))
1121 << "Found dead object " << obj << "\n" << heap_->DumpSpaces();
1122 }
1123 }
1124
VerifySystemWeaks()1125 void MarkSweep::VerifySystemWeaks() {
1126 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
1127 // Verify system weaks, uses a special object visitor which returns the input object.
1128 VerifySystemWeakVisitor visitor(this);
1129 Runtime* runtime = Runtime::Current();
1130 runtime->SweepSystemWeaks(&visitor);
1131 }
1132
1133 class MarkSweep::CheckpointMarkThreadRoots : public Closure, public RootVisitor {
1134 public:
CheckpointMarkThreadRoots(MarkSweep * mark_sweep,bool revoke_ros_alloc_thread_local_buffers_at_checkpoint)1135 CheckpointMarkThreadRoots(MarkSweep* mark_sweep,
1136 bool revoke_ros_alloc_thread_local_buffers_at_checkpoint)
1137 : mark_sweep_(mark_sweep),
1138 revoke_ros_alloc_thread_local_buffers_at_checkpoint_(
1139 revoke_ros_alloc_thread_local_buffers_at_checkpoint) {
1140 }
1141
VisitRoots(mirror::Object *** roots,size_t count,const RootInfo & info)1142 void VisitRoots(mirror::Object*** roots,
1143 size_t count,
1144 [[maybe_unused]] const RootInfo& info) override
1145 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
1146 for (size_t i = 0; i < count; ++i) {
1147 mark_sweep_->MarkObjectNonNullParallel(*roots[i]);
1148 }
1149 }
1150
VisitRoots(mirror::CompressedReference<mirror::Object> ** roots,size_t count,const RootInfo & info)1151 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots,
1152 size_t count,
1153 [[maybe_unused]] const RootInfo& info) override
1154 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
1155 for (size_t i = 0; i < count; ++i) {
1156 mark_sweep_->MarkObjectNonNullParallel(roots[i]->AsMirrorPtr());
1157 }
1158 }
1159
Run(Thread * thread)1160 void Run(Thread* thread) override NO_THREAD_SAFETY_ANALYSIS {
1161 ScopedTrace trace("Marking thread roots");
1162 // Note: self is not necessarily equal to thread since thread may be suspended.
1163 Thread* const self = Thread::Current();
1164 CHECK(thread == self ||
1165 thread->IsSuspended() ||
1166 thread->GetState() == ThreadState::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, ThreadState::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) const1350 ALWAYS_INLINE void operator()(mirror::Object* obj,
1351 MemberOffset offset,
1352 [[maybe_unused]] bool is_static) const
1353 REQUIRES(Locks::heap_bitmap_lock_) REQUIRES_SHARED(Locks::mutator_lock_) {
1354 if (kCheckLocks) {
1355 Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
1356 Locks::heap_bitmap_lock_->AssertExclusiveHeld(Thread::Current());
1357 }
1358 mark_sweep_->MarkObject(obj->GetFieldObject<mirror::Object>(offset), obj, offset);
1359 }
1360
VisitRootIfNonNull(mirror::CompressedReference<mirror::Object> * root) const1361 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
1362 REQUIRES(Locks::heap_bitmap_lock_)
1363 REQUIRES_SHARED(Locks::mutator_lock_) {
1364 if (!root->IsNull()) {
1365 VisitRoot(root);
1366 }
1367 }
1368
VisitRoot(mirror::CompressedReference<mirror::Object> * root) const1369 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
1370 REQUIRES(Locks::heap_bitmap_lock_)
1371 REQUIRES_SHARED(Locks::mutator_lock_) {
1372 if (kCheckLocks) {
1373 Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
1374 Locks::heap_bitmap_lock_->AssertExclusiveHeld(Thread::Current());
1375 }
1376 mark_sweep_->MarkObject(root->AsMirrorPtr());
1377 }
1378
1379 private:
1380 MarkSweep* const mark_sweep_;
1381 };
1382
1383 // Scans an object reference. Determines the type of the reference
1384 // and dispatches to a specialized scanning routine.
ScanObject(mirror::Object * obj)1385 void MarkSweep::ScanObject(mirror::Object* obj) {
1386 MarkVisitor mark_visitor(this);
1387 DelayReferenceReferentVisitor ref_visitor(this);
1388 ScanObjectVisit(obj, mark_visitor, ref_visitor);
1389 }
1390
ProcessMarkStackParallel(size_t thread_count)1391 void MarkSweep::ProcessMarkStackParallel(size_t thread_count) {
1392 Thread* self = Thread::Current();
1393 ThreadPool* thread_pool = GetHeap()->GetThreadPool();
1394 const size_t chunk_size = std::min(mark_stack_->Size() / thread_count + 1,
1395 static_cast<size_t>(MarkStackTask<false>::kMaxSize));
1396 CHECK_GT(chunk_size, 0U);
1397 // Split the current mark stack up into work tasks.
1398 for (auto* it = mark_stack_->Begin(), *end = mark_stack_->End(); it < end; ) {
1399 const size_t delta = std::min(static_cast<size_t>(end - it), chunk_size);
1400 thread_pool->AddTask(self, new MarkStackTask<false>(thread_pool, this, delta, it));
1401 it += delta;
1402 }
1403 thread_pool->SetMaxActiveWorkers(thread_count - 1);
1404 thread_pool->StartWorkers(self);
1405 thread_pool->Wait(self, true, true);
1406 thread_pool->StopWorkers(self);
1407 mark_stack_->Reset();
1408 CHECK_EQ(work_chunks_created_.load(std::memory_order_seq_cst),
1409 work_chunks_deleted_.load(std::memory_order_seq_cst))
1410 << " some of the work chunks were leaked";
1411 }
1412
1413 // Scan anything that's on the mark stack.
ProcessMarkStack(bool paused)1414 void MarkSweep::ProcessMarkStack(bool paused) {
1415 TimingLogger::ScopedTiming t(paused ? "(Paused)ProcessMarkStack" : __FUNCTION__, GetTimings());
1416 size_t thread_count = GetThreadCount(paused);
1417 if (kParallelProcessMarkStack && thread_count > 1 &&
1418 mark_stack_->Size() >= kMinimumParallelMarkStackSize) {
1419 ProcessMarkStackParallel(thread_count);
1420 } else {
1421 // TODO: Tune this.
1422 static const size_t kFifoSize = 4;
1423 BoundedFifoPowerOfTwo<mirror::Object*, kFifoSize> prefetch_fifo;
1424 for (;;) {
1425 mirror::Object* obj = nullptr;
1426 if (kUseMarkStackPrefetch) {
1427 while (!mark_stack_->IsEmpty() && prefetch_fifo.size() < kFifoSize) {
1428 mirror::Object* mark_stack_obj = mark_stack_->PopBack();
1429 DCHECK(mark_stack_obj != nullptr);
1430 __builtin_prefetch(mark_stack_obj);
1431 prefetch_fifo.push_back(mark_stack_obj);
1432 }
1433 if (prefetch_fifo.empty()) {
1434 break;
1435 }
1436 obj = prefetch_fifo.front();
1437 prefetch_fifo.pop_front();
1438 } else {
1439 if (mark_stack_->IsEmpty()) {
1440 break;
1441 }
1442 obj = mark_stack_->PopBack();
1443 }
1444 DCHECK(obj != nullptr);
1445 ScanObject(obj);
1446 }
1447 }
1448 }
1449
IsMarked(mirror::Object * object)1450 inline mirror::Object* MarkSweep::IsMarked(mirror::Object* object) {
1451 if (immune_spaces_.IsInImmuneRegion(object)) {
1452 return object;
1453 }
1454 if (current_space_bitmap_->HasAddress(object)) {
1455 return current_space_bitmap_->Test(object) ? object : nullptr;
1456 }
1457 // This function returns nullptr for objects allocated after marking phase as
1458 // they are not marked in the bitmap.
1459 return mark_bitmap_->Test(object) ? object : nullptr;
1460 }
1461
FinishPhase()1462 void MarkSweep::FinishPhase() {
1463 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
1464 if (kCountScannedTypes) {
1465 VLOG(gc)
1466 << "MarkSweep scanned"
1467 << " no reference objects=" << no_reference_class_count_.load(std::memory_order_relaxed)
1468 << " normal objects=" << normal_count_.load(std::memory_order_relaxed)
1469 << " classes=" << class_count_.load(std::memory_order_relaxed)
1470 << " object arrays=" << object_array_count_.load(std::memory_order_relaxed)
1471 << " references=" << reference_count_.load(std::memory_order_relaxed)
1472 << " other=" << other_count_.load(std::memory_order_relaxed);
1473 }
1474 if (kCountTasks) {
1475 VLOG(gc)
1476 << "Total number of work chunks allocated: "
1477 << work_chunks_created_.load(std::memory_order_relaxed);
1478 }
1479 if (kMeasureOverhead) {
1480 VLOG(gc) << "Overhead time " << PrettyDuration(overhead_time_.load(std::memory_order_relaxed));
1481 }
1482 if (kProfileLargeObjects) {
1483 VLOG(gc)
1484 << "Large objects tested " << large_object_test_.load(std::memory_order_relaxed)
1485 << " marked " << large_object_mark_.load(std::memory_order_relaxed);
1486 }
1487 if (kCountMarkedObjects) {
1488 VLOG(gc)
1489 << "Marked: null=" << mark_null_count_.load(std::memory_order_relaxed)
1490 << " immune=" << mark_immune_count_.load(std::memory_order_relaxed)
1491 << " fastpath=" << mark_fastpath_count_.load(std::memory_order_relaxed)
1492 << " slowpath=" << mark_slowpath_count_.load(std::memory_order_relaxed);
1493 }
1494 CHECK(mark_stack_->IsEmpty()); // Ensure that the mark stack is empty.
1495 mark_stack_->Reset();
1496 Thread* const self = Thread::Current();
1497 ReaderMutexLock mu(self, *Locks::mutator_lock_);
1498 WriterMutexLock mu2(self, *Locks::heap_bitmap_lock_);
1499 heap_->ClearMarkedObjects();
1500 }
1501
RevokeAllThreadLocalBuffers()1502 void MarkSweep::RevokeAllThreadLocalBuffers() {
1503 if (kRevokeRosAllocThreadLocalBuffersAtCheckpoint && IsConcurrent()) {
1504 // If concurrent, rosalloc thread-local buffers are revoked at the
1505 // thread checkpoint. Bump pointer space thread-local buffers must
1506 // not be in use.
1507 GetHeap()->AssertAllBumpPointerSpaceThreadLocalBuffersAreRevoked();
1508 } else {
1509 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
1510 GetHeap()->RevokeAllThreadLocalBuffers();
1511 }
1512 }
1513
1514 } // namespace collector
1515 } // namespace gc
1516 } // namespace art
1517