mark_sweep.cc revision 62ab87bb3ff4830def25a1716f6785256c7eebca
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 <functional> 20#include <numeric> 21#include <climits> 22#include <vector> 23 24#include "base/bounded_fifo.h" 25#include "base/logging.h" 26#include "base/macros.h" 27#include "base/mutex-inl.h" 28#include "base/timing_logger.h" 29#include "gc/accounting/card_table-inl.h" 30#include "gc/accounting/heap_bitmap-inl.h" 31#include "gc/accounting/mod_union_table.h" 32#include "gc/accounting/space_bitmap-inl.h" 33#include "gc/heap.h" 34#include "gc/space/image_space.h" 35#include "gc/space/large_object_space.h" 36#include "gc/space/space-inl.h" 37#include "mark_sweep-inl.h" 38#include "mirror/art_field-inl.h" 39#include "mirror/object-inl.h" 40#include "runtime.h" 41#include "scoped_thread_state_change.h" 42#include "thread-inl.h" 43#include "thread_list.h" 44 45using ::art::mirror::ArtField; 46using ::art::mirror::Class; 47using ::art::mirror::Object; 48using ::art::mirror::ObjectArray; 49 50namespace art { 51namespace gc { 52namespace collector { 53 54// Performance options. 55static constexpr bool kUseRecursiveMark = false; 56static constexpr bool kUseMarkStackPrefetch = true; 57static constexpr size_t kSweepArrayChunkFreeSize = 1024; 58static constexpr bool kPreCleanCards = true; 59 60// Parallelism options. 61static constexpr bool kParallelCardScan = true; 62static constexpr bool kParallelRecursiveMark = true; 63// Don't attempt to parallelize mark stack processing unless the mark stack is at least n 64// elements. This is temporary until we reduce the overhead caused by allocating tasks, etc.. Not 65// having this can add overhead in ProcessReferences since we may end up doing many calls of 66// ProcessMarkStack with very small mark stacks. 67static constexpr size_t kMinimumParallelMarkStackSize = 128; 68static constexpr bool kParallelProcessMarkStack = true; 69 70// Profiling and information flags. 71static constexpr bool kProfileLargeObjects = false; 72static constexpr bool kMeasureOverhead = false; 73static constexpr bool kCountTasks = false; 74static constexpr bool kCountJavaLangRefs = false; 75static constexpr bool kCountMarkedObjects = false; 76 77// Turn off kCheckLocks when profiling the GC since it slows the GC down by up to 40%. 78static constexpr bool kCheckLocks = kDebugLocking; 79static constexpr bool kVerifyRootsMarked = kIsDebugBuild; 80 81// If true, revoke the rosalloc thread-local buffers at the 82// checkpoint, as opposed to during the pause. 83static constexpr bool kRevokeRosAllocThreadLocalBuffersAtCheckpoint = true; 84 85void MarkSweep::BindBitmaps() { 86 timings_.StartSplit("BindBitmaps"); 87 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_); 88 // Mark all of the spaces we never collect as immune. 89 for (const auto& space : GetHeap()->GetContinuousSpaces()) { 90 if (space->GetGcRetentionPolicy() == space::kGcRetentionPolicyNeverCollect) { 91 CHECK(immune_region_.AddContinuousSpace(space)) << "Failed to add space " << *space; 92 } 93 } 94 timings_.EndSplit(); 95} 96 97MarkSweep::MarkSweep(Heap* heap, bool is_concurrent, const std::string& name_prefix) 98 : GarbageCollector(heap, 99 name_prefix + 100 (is_concurrent ? "concurrent mark sweep": "mark sweep")), 101 gc_barrier_(new Barrier(0)), 102 mark_stack_lock_("mark sweep mark stack lock", kMarkSweepMarkStackLock), 103 is_concurrent_(is_concurrent) { 104} 105 106void MarkSweep::InitializePhase() { 107 TimingLogger::ScopedSplit split("InitializePhase", &timings_); 108 mark_stack_ = heap_->mark_stack_.get(); 109 DCHECK(mark_stack_ != nullptr); 110 immune_region_.Reset(); 111 class_count_ = 0; 112 array_count_ = 0; 113 other_count_ = 0; 114 large_object_test_ = 0; 115 large_object_mark_ = 0; 116 overhead_time_ = 0; 117 work_chunks_created_ = 0; 118 work_chunks_deleted_ = 0; 119 reference_count_ = 0; 120 mark_null_count_ = 0; 121 mark_immune_count_ = 0; 122 mark_fastpath_count_ = 0; 123 mark_slowpath_count_ = 0; 124 { 125 // TODO: I don't think we should need heap bitmap lock to get the mark bitmap. 126 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_); 127 mark_bitmap_ = heap_->GetMarkBitmap(); 128 } 129 if (!clear_soft_references_) { 130 // Always clear soft references if a non-sticky collection. 131 clear_soft_references_ = GetGcType() != collector::kGcTypeSticky; 132 } 133 // Do any pre GC verification. 134 timings_.NewSplit("PreGcVerification"); 135 heap_->PreGcVerification(this); 136} 137 138void MarkSweep::ProcessReferences(Thread* self) { 139 TimingLogger::ScopedSplit split("ProcessReferences", &timings_); 140 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_); 141 GetHeap()->ProcessReferences(timings_, clear_soft_references_, &IsMarkedCallback, 142 &MarkObjectCallback, &ProcessMarkStackPausedCallback, this); 143} 144 145void MarkSweep::PreProcessReferences() { 146 if (IsConcurrent()) { 147 // No reason to do this for non-concurrent GC since pre processing soft references only helps 148 // pauses. 149 timings_.NewSplit("PreProcessReferences"); 150 GetHeap()->ProcessSoftReferences(timings_, clear_soft_references_, &IsMarkedCallback, 151 &MarkObjectCallback, &ProcessMarkStackPausedCallback, this); 152 } 153} 154 155void MarkSweep::PausePhase() { 156 TimingLogger::ScopedSplit split("(Paused)PausePhase", &timings_); 157 Thread* self = Thread::Current(); 158 Locks::mutator_lock_->AssertExclusiveHeld(self); 159 if (IsConcurrent()) { 160 // Handle the dirty objects if we are a concurrent GC. 161 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_); 162 // Re-mark root set. 163 ReMarkRoots(); 164 // Scan dirty objects, this is only required if we are not doing concurrent GC. 165 RecursiveMarkDirtyObjects(true, accounting::CardTable::kCardDirty); 166 } 167 ProcessReferences(self); 168 { 169 timings_.NewSplit("SwapStacks"); 170 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_); 171 heap_->SwapStacks(self); 172 live_stack_freeze_size_ = heap_->GetLiveStack()->Size(); 173 // Need to revoke all the thread local allocation stacks since we just swapped the allocation 174 // stacks and don't want anybody to allocate into the live stack. 175 RevokeAllThreadLocalAllocationStacks(self); 176 } 177 timings_.StartSplit("PreSweepingGcVerification"); 178 heap_->PreSweepingGcVerification(this); 179 timings_.EndSplit(); 180 if (IsConcurrent()) { 181 // Disallow new system weaks to prevent a race which occurs when someone adds a new system 182 // weak before we sweep them. Since this new system weak may not be marked, the GC may 183 // incorrectly sweep it. This also fixes a race where interning may attempt to return a strong 184 // reference to a string that is about to be swept. 185 Runtime::Current()->DisallowNewSystemWeaks(); 186 } 187} 188 189void MarkSweep::PreCleanCards() { 190 // Don't do this for non concurrent GCs since they don't have any dirty cards. 191 if (kPreCleanCards && IsConcurrent()) { 192 Thread* self = Thread::Current(); 193 CHECK(!Locks::mutator_lock_->IsExclusiveHeld(self)); 194 // Process dirty cards and add dirty cards to mod union tables, also ages cards. 195 heap_->ProcessCards(timings_, false); 196 // The checkpoint root marking is required to avoid a race condition which occurs if the 197 // following happens during a reference write: 198 // 1. mutator dirties the card (write barrier) 199 // 2. GC ages the card (the above ProcessCards call) 200 // 3. GC scans the object (the RecursiveMarkDirtyObjects call below) 201 // 4. mutator writes the value (corresponding to the write barrier in 1.) 202 // This causes the GC to age the card but not necessarily mark the reference which the mutator 203 // wrote into the object stored in the card. 204 // Having the checkpoint fixes this issue since it ensures that the card mark and the 205 // reference write are visible to the GC before the card is scanned (this is due to locks being 206 // acquired / released in the checkpoint code). 207 // The other roots are also marked to help reduce the pause. 208 MarkRootsCheckpoint(self, false); 209 MarkNonThreadRoots(); 210 MarkConcurrentRoots( 211 static_cast<VisitRootFlags>(kVisitRootFlagClearRootLog | kVisitRootFlagNewRoots)); 212 // Process the newly aged cards. 213 RecursiveMarkDirtyObjects(false, accounting::CardTable::kCardDirty - 1); 214 // TODO: Empty allocation stack to reduce the number of objects we need to test / mark as live 215 // in the next GC. 216 } 217} 218 219void MarkSweep::RevokeAllThreadLocalAllocationStacks(Thread* self) { 220 if (kUseThreadLocalAllocationStack) { 221 timings_.NewSplit("RevokeAllThreadLocalAllocationStacks"); 222 Locks::mutator_lock_->AssertExclusiveHeld(self); 223 heap_->RevokeAllThreadLocalAllocationStacks(self); 224 } 225} 226 227void MarkSweep::MarkingPhase() { 228 TimingLogger::ScopedSplit split("MarkingPhase", &timings_); 229 Thread* self = Thread::Current(); 230 231 BindBitmaps(); 232 FindDefaultSpaceBitmap(); 233 234 // Process dirty cards and add dirty cards to mod union tables. 235 heap_->ProcessCards(timings_, false); 236 237 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_); 238 MarkRoots(self); 239 MarkReachableObjects(); 240 // Pre-clean dirtied cards to reduce pauses. 241 PreCleanCards(); 242 PreProcessReferences(); 243} 244 245void MarkSweep::UpdateAndMarkModUnion() { 246 for (const auto& space : heap_->GetContinuousSpaces()) { 247 if (immune_region_.ContainsSpace(space)) { 248 const char* name = space->IsZygoteSpace() ? "UpdateAndMarkZygoteModUnionTable" : 249 "UpdateAndMarkImageModUnionTable"; 250 TimingLogger::ScopedSplit split(name, &timings_); 251 accounting::ModUnionTable* mod_union_table = heap_->FindModUnionTableFromSpace(space); 252 CHECK(mod_union_table != nullptr); 253 mod_union_table->UpdateAndMarkReferences(MarkHeapReferenceCallback, this); 254 } 255 } 256} 257 258void MarkSweep::MarkReachableObjects() { 259 UpdateAndMarkModUnion(); 260 // Recursively mark all the non-image bits set in the mark bitmap. 261 RecursiveMark(); 262} 263 264void MarkSweep::ReclaimPhase() { 265 TimingLogger::ScopedSplit split("ReclaimPhase", &timings_); 266 Thread* self = Thread::Current(); 267 SweepSystemWeaks(self); 268 if (IsConcurrent()) { 269 Runtime::Current()->AllowNewSystemWeaks(); 270 } 271 { 272 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_); 273 274 // Reclaim unmarked objects. 275 Sweep(false); 276 277 // Swap the live and mark bitmaps for each space which we modified space. This is an 278 // optimization that enables us to not clear live bits inside of the sweep. Only swaps unbound 279 // bitmaps. 280 timings_.StartSplit("SwapBitmaps"); 281 SwapBitmaps(); 282 timings_.EndSplit(); 283 284 // Unbind the live and mark bitmaps. 285 TimingLogger::ScopedSplit split("UnBindBitmaps", &timings_); 286 GetHeap()->UnBindBitmaps(); 287 } 288} 289 290void MarkSweep::FindDefaultSpaceBitmap() { 291 TimingLogger::ScopedSplit split("FindDefaultMarkBitmap", &timings_); 292 for (const auto& space : GetHeap()->GetContinuousSpaces()) { 293 accounting::ContinuousSpaceBitmap* bitmap = space->GetMarkBitmap(); 294 // We want to have the main space instead of non moving if possible. 295 if (bitmap != nullptr && 296 space->GetGcRetentionPolicy() == space::kGcRetentionPolicyAlwaysCollect) { 297 current_space_bitmap_ = bitmap; 298 // If we are not the non moving space exit the loop early since this will be good enough. 299 if (space != heap_->GetNonMovingSpace()) { 300 break; 301 } 302 } 303 } 304 if (current_space_bitmap_ == nullptr) { 305 heap_->DumpSpaces(); 306 LOG(FATAL) << "Could not find a default mark bitmap"; 307 } 308} 309 310void MarkSweep::ExpandMarkStack() { 311 ResizeMarkStack(mark_stack_->Capacity() * 2); 312} 313 314void MarkSweep::ResizeMarkStack(size_t new_size) { 315 // Rare case, no need to have Thread::Current be a parameter. 316 if (UNLIKELY(mark_stack_->Size() < mark_stack_->Capacity())) { 317 // Someone else acquired the lock and expanded the mark stack before us. 318 return; 319 } 320 std::vector<Object*> temp(mark_stack_->Begin(), mark_stack_->End()); 321 CHECK_LE(mark_stack_->Size(), new_size); 322 mark_stack_->Resize(new_size); 323 for (const auto& obj : temp) { 324 mark_stack_->PushBack(obj); 325 } 326} 327 328inline void MarkSweep::MarkObjectNonNullParallel(Object* obj) { 329 DCHECK(obj != nullptr); 330 if (MarkObjectParallel(obj)) { 331 MutexLock mu(Thread::Current(), mark_stack_lock_); 332 if (UNLIKELY(mark_stack_->Size() >= mark_stack_->Capacity())) { 333 ExpandMarkStack(); 334 } 335 // The object must be pushed on to the mark stack. 336 mark_stack_->PushBack(obj); 337 } 338} 339 340mirror::Object* MarkSweep::MarkObjectCallback(mirror::Object* obj, void* arg) { 341 MarkSweep* mark_sweep = reinterpret_cast<MarkSweep*>(arg); 342 mark_sweep->MarkObject(obj); 343 return obj; 344} 345 346void MarkSweep::MarkHeapReferenceCallback(mirror::HeapReference<mirror::Object>* ref, void* arg) { 347 reinterpret_cast<MarkSweep*>(arg)->MarkObject(ref->AsMirrorPtr()); 348} 349 350class MarkSweepMarkObjectSlowPath { 351 public: 352 explicit MarkSweepMarkObjectSlowPath(MarkSweep* mark_sweep) : mark_sweep_(mark_sweep) { 353 } 354 355 void operator()(const Object* obj) const ALWAYS_INLINE { 356 if (kProfileLargeObjects) { 357 // TODO: Differentiate between marking and testing somehow. 358 ++mark_sweep_->large_object_test_; 359 ++mark_sweep_->large_object_mark_; 360 } 361 space::LargeObjectSpace* large_object_space = mark_sweep_->GetHeap()->GetLargeObjectsSpace(); 362 if (UNLIKELY(!IsAligned<kPageSize>(obj) || 363 (kIsDebugBuild && !large_object_space->Contains(obj)))) { 364 LOG(ERROR) << "Tried to mark " << obj << " not contained by any spaces"; 365 LOG(ERROR) << "Attempting see if it's a bad root"; 366 mark_sweep_->VerifyRoots(); 367 LOG(FATAL) << "Can't mark invalid object"; 368 } 369 } 370 371 private: 372 MarkSweep* const mark_sweep_; 373}; 374 375inline void MarkSweep::MarkObjectNonNull(Object* obj) { 376 DCHECK(obj != nullptr); 377 if (kUseBakerOrBrooksReadBarrier) { 378 // Verify all the objects have the correct pointer installed. 379 obj->AssertReadBarrierPointer(); 380 } 381 if (immune_region_.ContainsObject(obj)) { 382 if (kCountMarkedObjects) { 383 ++mark_immune_count_; 384 } 385 DCHECK(mark_bitmap_->Test(obj)); 386 } else if (LIKELY(current_space_bitmap_->HasAddress(obj))) { 387 if (kCountMarkedObjects) { 388 ++mark_fastpath_count_; 389 } 390 if (UNLIKELY(!current_space_bitmap_->Set(obj))) { 391 PushOnMarkStack(obj); // This object was not previously marked. 392 } 393 } else { 394 if (kCountMarkedObjects) { 395 ++mark_slowpath_count_; 396 } 397 MarkSweepMarkObjectSlowPath visitor(this); 398 // TODO: We already know that the object is not in the current_space_bitmap_ but MarkBitmap::Set 399 // will check again. 400 if (!mark_bitmap_->Set(obj, visitor)) { 401 PushOnMarkStack(obj); // Was not already marked, push. 402 } 403 } 404} 405 406inline void MarkSweep::PushOnMarkStack(Object* obj) { 407 if (UNLIKELY(mark_stack_->Size() >= mark_stack_->Capacity())) { 408 // Lock is not needed but is here anyways to please annotalysis. 409 MutexLock mu(Thread::Current(), mark_stack_lock_); 410 ExpandMarkStack(); 411 } 412 // The object must be pushed on to the mark stack. 413 mark_stack_->PushBack(obj); 414} 415 416inline bool MarkSweep::MarkObjectParallel(const Object* obj) { 417 DCHECK(obj != nullptr); 418 if (kUseBakerOrBrooksReadBarrier) { 419 // Verify all the objects have the correct pointer installed. 420 obj->AssertReadBarrierPointer(); 421 } 422 if (immune_region_.ContainsObject(obj)) { 423 DCHECK(IsMarked(obj)); 424 return false; 425 } 426 // Try to take advantage of locality of references within a space, failing this find the space 427 // the hard way. 428 accounting::ContinuousSpaceBitmap* object_bitmap = current_space_bitmap_; 429 if (LIKELY(object_bitmap->HasAddress(obj))) { 430 return !object_bitmap->AtomicTestAndSet(obj); 431 } 432 MarkSweepMarkObjectSlowPath visitor(this); 433 return !mark_bitmap_->AtomicTestAndSet(obj, visitor); 434} 435 436// Used to mark objects when processing the mark stack. If an object is null, it is not marked. 437inline void MarkSweep::MarkObject(Object* obj) { 438 if (obj != nullptr) { 439 MarkObjectNonNull(obj); 440 } else if (kCountMarkedObjects) { 441 ++mark_null_count_; 442 } 443} 444 445void MarkSweep::MarkRootParallelCallback(Object** root, void* arg, uint32_t /*thread_id*/, 446 RootType /*root_type*/) { 447 reinterpret_cast<MarkSweep*>(arg)->MarkObjectNonNullParallel(*root); 448} 449 450void MarkSweep::VerifyRootMarked(Object** root, void* arg, uint32_t /*thread_id*/, 451 RootType /*root_type*/) { 452 CHECK(reinterpret_cast<MarkSweep*>(arg)->IsMarked(*root)); 453} 454 455void MarkSweep::MarkRootCallback(Object** root, void* arg, uint32_t /*thread_id*/, 456 RootType /*root_type*/) { 457 reinterpret_cast<MarkSweep*>(arg)->MarkObjectNonNull(*root); 458} 459 460void MarkSweep::VerifyRootCallback(const Object* root, void* arg, size_t vreg, 461 const StackVisitor* visitor, RootType root_type) { 462 reinterpret_cast<MarkSweep*>(arg)->VerifyRoot(root, vreg, visitor, root_type); 463} 464 465void MarkSweep::VerifyRoot(const Object* root, size_t vreg, const StackVisitor* visitor, 466 RootType root_type) { 467 // See if the root is on any space bitmap. 468 if (heap_->GetLiveBitmap()->GetContinuousSpaceBitmap(root) == nullptr) { 469 space::LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace(); 470 if (!large_object_space->Contains(root)) { 471 LOG(ERROR) << "Found invalid root: " << root << " with type " << root_type; 472 if (visitor != NULL) { 473 LOG(ERROR) << visitor->DescribeLocation() << " in VReg: " << vreg; 474 } 475 } 476 } 477} 478 479void MarkSweep::VerifyRoots() { 480 Runtime::Current()->GetThreadList()->VerifyRoots(VerifyRootCallback, this); 481} 482 483void MarkSweep::MarkRoots(Thread* self) { 484 if (Locks::mutator_lock_->IsExclusiveHeld(self)) { 485 // If we exclusively hold the mutator lock, all threads must be suspended. 486 timings_.StartSplit("MarkRoots"); 487 Runtime::Current()->VisitRoots(MarkRootCallback, this); 488 timings_.EndSplit(); 489 RevokeAllThreadLocalAllocationStacks(self); 490 } else { 491 MarkRootsCheckpoint(self, kRevokeRosAllocThreadLocalBuffersAtCheckpoint); 492 // At this point the live stack should no longer have any mutators which push into it. 493 MarkNonThreadRoots(); 494 MarkConcurrentRoots( 495 static_cast<VisitRootFlags>(kVisitRootFlagAllRoots | kVisitRootFlagStartLoggingNewRoots)); 496 } 497} 498 499void MarkSweep::MarkNonThreadRoots() { 500 timings_.StartSplit("MarkNonThreadRoots"); 501 Runtime::Current()->VisitNonThreadRoots(MarkRootCallback, this); 502 timings_.EndSplit(); 503} 504 505void MarkSweep::MarkConcurrentRoots(VisitRootFlags flags) { 506 timings_.StartSplit("MarkConcurrentRoots"); 507 // Visit all runtime roots and clear dirty flags. 508 Runtime::Current()->VisitConcurrentRoots(MarkRootCallback, this, flags); 509 timings_.EndSplit(); 510} 511 512class ScanObjectVisitor { 513 public: 514 explicit ScanObjectVisitor(MarkSweep* const mark_sweep) ALWAYS_INLINE 515 : mark_sweep_(mark_sweep) {} 516 517 void operator()(Object* obj) const ALWAYS_INLINE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) 518 EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) { 519 if (kCheckLocks) { 520 Locks::mutator_lock_->AssertSharedHeld(Thread::Current()); 521 Locks::heap_bitmap_lock_->AssertExclusiveHeld(Thread::Current()); 522 } 523 mark_sweep_->ScanObject(obj); 524 } 525 526 private: 527 MarkSweep* const mark_sweep_; 528}; 529 530class DelayReferenceReferentVisitor { 531 public: 532 explicit DelayReferenceReferentVisitor(MarkSweep* collector) : collector_(collector) { 533 } 534 535 void operator()(mirror::Class* klass, mirror::Reference* ref) const 536 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) 537 EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) { 538 collector_->DelayReferenceReferent(klass, ref); 539 } 540 541 private: 542 MarkSweep* const collector_; 543}; 544 545template <bool kUseFinger = false> 546class MarkStackTask : public Task { 547 public: 548 MarkStackTask(ThreadPool* thread_pool, MarkSweep* mark_sweep, size_t mark_stack_size, 549 Object** mark_stack) 550 : mark_sweep_(mark_sweep), 551 thread_pool_(thread_pool), 552 mark_stack_pos_(mark_stack_size) { 553 // We may have to copy part of an existing mark stack when another mark stack overflows. 554 if (mark_stack_size != 0) { 555 DCHECK(mark_stack != NULL); 556 // TODO: Check performance? 557 std::copy(mark_stack, mark_stack + mark_stack_size, mark_stack_); 558 } 559 if (kCountTasks) { 560 ++mark_sweep_->work_chunks_created_; 561 } 562 } 563 564 static const size_t kMaxSize = 1 * KB; 565 566 protected: 567 class MarkObjectParallelVisitor { 568 public: 569 explicit MarkObjectParallelVisitor(MarkStackTask<kUseFinger>* chunk_task, 570 MarkSweep* mark_sweep) ALWAYS_INLINE 571 : chunk_task_(chunk_task), mark_sweep_(mark_sweep) {} 572 573 void operator()(Object* obj, MemberOffset offset, bool /* static */) const ALWAYS_INLINE 574 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 575 mirror::Object* ref = obj->GetFieldObject<mirror::Object>(offset, false); 576 if (ref != nullptr && mark_sweep_->MarkObjectParallel(ref)) { 577 if (kUseFinger) { 578 android_memory_barrier(); 579 if (reinterpret_cast<uintptr_t>(ref) >= 580 static_cast<uintptr_t>(mark_sweep_->atomic_finger_)) { 581 return; 582 } 583 } 584 chunk_task_->MarkStackPush(ref); 585 } 586 } 587 588 private: 589 MarkStackTask<kUseFinger>* const chunk_task_; 590 MarkSweep* const mark_sweep_; 591 }; 592 593 class ScanObjectParallelVisitor { 594 public: 595 explicit ScanObjectParallelVisitor(MarkStackTask<kUseFinger>* chunk_task) ALWAYS_INLINE 596 : chunk_task_(chunk_task) {} 597 598 // No thread safety analysis since multiple threads will use this visitor. 599 void operator()(Object* obj) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) 600 EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) { 601 MarkSweep* const mark_sweep = chunk_task_->mark_sweep_; 602 MarkObjectParallelVisitor mark_visitor(chunk_task_, mark_sweep); 603 DelayReferenceReferentVisitor ref_visitor(mark_sweep); 604 mark_sweep->ScanObjectVisit(obj, mark_visitor, ref_visitor); 605 } 606 607 private: 608 MarkStackTask<kUseFinger>* const chunk_task_; 609 }; 610 611 virtual ~MarkStackTask() { 612 // Make sure that we have cleared our mark stack. 613 DCHECK_EQ(mark_stack_pos_, 0U); 614 if (kCountTasks) { 615 ++mark_sweep_->work_chunks_deleted_; 616 } 617 } 618 619 MarkSweep* const mark_sweep_; 620 ThreadPool* const thread_pool_; 621 // Thread local mark stack for this task. 622 Object* mark_stack_[kMaxSize]; 623 // Mark stack position. 624 size_t mark_stack_pos_; 625 626 void MarkStackPush(Object* obj) ALWAYS_INLINE { 627 if (UNLIKELY(mark_stack_pos_ == kMaxSize)) { 628 // Mark stack overflow, give 1/2 the stack to the thread pool as a new work task. 629 mark_stack_pos_ /= 2; 630 auto* task = new MarkStackTask(thread_pool_, mark_sweep_, kMaxSize - mark_stack_pos_, 631 mark_stack_ + mark_stack_pos_); 632 thread_pool_->AddTask(Thread::Current(), task); 633 } 634 DCHECK(obj != nullptr); 635 DCHECK_LT(mark_stack_pos_, kMaxSize); 636 mark_stack_[mark_stack_pos_++] = obj; 637 } 638 639 virtual void Finalize() { 640 delete this; 641 } 642 643 // Scans all of the objects 644 virtual void Run(Thread* self) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) 645 EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) { 646 ScanObjectParallelVisitor visitor(this); 647 // TODO: Tune this. 648 static const size_t kFifoSize = 4; 649 BoundedFifoPowerOfTwo<Object*, kFifoSize> prefetch_fifo; 650 for (;;) { 651 Object* obj = nullptr; 652 if (kUseMarkStackPrefetch) { 653 while (mark_stack_pos_ != 0 && prefetch_fifo.size() < kFifoSize) { 654 Object* obj = mark_stack_[--mark_stack_pos_]; 655 DCHECK(obj != nullptr); 656 __builtin_prefetch(obj); 657 prefetch_fifo.push_back(obj); 658 } 659 if (UNLIKELY(prefetch_fifo.empty())) { 660 break; 661 } 662 obj = prefetch_fifo.front(); 663 prefetch_fifo.pop_front(); 664 } else { 665 if (UNLIKELY(mark_stack_pos_ == 0)) { 666 break; 667 } 668 obj = mark_stack_[--mark_stack_pos_]; 669 } 670 DCHECK(obj != nullptr); 671 visitor(obj); 672 } 673 } 674}; 675 676class CardScanTask : public MarkStackTask<false> { 677 public: 678 CardScanTask(ThreadPool* thread_pool, MarkSweep* mark_sweep, 679 accounting::ContinuousSpaceBitmap* bitmap, 680 byte* begin, byte* end, byte minimum_age, size_t mark_stack_size, 681 Object** mark_stack_obj) 682 : MarkStackTask<false>(thread_pool, mark_sweep, mark_stack_size, mark_stack_obj), 683 bitmap_(bitmap), 684 begin_(begin), 685 end_(end), 686 minimum_age_(minimum_age) { 687 } 688 689 protected: 690 accounting::ContinuousSpaceBitmap* const bitmap_; 691 byte* const begin_; 692 byte* const end_; 693 const byte minimum_age_; 694 695 virtual void Finalize() { 696 delete this; 697 } 698 699 virtual void Run(Thread* self) NO_THREAD_SAFETY_ANALYSIS { 700 ScanObjectParallelVisitor visitor(this); 701 accounting::CardTable* card_table = mark_sweep_->GetHeap()->GetCardTable(); 702 size_t cards_scanned = card_table->Scan(bitmap_, begin_, end_, visitor, minimum_age_); 703 VLOG(heap) << "Parallel scanning cards " << reinterpret_cast<void*>(begin_) << " - " 704 << reinterpret_cast<void*>(end_) << " = " << cards_scanned; 705 // Finish by emptying our local mark stack. 706 MarkStackTask::Run(self); 707 } 708}; 709 710size_t MarkSweep::GetThreadCount(bool paused) const { 711 if (heap_->GetThreadPool() == nullptr || !heap_->CareAboutPauseTimes()) { 712 return 1; 713 } 714 if (paused) { 715 return heap_->GetParallelGCThreadCount() + 1; 716 } else { 717 return heap_->GetConcGCThreadCount() + 1; 718 } 719} 720 721void MarkSweep::ScanGrayObjects(bool paused, byte minimum_age) { 722 accounting::CardTable* card_table = GetHeap()->GetCardTable(); 723 ThreadPool* thread_pool = GetHeap()->GetThreadPool(); 724 size_t thread_count = GetThreadCount(paused); 725 // The parallel version with only one thread is faster for card scanning, TODO: fix. 726 if (kParallelCardScan && thread_count > 1) { 727 Thread* self = Thread::Current(); 728 // Can't have a different split for each space since multiple spaces can have their cards being 729 // scanned at the same time. 730 timings_.StartSplit(paused ? "(Paused)ScanGrayObjects" : "ScanGrayObjects"); 731 // Try to take some of the mark stack since we can pass this off to the worker tasks. 732 Object** mark_stack_begin = mark_stack_->Begin(); 733 Object** mark_stack_end = mark_stack_->End(); 734 const size_t mark_stack_size = mark_stack_end - mark_stack_begin; 735 // Estimated number of work tasks we will create. 736 const size_t mark_stack_tasks = GetHeap()->GetContinuousSpaces().size() * thread_count; 737 DCHECK_NE(mark_stack_tasks, 0U); 738 const size_t mark_stack_delta = std::min(CardScanTask::kMaxSize / 2, 739 mark_stack_size / mark_stack_tasks + 1); 740 for (const auto& space : GetHeap()->GetContinuousSpaces()) { 741 if (space->GetMarkBitmap() == nullptr) { 742 continue; 743 } 744 byte* card_begin = space->Begin(); 745 byte* card_end = space->End(); 746 // Align up the end address. For example, the image space's end 747 // may not be card-size-aligned. 748 card_end = AlignUp(card_end, accounting::CardTable::kCardSize); 749 DCHECK(IsAligned<accounting::CardTable::kCardSize>(card_begin)); 750 DCHECK(IsAligned<accounting::CardTable::kCardSize>(card_end)); 751 // Calculate how many bytes of heap we will scan, 752 const size_t address_range = card_end - card_begin; 753 // Calculate how much address range each task gets. 754 const size_t card_delta = RoundUp(address_range / thread_count + 1, 755 accounting::CardTable::kCardSize); 756 // Create the worker tasks for this space. 757 while (card_begin != card_end) { 758 // Add a range of cards. 759 size_t addr_remaining = card_end - card_begin; 760 size_t card_increment = std::min(card_delta, addr_remaining); 761 // Take from the back of the mark stack. 762 size_t mark_stack_remaining = mark_stack_end - mark_stack_begin; 763 size_t mark_stack_increment = std::min(mark_stack_delta, mark_stack_remaining); 764 mark_stack_end -= mark_stack_increment; 765 mark_stack_->PopBackCount(static_cast<int32_t>(mark_stack_increment)); 766 DCHECK_EQ(mark_stack_end, mark_stack_->End()); 767 // Add the new task to the thread pool. 768 auto* task = new CardScanTask(thread_pool, this, space->GetMarkBitmap(), card_begin, 769 card_begin + card_increment, minimum_age, 770 mark_stack_increment, mark_stack_end); 771 thread_pool->AddTask(self, task); 772 card_begin += card_increment; 773 } 774 } 775 776 // Note: the card scan below may dirty new cards (and scan them) 777 // as a side effect when a Reference object is encountered and 778 // queued during the marking. See b/11465268. 779 thread_pool->SetMaxActiveWorkers(thread_count - 1); 780 thread_pool->StartWorkers(self); 781 thread_pool->Wait(self, true, true); 782 thread_pool->StopWorkers(self); 783 timings_.EndSplit(); 784 } else { 785 for (const auto& space : GetHeap()->GetContinuousSpaces()) { 786 if (space->GetMarkBitmap() != nullptr) { 787 // Image spaces are handled properly since live == marked for them. 788 switch (space->GetGcRetentionPolicy()) { 789 case space::kGcRetentionPolicyNeverCollect: 790 timings_.StartSplit(paused ? "(Paused)ScanGrayImageSpaceObjects" : 791 "ScanGrayImageSpaceObjects"); 792 break; 793 case space::kGcRetentionPolicyFullCollect: 794 timings_.StartSplit(paused ? "(Paused)ScanGrayZygoteSpaceObjects" : 795 "ScanGrayZygoteSpaceObjects"); 796 break; 797 case space::kGcRetentionPolicyAlwaysCollect: 798 timings_.StartSplit(paused ? "(Paused)ScanGrayAllocSpaceObjects" : 799 "ScanGrayAllocSpaceObjects"); 800 break; 801 } 802 ScanObjectVisitor visitor(this); 803 card_table->Scan(space->GetMarkBitmap(), space->Begin(), space->End(), visitor, minimum_age); 804 timings_.EndSplit(); 805 } 806 } 807 } 808} 809 810class RecursiveMarkTask : public MarkStackTask<false> { 811 public: 812 RecursiveMarkTask(ThreadPool* thread_pool, MarkSweep* mark_sweep, 813 accounting::ContinuousSpaceBitmap* bitmap, uintptr_t begin, uintptr_t end) 814 : MarkStackTask<false>(thread_pool, mark_sweep, 0, NULL), 815 bitmap_(bitmap), 816 begin_(begin), 817 end_(end) { 818 } 819 820 protected: 821 accounting::ContinuousSpaceBitmap* const bitmap_; 822 const uintptr_t begin_; 823 const uintptr_t end_; 824 825 virtual void Finalize() { 826 delete this; 827 } 828 829 // Scans all of the objects 830 virtual void Run(Thread* self) NO_THREAD_SAFETY_ANALYSIS { 831 ScanObjectParallelVisitor visitor(this); 832 bitmap_->VisitMarkedRange(begin_, end_, visitor); 833 // Finish by emptying our local mark stack. 834 MarkStackTask::Run(self); 835 } 836}; 837 838// Populates the mark stack based on the set of marked objects and 839// recursively marks until the mark stack is emptied. 840void MarkSweep::RecursiveMark() { 841 TimingLogger::ScopedSplit split("RecursiveMark", &timings_); 842 // RecursiveMark will build the lists of known instances of the Reference classes. See 843 // DelayReferenceReferent for details. 844 if (kUseRecursiveMark) { 845 const bool partial = GetGcType() == kGcTypePartial; 846 ScanObjectVisitor scan_visitor(this); 847 auto* self = Thread::Current(); 848 ThreadPool* thread_pool = heap_->GetThreadPool(); 849 size_t thread_count = GetThreadCount(false); 850 const bool parallel = kParallelRecursiveMark && thread_count > 1; 851 mark_stack_->Reset(); 852 for (const auto& space : GetHeap()->GetContinuousSpaces()) { 853 if ((space->GetGcRetentionPolicy() == space::kGcRetentionPolicyAlwaysCollect) || 854 (!partial && space->GetGcRetentionPolicy() == space::kGcRetentionPolicyFullCollect)) { 855 current_space_bitmap_ = space->GetMarkBitmap(); 856 if (current_space_bitmap_ == nullptr) { 857 continue; 858 } 859 if (parallel) { 860 // We will use the mark stack the future. 861 // CHECK(mark_stack_->IsEmpty()); 862 // This function does not handle heap end increasing, so we must use the space end. 863 uintptr_t begin = reinterpret_cast<uintptr_t>(space->Begin()); 864 uintptr_t end = reinterpret_cast<uintptr_t>(space->End()); 865 atomic_finger_ = static_cast<int32_t>(0xFFFFFFFF); 866 867 // Create a few worker tasks. 868 const size_t n = thread_count * 2; 869 while (begin != end) { 870 uintptr_t start = begin; 871 uintptr_t delta = (end - begin) / n; 872 delta = RoundUp(delta, KB); 873 if (delta < 16 * KB) delta = end - begin; 874 begin += delta; 875 auto* task = new RecursiveMarkTask(thread_pool, this, current_space_bitmap_, start, 876 begin); 877 thread_pool->AddTask(self, task); 878 } 879 thread_pool->SetMaxActiveWorkers(thread_count - 1); 880 thread_pool->StartWorkers(self); 881 thread_pool->Wait(self, true, true); 882 thread_pool->StopWorkers(self); 883 } else { 884 // This function does not handle heap end increasing, so we must use the space end. 885 uintptr_t begin = reinterpret_cast<uintptr_t>(space->Begin()); 886 uintptr_t end = reinterpret_cast<uintptr_t>(space->End()); 887 current_space_bitmap_->VisitMarkedRange(begin, end, scan_visitor); 888 } 889 } 890 } 891 } 892 ProcessMarkStack(false); 893} 894 895mirror::Object* MarkSweep::IsMarkedCallback(mirror::Object* object, void* arg) { 896 if (reinterpret_cast<MarkSweep*>(arg)->IsMarked(object)) { 897 return object; 898 } 899 return nullptr; 900} 901 902void MarkSweep::RecursiveMarkDirtyObjects(bool paused, byte minimum_age) { 903 ScanGrayObjects(paused, minimum_age); 904 ProcessMarkStack(paused); 905} 906 907void MarkSweep::ReMarkRoots() { 908 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current()); 909 timings_.StartSplit("(Paused)ReMarkRoots"); 910 Runtime::Current()->VisitRoots( 911 MarkRootCallback, this, static_cast<VisitRootFlags>(kVisitRootFlagNewRoots | 912 kVisitRootFlagStopLoggingNewRoots | 913 kVisitRootFlagClearRootLog)); 914 timings_.EndSplit(); 915 if (kVerifyRootsMarked) { 916 timings_.StartSplit("(Paused)VerifyRoots"); 917 Runtime::Current()->VisitRoots(VerifyRootMarked, this); 918 timings_.EndSplit(); 919 } 920} 921 922void MarkSweep::SweepSystemWeaks(Thread* self) { 923 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_); 924 timings_.StartSplit("SweepSystemWeaks"); 925 Runtime::Current()->SweepSystemWeaks(IsMarkedCallback, this); 926 timings_.EndSplit(); 927} 928 929mirror::Object* MarkSweep::VerifySystemWeakIsLiveCallback(Object* obj, void* arg) { 930 reinterpret_cast<MarkSweep*>(arg)->VerifyIsLive(obj); 931 // We don't actually want to sweep the object, so lets return "marked" 932 return obj; 933} 934 935void MarkSweep::VerifyIsLive(const Object* obj) { 936 if (!heap_->GetLiveBitmap()->Test(obj)) { 937 if (std::find(heap_->allocation_stack_->Begin(), heap_->allocation_stack_->End(), obj) == 938 heap_->allocation_stack_->End()) { 939 // Object not found! 940 heap_->DumpSpaces(); 941 LOG(FATAL) << "Found dead object " << obj; 942 } 943 } 944} 945 946void MarkSweep::VerifySystemWeaks() { 947 // Verify system weaks, uses a special object visitor which returns the input object. 948 Runtime::Current()->SweepSystemWeaks(VerifySystemWeakIsLiveCallback, this); 949} 950 951class CheckpointMarkThreadRoots : public Closure { 952 public: 953 explicit CheckpointMarkThreadRoots(MarkSweep* mark_sweep, 954 bool revoke_ros_alloc_thread_local_buffers_at_checkpoint) 955 : mark_sweep_(mark_sweep), 956 revoke_ros_alloc_thread_local_buffers_at_checkpoint_( 957 revoke_ros_alloc_thread_local_buffers_at_checkpoint) { 958 } 959 960 virtual void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS { 961 ATRACE_BEGIN("Marking thread roots"); 962 // Note: self is not necessarily equal to thread since thread may be suspended. 963 Thread* self = Thread::Current(); 964 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc) 965 << thread->GetState() << " thread " << thread << " self " << self; 966 thread->VisitRoots(MarkSweep::MarkRootParallelCallback, mark_sweep_); 967 ATRACE_END(); 968 if (revoke_ros_alloc_thread_local_buffers_at_checkpoint_) { 969 ATRACE_BEGIN("RevokeRosAllocThreadLocalBuffers"); 970 mark_sweep_->GetHeap()->RevokeRosAllocThreadLocalBuffers(thread); 971 ATRACE_END(); 972 } 973 mark_sweep_->GetBarrier().Pass(self); 974 } 975 976 private: 977 MarkSweep* const mark_sweep_; 978 const bool revoke_ros_alloc_thread_local_buffers_at_checkpoint_; 979}; 980 981void MarkSweep::MarkRootsCheckpoint(Thread* self, 982 bool revoke_ros_alloc_thread_local_buffers_at_checkpoint) { 983 CheckpointMarkThreadRoots check_point(this, revoke_ros_alloc_thread_local_buffers_at_checkpoint); 984 timings_.StartSplit("MarkRootsCheckpoint"); 985 ThreadList* thread_list = Runtime::Current()->GetThreadList(); 986 // Request the check point is run on all threads returning a count of the threads that must 987 // run through the barrier including self. 988 size_t barrier_count = thread_list->RunCheckpoint(&check_point); 989 // Release locks then wait for all mutator threads to pass the barrier. 990 // TODO: optimize to not release locks when there are no threads to wait for. 991 Locks::heap_bitmap_lock_->ExclusiveUnlock(self); 992 Locks::mutator_lock_->SharedUnlock(self); 993 { 994 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun); 995 gc_barrier_->Increment(self, barrier_count); 996 } 997 Locks::mutator_lock_->SharedLock(self); 998 Locks::heap_bitmap_lock_->ExclusiveLock(self); 999 timings_.EndSplit(); 1000} 1001 1002void MarkSweep::SweepArray(accounting::ObjectStack* allocations, bool swap_bitmaps) { 1003 timings_.StartSplit("SweepArray"); 1004 Thread* self = Thread::Current(); 1005 mirror::Object* chunk_free_buffer[kSweepArrayChunkFreeSize]; 1006 size_t chunk_free_pos = 0; 1007 size_t freed_bytes = 0; 1008 size_t freed_large_object_bytes = 0; 1009 size_t freed_objects = 0; 1010 size_t freed_large_objects = 0; 1011 // How many objects are left in the array, modified after each space is swept. 1012 Object** objects = allocations->Begin(); 1013 size_t count = allocations->Size(); 1014 // Change the order to ensure that the non-moving space last swept as an optimization. 1015 std::vector<space::ContinuousSpace*> sweep_spaces; 1016 space::ContinuousSpace* non_moving_space = nullptr; 1017 for (space::ContinuousSpace* space : heap_->GetContinuousSpaces()) { 1018 if (space->IsAllocSpace() && !immune_region_.ContainsSpace(space) && 1019 space->GetLiveBitmap() != nullptr) { 1020 if (space == heap_->GetNonMovingSpace()) { 1021 non_moving_space = space; 1022 } else { 1023 sweep_spaces.push_back(space); 1024 } 1025 } 1026 } 1027 // Unlikely to sweep a significant amount of non_movable objects, so we do these after the after 1028 // the other alloc spaces as an optimization. 1029 if (non_moving_space != nullptr) { 1030 sweep_spaces.push_back(non_moving_space); 1031 } 1032 // Start by sweeping the continuous spaces. 1033 for (space::ContinuousSpace* space : sweep_spaces) { 1034 space::AllocSpace* alloc_space = space->AsAllocSpace(); 1035 accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap(); 1036 accounting::ContinuousSpaceBitmap* mark_bitmap = space->GetMarkBitmap(); 1037 if (swap_bitmaps) { 1038 std::swap(live_bitmap, mark_bitmap); 1039 } 1040 Object** out = objects; 1041 for (size_t i = 0; i < count; ++i) { 1042 Object* obj = objects[i]; 1043 if (kUseThreadLocalAllocationStack && obj == nullptr) { 1044 continue; 1045 } 1046 if (space->HasAddress(obj)) { 1047 // This object is in the space, remove it from the array and add it to the sweep buffer 1048 // if needed. 1049 if (!mark_bitmap->Test(obj)) { 1050 if (chunk_free_pos >= kSweepArrayChunkFreeSize) { 1051 timings_.StartSplit("FreeList"); 1052 freed_objects += chunk_free_pos; 1053 freed_bytes += alloc_space->FreeList(self, chunk_free_pos, chunk_free_buffer); 1054 timings_.EndSplit(); 1055 chunk_free_pos = 0; 1056 } 1057 chunk_free_buffer[chunk_free_pos++] = obj; 1058 } 1059 } else { 1060 *(out++) = obj; 1061 } 1062 } 1063 if (chunk_free_pos > 0) { 1064 timings_.StartSplit("FreeList"); 1065 freed_objects += chunk_free_pos; 1066 freed_bytes += alloc_space->FreeList(self, chunk_free_pos, chunk_free_buffer); 1067 timings_.EndSplit(); 1068 chunk_free_pos = 0; 1069 } 1070 // All of the references which space contained are no longer in the allocation stack, update 1071 // the count. 1072 count = out - objects; 1073 } 1074 // Handle the large object space. 1075 space::LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace(); 1076 accounting::LargeObjectBitmap* large_live_objects = large_object_space->GetLiveBitmap(); 1077 accounting::LargeObjectBitmap* large_mark_objects = large_object_space->GetMarkBitmap(); 1078 if (swap_bitmaps) { 1079 std::swap(large_live_objects, large_mark_objects); 1080 } 1081 for (size_t i = 0; i < count; ++i) { 1082 Object* obj = objects[i]; 1083 // Handle large objects. 1084 if (kUseThreadLocalAllocationStack && obj == nullptr) { 1085 continue; 1086 } 1087 if (!large_mark_objects->Test(obj)) { 1088 ++freed_large_objects; 1089 freed_large_object_bytes += large_object_space->Free(self, obj); 1090 } 1091 } 1092 timings_.EndSplit(); 1093 1094 timings_.StartSplit("RecordFree"); 1095 VLOG(heap) << "Freed " << freed_objects << "/" << count 1096 << " objects with size " << PrettySize(freed_bytes); 1097 heap_->RecordFree(freed_objects + freed_large_objects, freed_bytes + freed_large_object_bytes); 1098 freed_objects_.FetchAndAdd(freed_objects); 1099 freed_large_objects_.FetchAndAdd(freed_large_objects); 1100 freed_bytes_.FetchAndAdd(freed_bytes); 1101 freed_large_object_bytes_.FetchAndAdd(freed_large_object_bytes); 1102 timings_.EndSplit(); 1103 1104 timings_.StartSplit("ResetStack"); 1105 allocations->Reset(); 1106 timings_.EndSplit(); 1107} 1108 1109void MarkSweep::Sweep(bool swap_bitmaps) { 1110 // Ensure that nobody inserted items in the live stack after we swapped the stacks. 1111 CHECK_GE(live_stack_freeze_size_, GetHeap()->GetLiveStack()->Size()); 1112 // Mark everything allocated since the last as GC live so that we can sweep concurrently, 1113 // knowing that new allocations won't be marked as live. 1114 timings_.StartSplit("MarkStackAsLive"); 1115 accounting::ObjectStack* live_stack = heap_->GetLiveStack(); 1116 heap_->MarkAllocStackAsLive(live_stack); 1117 live_stack->Reset(); 1118 timings_.EndSplit(); 1119 1120 DCHECK(mark_stack_->IsEmpty()); 1121 for (const auto& space : GetHeap()->GetContinuousSpaces()) { 1122 if (space->IsContinuousMemMapAllocSpace()) { 1123 space::ContinuousMemMapAllocSpace* alloc_space = space->AsContinuousMemMapAllocSpace(); 1124 TimingLogger::ScopedSplit split( 1125 alloc_space->IsZygoteSpace() ? "SweepZygoteSpace" : "SweepMallocSpace", &timings_); 1126 size_t freed_objects = 0; 1127 size_t freed_bytes = 0; 1128 alloc_space->Sweep(swap_bitmaps, &freed_objects, &freed_bytes); 1129 heap_->RecordFree(freed_objects, freed_bytes); 1130 freed_objects_.FetchAndAdd(freed_objects); 1131 freed_bytes_.FetchAndAdd(freed_bytes); 1132 } 1133 } 1134 SweepLargeObjects(swap_bitmaps); 1135} 1136 1137void MarkSweep::SweepLargeObjects(bool swap_bitmaps) { 1138 TimingLogger::ScopedSplit split("SweepLargeObjects", &timings_); 1139 size_t freed_objects = 0; 1140 size_t freed_bytes = 0; 1141 heap_->GetLargeObjectsSpace()->Sweep(swap_bitmaps, &freed_objects, &freed_bytes); 1142 freed_large_objects_.FetchAndAdd(freed_objects); 1143 freed_large_object_bytes_.FetchAndAdd(freed_bytes); 1144 heap_->RecordFree(freed_objects, freed_bytes); 1145} 1146 1147// Process the "referent" field in a java.lang.ref.Reference. If the referent has not yet been 1148// marked, put it on the appropriate list in the heap for later processing. 1149void MarkSweep::DelayReferenceReferent(mirror::Class* klass, mirror::Reference* ref) { 1150 DCHECK(klass != nullptr); 1151 if (kCountJavaLangRefs) { 1152 ++reference_count_; 1153 } 1154 heap_->DelayReferenceReferent(klass, ref, IsMarkedCallback, this); 1155} 1156 1157class MarkObjectVisitor { 1158 public: 1159 explicit MarkObjectVisitor(MarkSweep* const mark_sweep) ALWAYS_INLINE : mark_sweep_(mark_sweep) { 1160 } 1161 1162 void operator()(Object* obj, MemberOffset offset, bool /* is_static */) const 1163 ALWAYS_INLINE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) 1164 EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) { 1165 if (kCheckLocks) { 1166 Locks::mutator_lock_->AssertSharedHeld(Thread::Current()); 1167 Locks::heap_bitmap_lock_->AssertExclusiveHeld(Thread::Current()); 1168 } 1169 mark_sweep_->MarkObject(obj->GetFieldObject<mirror::Object>(offset, false)); 1170 } 1171 1172 private: 1173 MarkSweep* const mark_sweep_; 1174}; 1175 1176// Scans an object reference. Determines the type of the reference 1177// and dispatches to a specialized scanning routine. 1178void MarkSweep::ScanObject(Object* obj) { 1179 MarkObjectVisitor mark_visitor(this); 1180 DelayReferenceReferentVisitor ref_visitor(this); 1181 ScanObjectVisit(obj, mark_visitor, ref_visitor); 1182} 1183 1184void MarkSweep::ProcessMarkStackPausedCallback(void* arg) { 1185 reinterpret_cast<MarkSweep*>(arg)->ProcessMarkStack(true); 1186} 1187 1188void MarkSweep::ProcessMarkStackParallel(size_t thread_count) { 1189 Thread* self = Thread::Current(); 1190 ThreadPool* thread_pool = GetHeap()->GetThreadPool(); 1191 const size_t chunk_size = std::min(mark_stack_->Size() / thread_count + 1, 1192 static_cast<size_t>(MarkStackTask<false>::kMaxSize)); 1193 CHECK_GT(chunk_size, 0U); 1194 // Split the current mark stack up into work tasks. 1195 for (mirror::Object **it = mark_stack_->Begin(), **end = mark_stack_->End(); it < end; ) { 1196 const size_t delta = std::min(static_cast<size_t>(end - it), chunk_size); 1197 thread_pool->AddTask(self, new MarkStackTask<false>(thread_pool, this, delta, it)); 1198 it += delta; 1199 } 1200 thread_pool->SetMaxActiveWorkers(thread_count - 1); 1201 thread_pool->StartWorkers(self); 1202 thread_pool->Wait(self, true, true); 1203 thread_pool->StopWorkers(self); 1204 mark_stack_->Reset(); 1205 CHECK_EQ(work_chunks_created_, work_chunks_deleted_) << " some of the work chunks were leaked"; 1206} 1207 1208// Scan anything that's on the mark stack. 1209void MarkSweep::ProcessMarkStack(bool paused) { 1210 timings_.StartSplit(paused ? "(Paused)ProcessMarkStack" : "ProcessMarkStack"); 1211 size_t thread_count = GetThreadCount(paused); 1212 if (kParallelProcessMarkStack && thread_count > 1 && 1213 mark_stack_->Size() >= kMinimumParallelMarkStackSize) { 1214 ProcessMarkStackParallel(thread_count); 1215 } else { 1216 // TODO: Tune this. 1217 static const size_t kFifoSize = 4; 1218 BoundedFifoPowerOfTwo<Object*, kFifoSize> prefetch_fifo; 1219 for (;;) { 1220 Object* obj = NULL; 1221 if (kUseMarkStackPrefetch) { 1222 while (!mark_stack_->IsEmpty() && prefetch_fifo.size() < kFifoSize) { 1223 Object* obj = mark_stack_->PopBack(); 1224 DCHECK(obj != NULL); 1225 __builtin_prefetch(obj); 1226 prefetch_fifo.push_back(obj); 1227 } 1228 if (prefetch_fifo.empty()) { 1229 break; 1230 } 1231 obj = prefetch_fifo.front(); 1232 prefetch_fifo.pop_front(); 1233 } else { 1234 if (mark_stack_->IsEmpty()) { 1235 break; 1236 } 1237 obj = mark_stack_->PopBack(); 1238 } 1239 DCHECK(obj != nullptr); 1240 ScanObject(obj); 1241 } 1242 } 1243 timings_.EndSplit(); 1244} 1245 1246inline bool MarkSweep::IsMarked(const Object* object) const 1247 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) { 1248 if (immune_region_.ContainsObject(object)) { 1249 return true; 1250 } 1251 if (current_space_bitmap_->HasAddress(object)) { 1252 return current_space_bitmap_->Test(object); 1253 } 1254 return mark_bitmap_->Test(object); 1255} 1256 1257void MarkSweep::FinishPhase() { 1258 TimingLogger::ScopedSplit split("FinishPhase", &timings_); 1259 // Can't enqueue references if we hold the mutator lock. 1260 timings_.NewSplit("PostGcVerification"); 1261 heap_->PostGcVerification(this); 1262 if (kCountScannedTypes) { 1263 VLOG(gc) << "MarkSweep scanned classes=" << class_count_ << " arrays=" << array_count_ 1264 << " other=" << other_count_; 1265 } 1266 if (kCountTasks) { 1267 VLOG(gc) << "Total number of work chunks allocated: " << work_chunks_created_; 1268 } 1269 if (kMeasureOverhead) { 1270 VLOG(gc) << "Overhead time " << PrettyDuration(overhead_time_); 1271 } 1272 if (kProfileLargeObjects) { 1273 VLOG(gc) << "Large objects tested " << large_object_test_ << " marked " << large_object_mark_; 1274 } 1275 if (kCountJavaLangRefs) { 1276 VLOG(gc) << "References scanned " << reference_count_; 1277 } 1278 if (kCountMarkedObjects) { 1279 VLOG(gc) << "Marked: null=" << mark_null_count_ << " immune=" << mark_immune_count_ 1280 << " fastpath=" << mark_fastpath_count_ << " slowpath=" << mark_slowpath_count_; 1281 } 1282 CHECK(mark_stack_->IsEmpty()); // Ensure that the mark stack is empty. 1283 mark_stack_->Reset(); 1284 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_); 1285 heap_->ClearMarkedObjects(); 1286} 1287 1288void MarkSweep::RevokeAllThreadLocalBuffers() { 1289 if (kRevokeRosAllocThreadLocalBuffersAtCheckpoint && IsConcurrent()) { 1290 // If concurrent, rosalloc thread-local buffers are revoked at the 1291 // thread checkpoint. Bump pointer space thread-local buffers must 1292 // not be in use. 1293 GetHeap()->AssertAllBumpPointerSpaceThreadLocalBuffersAreRevoked(); 1294 } else { 1295 timings_.StartSplit("(Paused)RevokeAllThreadLocalBuffers"); 1296 GetHeap()->RevokeAllThreadLocalBuffers(); 1297 timings_.EndSplit(); 1298 } 1299} 1300 1301} // namespace collector 1302} // namespace gc 1303} // namespace art 1304