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