mark_sweep.cc revision 624468cd401cc1ac0dd70c746301e0788a597759
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 kVerifyRoots = 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 large_object_lock_("mark sweep large object lock", kMarkSweepLargeObjectLock), 103 mark_stack_lock_("mark sweep mark stack lock", kMarkSweepMarkStackLock), 104 is_concurrent_(is_concurrent) { 105} 106 107void MarkSweep::InitializePhase() { 108 timings_.Reset(); 109 TimingLogger::ScopedSplit split("InitializePhase", &timings_); 110 mark_stack_ = heap_->mark_stack_.get(); 111 DCHECK(mark_stack_ != nullptr); 112 immune_region_.Reset(); 113 class_count_ = 0; 114 array_count_ = 0; 115 other_count_ = 0; 116 large_object_test_ = 0; 117 large_object_mark_ = 0; 118 overhead_time_ = 0; 119 work_chunks_created_ = 0; 120 work_chunks_deleted_ = 0; 121 reference_count_ = 0; 122 mark_null_count_ = 0; 123 mark_immune_count_ = 0; 124 mark_fastpath_count_ = 0; 125 mark_slowpath_count_ = 0; 126 FindDefaultSpaceBitmap(); 127 { 128 // TODO: I don't think we should need heap bitmap lock to get the mark bitmap. 129 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_); 130 mark_bitmap_ = heap_->GetMarkBitmap(); 131 } 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::SpaceBitmap* bitmap = space->GetMarkBitmap(); 294 if (bitmap != nullptr && 295 space->GetGcRetentionPolicy() == space::kGcRetentionPolicyAlwaysCollect) { 296 current_space_bitmap_ = bitmap; 297 return; 298 } 299 } 300 GetHeap()->DumpSpaces(); 301 LOG(FATAL) << "Could not find a default mark bitmap"; 302} 303 304void MarkSweep::ExpandMarkStack() { 305 ResizeMarkStack(mark_stack_->Capacity() * 2); 306} 307 308void MarkSweep::ResizeMarkStack(size_t new_size) { 309 // Rare case, no need to have Thread::Current be a parameter. 310 if (UNLIKELY(mark_stack_->Size() < mark_stack_->Capacity())) { 311 // Someone else acquired the lock and expanded the mark stack before us. 312 return; 313 } 314 std::vector<Object*> temp(mark_stack_->Begin(), mark_stack_->End()); 315 CHECK_LE(mark_stack_->Size(), new_size); 316 mark_stack_->Resize(new_size); 317 for (const auto& obj : temp) { 318 mark_stack_->PushBack(obj); 319 } 320} 321 322inline void MarkSweep::MarkObjectNonNullParallel(Object* obj) { 323 DCHECK(obj != NULL); 324 if (MarkObjectParallel(obj)) { 325 MutexLock mu(Thread::Current(), mark_stack_lock_); 326 if (UNLIKELY(mark_stack_->Size() >= mark_stack_->Capacity())) { 327 ExpandMarkStack(); 328 } 329 // The object must be pushed on to the mark stack. 330 mark_stack_->PushBack(obj); 331 } 332} 333 334mirror::Object* MarkSweep::MarkObjectCallback(mirror::Object* obj, void* arg) { 335 MarkSweep* mark_sweep = reinterpret_cast<MarkSweep*>(arg); 336 mark_sweep->MarkObject(obj); 337 return obj; 338} 339 340void MarkSweep::MarkHeapReferenceCallback(mirror::HeapReference<mirror::Object>* ref, void* arg) { 341 reinterpret_cast<MarkSweep*>(arg)->MarkObject(ref->AsMirrorPtr()); 342} 343 344inline void MarkSweep::MarkObjectNonNull(Object* obj) { 345 DCHECK(obj != nullptr); 346 if (kUseBakerOrBrooksReadBarrier) { 347 // Verify all the objects have the correct pointer installed. 348 obj->AssertReadBarrierPointer(); 349 } 350 if (immune_region_.ContainsObject(obj)) { 351 if (kCountMarkedObjects) { 352 ++mark_immune_count_; 353 } 354 DCHECK(IsMarked(obj)); 355 return; 356 } 357 // Try to take advantage of locality of references within a space, failing this find the space 358 // the hard way. 359 accounting::SpaceBitmap* object_bitmap = current_space_bitmap_; 360 if (UNLIKELY(!object_bitmap->HasAddress(obj))) { 361 object_bitmap = mark_bitmap_->GetContinuousSpaceBitmap(obj); 362 if (kCountMarkedObjects) { 363 ++mark_slowpath_count_; 364 } 365 if (UNLIKELY(object_bitmap == nullptr)) { 366 MarkLargeObject(obj, true); 367 return; 368 } 369 } else if (kCountMarkedObjects) { 370 ++mark_fastpath_count_; 371 } 372 // This object was not previously marked. 373 if (!object_bitmap->Set(obj)) { 374 PushOnMarkStack(obj); 375 } 376} 377 378inline void MarkSweep::PushOnMarkStack(Object* obj) { 379 if (UNLIKELY(mark_stack_->Size() >= mark_stack_->Capacity())) { 380 // Lock is not needed but is here anyways to please annotalysis. 381 MutexLock mu(Thread::Current(), mark_stack_lock_); 382 ExpandMarkStack(); 383 } 384 // The object must be pushed on to the mark stack. 385 mark_stack_->PushBack(obj); 386} 387 388// Rare case, probably not worth inlining since it will increase instruction cache miss rate. 389bool MarkSweep::MarkLargeObject(const Object* obj, bool set) { 390 // TODO: support >1 discontinuous space. 391 space::LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace(); 392 accounting::ObjectSet* large_objects = large_object_space->GetMarkObjects(); 393 if (kProfileLargeObjects) { 394 ++large_object_test_; 395 } 396 if (UNLIKELY(!large_objects->Test(obj))) { 397 if (!large_object_space->Contains(obj)) { 398 LOG(ERROR) << "Tried to mark " << obj << " not contained by any spaces"; 399 LOG(ERROR) << "Attempting see if it's a bad root"; 400 VerifyRoots(); 401 LOG(FATAL) << "Can't mark bad root"; 402 } 403 if (kProfileLargeObjects) { 404 ++large_object_mark_; 405 } 406 if (set) { 407 large_objects->Set(obj); 408 } else { 409 large_objects->Clear(obj); 410 } 411 return true; 412 } 413 return false; 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::SpaceBitmap* object_bitmap = current_space_bitmap_; 429 if (UNLIKELY(!object_bitmap->HasAddress(obj))) { 430 accounting::SpaceBitmap* new_bitmap = mark_bitmap_->GetContinuousSpaceBitmap(obj); 431 if (new_bitmap != NULL) { 432 object_bitmap = new_bitmap; 433 } else { 434 // TODO: Remove the Thread::Current here? 435 // TODO: Convert this to some kind of atomic marking? 436 MutexLock mu(Thread::Current(), large_object_lock_); 437 return MarkLargeObject(obj, true); 438 } 439 } 440 // Return true if the object was not previously marked. 441 return !object_bitmap->AtomicTestAndSet(obj); 442} 443 444// Used to mark objects when processing the mark stack. If an object is null, it is not marked. 445inline void MarkSweep::MarkObject(Object* obj) { 446 if (obj != nullptr) { 447 MarkObjectNonNull(obj); 448 } else if (kCountMarkedObjects) { 449 ++mark_null_count_; 450 } 451} 452 453void MarkSweep::MarkRootParallelCallback(Object** root, void* arg, uint32_t /*thread_id*/, 454 RootType /*root_type*/) { 455 reinterpret_cast<MarkSweep*>(arg)->MarkObjectNonNullParallel(*root); 456} 457 458void MarkSweep::VerifyRootMarked(Object** root, void* arg, uint32_t /*thread_id*/, 459 RootType /*root_type*/) { 460 CHECK(reinterpret_cast<MarkSweep*>(arg)->IsMarked(*root)); 461} 462 463void MarkSweep::MarkRootCallback(Object** root, void* arg, uint32_t /*thread_id*/, 464 RootType /*root_type*/) { 465 reinterpret_cast<MarkSweep*>(arg)->MarkObjectNonNull(*root); 466} 467 468void MarkSweep::VerifyRootCallback(const Object* root, void* arg, size_t vreg, 469 const StackVisitor* visitor) { 470 reinterpret_cast<MarkSweep*>(arg)->VerifyRoot(root, vreg, visitor); 471} 472 473void MarkSweep::VerifyRoot(const Object* root, size_t vreg, const StackVisitor* visitor) { 474 // See if the root is on any space bitmap. 475 if (GetHeap()->GetLiveBitmap()->GetContinuousSpaceBitmap(root) == NULL) { 476 space::LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace(); 477 if (!large_object_space->Contains(root)) { 478 LOG(ERROR) << "Found invalid root: " << root; 479 if (visitor != NULL) { 480 LOG(ERROR) << visitor->DescribeLocation() << " in VReg: " << vreg; 481 } 482 } 483 } 484} 485 486void MarkSweep::VerifyRoots() { 487 Runtime::Current()->GetThreadList()->VerifyRoots(VerifyRootCallback, this); 488} 489 490void MarkSweep::MarkRoots(Thread* self) { 491 if (Locks::mutator_lock_->IsExclusiveHeld(self)) { 492 // If we exclusively hold the mutator lock, all threads must be suspended. 493 timings_.StartSplit("MarkRoots"); 494 Runtime::Current()->VisitRoots(MarkRootCallback, this); 495 timings_.EndSplit(); 496 RevokeAllThreadLocalAllocationStacks(self); 497 } else { 498 MarkRootsCheckpoint(self, kRevokeRosAllocThreadLocalBuffersAtCheckpoint); 499 // At this point the live stack should no longer have any mutators which push into it. 500 MarkNonThreadRoots(); 501 MarkConcurrentRoots( 502 static_cast<VisitRootFlags>(kVisitRootFlagAllRoots | kVisitRootFlagStartLoggingNewRoots)); 503 } 504} 505 506void MarkSweep::MarkNonThreadRoots() { 507 timings_.StartSplit("MarkNonThreadRoots"); 508 Runtime::Current()->VisitNonThreadRoots(MarkRootCallback, this); 509 timings_.EndSplit(); 510} 511 512void MarkSweep::MarkConcurrentRoots(VisitRootFlags flags) { 513 timings_.StartSplit("MarkConcurrentRoots"); 514 // Visit all runtime roots and clear dirty flags. 515 Runtime::Current()->VisitConcurrentRoots(MarkRootCallback, this, flags); 516 timings_.EndSplit(); 517} 518 519class ScanObjectVisitor { 520 public: 521 explicit ScanObjectVisitor(MarkSweep* const mark_sweep) ALWAYS_INLINE 522 : mark_sweep_(mark_sweep) {} 523 524 void operator()(Object* obj) const ALWAYS_INLINE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) 525 EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) { 526 if (kCheckLocks) { 527 Locks::mutator_lock_->AssertSharedHeld(Thread::Current()); 528 Locks::heap_bitmap_lock_->AssertExclusiveHeld(Thread::Current()); 529 } 530 mark_sweep_->ScanObject(obj); 531 } 532 533 private: 534 MarkSweep* const mark_sweep_; 535}; 536 537class DelayReferenceReferentVisitor { 538 public: 539 explicit DelayReferenceReferentVisitor(MarkSweep* collector) : collector_(collector) { 540 } 541 542 void operator()(mirror::Class* klass, mirror::Reference* ref) const 543 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) 544 EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) { 545 collector_->DelayReferenceReferent(klass, ref); 546 } 547 548 private: 549 MarkSweep* const collector_; 550}; 551 552template <bool kUseFinger = false> 553class MarkStackTask : public Task { 554 public: 555 MarkStackTask(ThreadPool* thread_pool, MarkSweep* mark_sweep, size_t mark_stack_size, 556 Object** mark_stack) 557 : mark_sweep_(mark_sweep), 558 thread_pool_(thread_pool), 559 mark_stack_pos_(mark_stack_size) { 560 // We may have to copy part of an existing mark stack when another mark stack overflows. 561 if (mark_stack_size != 0) { 562 DCHECK(mark_stack != NULL); 563 // TODO: Check performance? 564 std::copy(mark_stack, mark_stack + mark_stack_size, mark_stack_); 565 } 566 if (kCountTasks) { 567 ++mark_sweep_->work_chunks_created_; 568 } 569 } 570 571 static const size_t kMaxSize = 1 * KB; 572 573 protected: 574 class MarkObjectParallelVisitor { 575 public: 576 explicit MarkObjectParallelVisitor(MarkStackTask<kUseFinger>* chunk_task, 577 MarkSweep* mark_sweep) ALWAYS_INLINE 578 : chunk_task_(chunk_task), mark_sweep_(mark_sweep) {} 579 580 void operator()(Object* obj, MemberOffset offset, bool /* static */) const ALWAYS_INLINE 581 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 582 mirror::Object* ref = obj->GetFieldObject<mirror::Object>(offset, false); 583 if (ref != nullptr && mark_sweep_->MarkObjectParallel(ref)) { 584 if (kUseFinger) { 585 android_memory_barrier(); 586 if (reinterpret_cast<uintptr_t>(ref) >= 587 static_cast<uintptr_t>(mark_sweep_->atomic_finger_)) { 588 return; 589 } 590 } 591 chunk_task_->MarkStackPush(ref); 592 } 593 } 594 595 private: 596 MarkStackTask<kUseFinger>* const chunk_task_; 597 MarkSweep* const mark_sweep_; 598 }; 599 600 class ScanObjectParallelVisitor { 601 public: 602 explicit ScanObjectParallelVisitor(MarkStackTask<kUseFinger>* chunk_task) ALWAYS_INLINE 603 : chunk_task_(chunk_task) {} 604 605 // No thread safety analysis since multiple threads will use this visitor. 606 void operator()(Object* obj) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) 607 EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) { 608 MarkSweep* const mark_sweep = chunk_task_->mark_sweep_; 609 MarkObjectParallelVisitor mark_visitor(chunk_task_, mark_sweep); 610 DelayReferenceReferentVisitor ref_visitor(mark_sweep); 611 mark_sweep->ScanObjectVisit(obj, mark_visitor, ref_visitor); 612 } 613 614 private: 615 MarkStackTask<kUseFinger>* const chunk_task_; 616 }; 617 618 virtual ~MarkStackTask() { 619 // Make sure that we have cleared our mark stack. 620 DCHECK_EQ(mark_stack_pos_, 0U); 621 if (kCountTasks) { 622 ++mark_sweep_->work_chunks_deleted_; 623 } 624 } 625 626 MarkSweep* const mark_sweep_; 627 ThreadPool* const thread_pool_; 628 // Thread local mark stack for this task. 629 Object* mark_stack_[kMaxSize]; 630 // Mark stack position. 631 size_t mark_stack_pos_; 632 633 void MarkStackPush(Object* obj) ALWAYS_INLINE { 634 if (UNLIKELY(mark_stack_pos_ == kMaxSize)) { 635 // Mark stack overflow, give 1/2 the stack to the thread pool as a new work task. 636 mark_stack_pos_ /= 2; 637 auto* task = new MarkStackTask(thread_pool_, mark_sweep_, kMaxSize - mark_stack_pos_, 638 mark_stack_ + mark_stack_pos_); 639 thread_pool_->AddTask(Thread::Current(), task); 640 } 641 DCHECK(obj != nullptr); 642 DCHECK_LT(mark_stack_pos_, kMaxSize); 643 mark_stack_[mark_stack_pos_++] = obj; 644 } 645 646 virtual void Finalize() { 647 delete this; 648 } 649 650 // Scans all of the objects 651 virtual void Run(Thread* self) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) 652 EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) { 653 ScanObjectParallelVisitor visitor(this); 654 // TODO: Tune this. 655 static const size_t kFifoSize = 4; 656 BoundedFifoPowerOfTwo<Object*, kFifoSize> prefetch_fifo; 657 for (;;) { 658 Object* obj = nullptr; 659 if (kUseMarkStackPrefetch) { 660 while (mark_stack_pos_ != 0 && prefetch_fifo.size() < kFifoSize) { 661 Object* obj = mark_stack_[--mark_stack_pos_]; 662 DCHECK(obj != nullptr); 663 __builtin_prefetch(obj); 664 prefetch_fifo.push_back(obj); 665 } 666 if (UNLIKELY(prefetch_fifo.empty())) { 667 break; 668 } 669 obj = prefetch_fifo.front(); 670 prefetch_fifo.pop_front(); 671 } else { 672 if (UNLIKELY(mark_stack_pos_ == 0)) { 673 break; 674 } 675 obj = mark_stack_[--mark_stack_pos_]; 676 } 677 DCHECK(obj != nullptr); 678 visitor(obj); 679 } 680 } 681}; 682 683class CardScanTask : public MarkStackTask<false> { 684 public: 685 CardScanTask(ThreadPool* thread_pool, MarkSweep* mark_sweep, accounting::SpaceBitmap* bitmap, 686 byte* begin, byte* end, byte minimum_age, size_t mark_stack_size, 687 Object** mark_stack_obj) 688 : MarkStackTask<false>(thread_pool, mark_sweep, mark_stack_size, mark_stack_obj), 689 bitmap_(bitmap), 690 begin_(begin), 691 end_(end), 692 minimum_age_(minimum_age) { 693 } 694 695 protected: 696 accounting::SpaceBitmap* const bitmap_; 697 byte* const begin_; 698 byte* const end_; 699 const byte minimum_age_; 700 701 virtual void Finalize() { 702 delete this; 703 } 704 705 virtual void Run(Thread* self) NO_THREAD_SAFETY_ANALYSIS { 706 ScanObjectParallelVisitor visitor(this); 707 accounting::CardTable* card_table = mark_sweep_->GetHeap()->GetCardTable(); 708 size_t cards_scanned = card_table->Scan(bitmap_, begin_, end_, visitor, minimum_age_); 709 VLOG(heap) << "Parallel scanning cards " << reinterpret_cast<void*>(begin_) << " - " 710 << reinterpret_cast<void*>(end_) << " = " << cards_scanned; 711 // Finish by emptying our local mark stack. 712 MarkStackTask::Run(self); 713 } 714}; 715 716size_t MarkSweep::GetThreadCount(bool paused) const { 717 if (heap_->GetThreadPool() == nullptr || !heap_->CareAboutPauseTimes()) { 718 return 0; 719 } 720 if (paused) { 721 return heap_->GetParallelGCThreadCount() + 1; 722 } else { 723 return heap_->GetConcGCThreadCount() + 1; 724 } 725} 726 727void MarkSweep::ScanGrayObjects(bool paused, byte minimum_age) { 728 accounting::CardTable* card_table = GetHeap()->GetCardTable(); 729 ThreadPool* thread_pool = GetHeap()->GetThreadPool(); 730 size_t thread_count = GetThreadCount(paused); 731 // The parallel version with only one thread is faster for card scanning, TODO: fix. 732 if (kParallelCardScan && thread_count > 0) { 733 Thread* self = Thread::Current(); 734 // Can't have a different split for each space since multiple spaces can have their cards being 735 // scanned at the same time. 736 timings_.StartSplit(paused ? "(Paused)ScanGrayObjects" : "ScanGrayObjects"); 737 // Try to take some of the mark stack since we can pass this off to the worker tasks. 738 Object** mark_stack_begin = mark_stack_->Begin(); 739 Object** mark_stack_end = mark_stack_->End(); 740 const size_t mark_stack_size = mark_stack_end - mark_stack_begin; 741 // Estimated number of work tasks we will create. 742 const size_t mark_stack_tasks = GetHeap()->GetContinuousSpaces().size() * thread_count; 743 DCHECK_NE(mark_stack_tasks, 0U); 744 const size_t mark_stack_delta = std::min(CardScanTask::kMaxSize / 2, 745 mark_stack_size / mark_stack_tasks + 1); 746 for (const auto& space : GetHeap()->GetContinuousSpaces()) { 747 if (space->GetMarkBitmap() == nullptr) { 748 continue; 749 } 750 byte* card_begin = space->Begin(); 751 byte* card_end = space->End(); 752 // Align up the end address. For example, the image space's end 753 // may not be card-size-aligned. 754 card_end = AlignUp(card_end, accounting::CardTable::kCardSize); 755 DCHECK(IsAligned<accounting::CardTable::kCardSize>(card_begin)); 756 DCHECK(IsAligned<accounting::CardTable::kCardSize>(card_end)); 757 // Calculate how many bytes of heap we will scan, 758 const size_t address_range = card_end - card_begin; 759 // Calculate how much address range each task gets. 760 const size_t card_delta = RoundUp(address_range / thread_count + 1, 761 accounting::CardTable::kCardSize); 762 // Create the worker tasks for this space. 763 while (card_begin != card_end) { 764 // Add a range of cards. 765 size_t addr_remaining = card_end - card_begin; 766 size_t card_increment = std::min(card_delta, addr_remaining); 767 // Take from the back of the mark stack. 768 size_t mark_stack_remaining = mark_stack_end - mark_stack_begin; 769 size_t mark_stack_increment = std::min(mark_stack_delta, mark_stack_remaining); 770 mark_stack_end -= mark_stack_increment; 771 mark_stack_->PopBackCount(static_cast<int32_t>(mark_stack_increment)); 772 DCHECK_EQ(mark_stack_end, mark_stack_->End()); 773 // Add the new task to the thread pool. 774 auto* task = new CardScanTask(thread_pool, this, space->GetMarkBitmap(), card_begin, 775 card_begin + card_increment, minimum_age, 776 mark_stack_increment, mark_stack_end); 777 thread_pool->AddTask(self, task); 778 card_begin += card_increment; 779 } 780 } 781 782 // Note: the card scan below may dirty new cards (and scan them) 783 // as a side effect when a Reference object is encountered and 784 // queued during the marking. See b/11465268. 785 thread_pool->SetMaxActiveWorkers(thread_count - 1); 786 thread_pool->StartWorkers(self); 787 thread_pool->Wait(self, true, true); 788 thread_pool->StopWorkers(self); 789 timings_.EndSplit(); 790 } else { 791 for (const auto& space : GetHeap()->GetContinuousSpaces()) { 792 if (space->GetMarkBitmap() != nullptr) { 793 // Image spaces are handled properly since live == marked for them. 794 switch (space->GetGcRetentionPolicy()) { 795 case space::kGcRetentionPolicyNeverCollect: 796 timings_.StartSplit(paused ? "(Paused)ScanGrayImageSpaceObjects" : 797 "ScanGrayImageSpaceObjects"); 798 break; 799 case space::kGcRetentionPolicyFullCollect: 800 timings_.StartSplit(paused ? "(Paused)ScanGrayZygoteSpaceObjects" : 801 "ScanGrayZygoteSpaceObjects"); 802 break; 803 case space::kGcRetentionPolicyAlwaysCollect: 804 timings_.StartSplit(paused ? "(Paused)ScanGrayAllocSpaceObjects" : 805 "ScanGrayAllocSpaceObjects"); 806 break; 807 } 808 ScanObjectVisitor visitor(this); 809 card_table->Scan(space->GetMarkBitmap(), space->Begin(), space->End(), visitor, minimum_age); 810 timings_.EndSplit(); 811 } 812 } 813 } 814} 815 816class RecursiveMarkTask : public MarkStackTask<false> { 817 public: 818 RecursiveMarkTask(ThreadPool* thread_pool, MarkSweep* mark_sweep, 819 accounting::SpaceBitmap* bitmap, uintptr_t begin, uintptr_t end) 820 : MarkStackTask<false>(thread_pool, mark_sweep, 0, NULL), 821 bitmap_(bitmap), 822 begin_(begin), 823 end_(end) { 824 } 825 826 protected: 827 accounting::SpaceBitmap* const bitmap_; 828 const uintptr_t begin_; 829 const uintptr_t end_; 830 831 virtual void Finalize() { 832 delete this; 833 } 834 835 // Scans all of the objects 836 virtual void Run(Thread* self) NO_THREAD_SAFETY_ANALYSIS { 837 ScanObjectParallelVisitor visitor(this); 838 bitmap_->VisitMarkedRange(begin_, end_, visitor); 839 // Finish by emptying our local mark stack. 840 MarkStackTask::Run(self); 841 } 842}; 843 844// Populates the mark stack based on the set of marked objects and 845// recursively marks until the mark stack is emptied. 846void MarkSweep::RecursiveMark() { 847 TimingLogger::ScopedSplit split("RecursiveMark", &timings_); 848 // RecursiveMark will build the lists of known instances of the Reference classes. See 849 // DelayReferenceReferent for details. 850 if (kUseRecursiveMark) { 851 const bool partial = GetGcType() == kGcTypePartial; 852 ScanObjectVisitor scan_visitor(this); 853 auto* self = Thread::Current(); 854 ThreadPool* thread_pool = heap_->GetThreadPool(); 855 size_t thread_count = GetThreadCount(false); 856 const bool parallel = kParallelRecursiveMark && thread_count > 1; 857 mark_stack_->Reset(); 858 for (const auto& space : GetHeap()->GetContinuousSpaces()) { 859 if ((space->GetGcRetentionPolicy() == space::kGcRetentionPolicyAlwaysCollect) || 860 (!partial && space->GetGcRetentionPolicy() == space::kGcRetentionPolicyFullCollect)) { 861 current_space_bitmap_ = space->GetMarkBitmap(); 862 if (current_space_bitmap_ == nullptr) { 863 continue; 864 } 865 if (parallel) { 866 // We will use the mark stack the future. 867 // CHECK(mark_stack_->IsEmpty()); 868 // This function does not handle heap end increasing, so we must use the space end. 869 uintptr_t begin = reinterpret_cast<uintptr_t>(space->Begin()); 870 uintptr_t end = reinterpret_cast<uintptr_t>(space->End()); 871 atomic_finger_ = static_cast<int32_t>(0xFFFFFFFF); 872 873 // Create a few worker tasks. 874 const size_t n = thread_count * 2; 875 while (begin != end) { 876 uintptr_t start = begin; 877 uintptr_t delta = (end - begin) / n; 878 delta = RoundUp(delta, KB); 879 if (delta < 16 * KB) delta = end - begin; 880 begin += delta; 881 auto* task = new RecursiveMarkTask(thread_pool, this, current_space_bitmap_, start, 882 begin); 883 thread_pool->AddTask(self, task); 884 } 885 thread_pool->SetMaxActiveWorkers(thread_count - 1); 886 thread_pool->StartWorkers(self); 887 thread_pool->Wait(self, true, true); 888 thread_pool->StopWorkers(self); 889 } else { 890 // This function does not handle heap end increasing, so we must use the space end. 891 uintptr_t begin = reinterpret_cast<uintptr_t>(space->Begin()); 892 uintptr_t end = reinterpret_cast<uintptr_t>(space->End()); 893 current_space_bitmap_->VisitMarkedRange(begin, end, scan_visitor); 894 } 895 } 896 } 897 } 898 ProcessMarkStack(false); 899} 900 901mirror::Object* MarkSweep::IsMarkedCallback(mirror::Object* object, void* arg) { 902 if (reinterpret_cast<MarkSweep*>(arg)->IsMarked(object)) { 903 return object; 904 } 905 return nullptr; 906} 907 908void MarkSweep::RecursiveMarkDirtyObjects(bool paused, byte minimum_age) { 909 ScanGrayObjects(paused, minimum_age); 910 ProcessMarkStack(paused); 911} 912 913void MarkSweep::ReMarkRoots() { 914 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current()); 915 timings_.StartSplit("(Paused)ReMarkRoots"); 916 Runtime::Current()->VisitRoots( 917 MarkRootCallback, this, static_cast<VisitRootFlags>(kVisitRootFlagNewRoots | 918 kVisitRootFlagStopLoggingNewRoots | 919 kVisitRootFlagClearRootLog)); 920 timings_.EndSplit(); 921 if (kVerifyRoots) { 922 timings_.StartSplit("(Paused)VerifyRoots"); 923 Runtime::Current()->VisitRoots(VerifyRootMarked, this); 924 timings_.EndSplit(); 925 } 926} 927 928void MarkSweep::SweepSystemWeaks(Thread* self) { 929 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_); 930 timings_.StartSplit("SweepSystemWeaks"); 931 Runtime::Current()->SweepSystemWeaks(IsMarkedCallback, this); 932 timings_.EndSplit(); 933} 934 935mirror::Object* MarkSweep::VerifySystemWeakIsLiveCallback(Object* obj, void* arg) { 936 reinterpret_cast<MarkSweep*>(arg)->VerifyIsLive(obj); 937 // We don't actually want to sweep the object, so lets return "marked" 938 return obj; 939} 940 941void MarkSweep::VerifyIsLive(const Object* obj) { 942 if (!heap_->GetLiveBitmap()->Test(obj)) { 943 space::LargeObjectSpace* large_object_space = heap_->GetLargeObjectsSpace(); 944 if (!large_object_space->GetLiveObjects()->Test(obj)) { 945 if (std::find(heap_->allocation_stack_->Begin(), heap_->allocation_stack_->End(), obj) == 946 heap_->allocation_stack_->End()) { 947 // Object not found! 948 heap_->DumpSpaces(); 949 LOG(FATAL) << "Found dead object " << obj; 950 } 951 } 952 } 953} 954 955void MarkSweep::VerifySystemWeaks() { 956 // Verify system weaks, uses a special object visitor which returns the input object. 957 Runtime::Current()->SweepSystemWeaks(VerifySystemWeakIsLiveCallback, this); 958} 959 960class CheckpointMarkThreadRoots : public Closure { 961 public: 962 explicit CheckpointMarkThreadRoots(MarkSweep* mark_sweep, 963 bool revoke_ros_alloc_thread_local_buffers_at_checkpoint) 964 : mark_sweep_(mark_sweep), 965 revoke_ros_alloc_thread_local_buffers_at_checkpoint_( 966 revoke_ros_alloc_thread_local_buffers_at_checkpoint) { 967 } 968 969 virtual void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS { 970 ATRACE_BEGIN("Marking thread roots"); 971 // Note: self is not necessarily equal to thread since thread may be suspended. 972 Thread* self = Thread::Current(); 973 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc) 974 << thread->GetState() << " thread " << thread << " self " << self; 975 thread->VisitRoots(MarkSweep::MarkRootParallelCallback, mark_sweep_); 976 ATRACE_END(); 977 if (revoke_ros_alloc_thread_local_buffers_at_checkpoint_) { 978 ATRACE_BEGIN("RevokeRosAllocThreadLocalBuffers"); 979 mark_sweep_->GetHeap()->RevokeRosAllocThreadLocalBuffers(thread); 980 ATRACE_END(); 981 } 982 mark_sweep_->GetBarrier().Pass(self); 983 } 984 985 private: 986 MarkSweep* const mark_sweep_; 987 const bool revoke_ros_alloc_thread_local_buffers_at_checkpoint_; 988}; 989 990void MarkSweep::MarkRootsCheckpoint(Thread* self, 991 bool revoke_ros_alloc_thread_local_buffers_at_checkpoint) { 992 CheckpointMarkThreadRoots check_point(this, revoke_ros_alloc_thread_local_buffers_at_checkpoint); 993 timings_.StartSplit("MarkRootsCheckpoint"); 994 ThreadList* thread_list = Runtime::Current()->GetThreadList(); 995 // Request the check point is run on all threads returning a count of the threads that must 996 // run through the barrier including self. 997 size_t barrier_count = thread_list->RunCheckpoint(&check_point); 998 // Release locks then wait for all mutator threads to pass the barrier. 999 // TODO: optimize to not release locks when there are no threads to wait for. 1000 Locks::heap_bitmap_lock_->ExclusiveUnlock(self); 1001 Locks::mutator_lock_->SharedUnlock(self); 1002 { 1003 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun); 1004 gc_barrier_->Increment(self, barrier_count); 1005 } 1006 Locks::mutator_lock_->SharedLock(self); 1007 Locks::heap_bitmap_lock_->ExclusiveLock(self); 1008 timings_.EndSplit(); 1009} 1010 1011void MarkSweep::SweepArray(accounting::ObjectStack* allocations, bool swap_bitmaps) { 1012 timings_.StartSplit("SweepArray"); 1013 Thread* self = Thread::Current(); 1014 mirror::Object* chunk_free_buffer[kSweepArrayChunkFreeSize]; 1015 size_t chunk_free_pos = 0; 1016 size_t freed_bytes = 0; 1017 size_t freed_large_object_bytes = 0; 1018 size_t freed_objects = 0; 1019 size_t freed_large_objects = 0; 1020 // How many objects are left in the array, modified after each space is swept. 1021 Object** objects = allocations->Begin(); 1022 size_t count = allocations->Size(); 1023 // Change the order to ensure that the non-moving space last swept as an optimization. 1024 std::vector<space::ContinuousSpace*> sweep_spaces; 1025 space::ContinuousSpace* non_moving_space = nullptr; 1026 for (space::ContinuousSpace* space : heap_->GetContinuousSpaces()) { 1027 if (space->IsAllocSpace() && !immune_region_.ContainsSpace(space) && 1028 space->GetLiveBitmap() != nullptr) { 1029 if (space == heap_->GetNonMovingSpace()) { 1030 non_moving_space = space; 1031 } else { 1032 sweep_spaces.push_back(space); 1033 } 1034 } 1035 } 1036 // Unlikely to sweep a significant amount of non_movable objects, so we do these after the after 1037 // the other alloc spaces as an optimization. 1038 if (non_moving_space != nullptr) { 1039 sweep_spaces.push_back(non_moving_space); 1040 } 1041 // Start by sweeping the continuous spaces. 1042 for (space::ContinuousSpace* space : sweep_spaces) { 1043 space::AllocSpace* alloc_space = space->AsAllocSpace(); 1044 accounting::SpaceBitmap* live_bitmap = space->GetLiveBitmap(); 1045 accounting::SpaceBitmap* mark_bitmap = space->GetMarkBitmap(); 1046 if (swap_bitmaps) { 1047 std::swap(live_bitmap, mark_bitmap); 1048 } 1049 Object** out = objects; 1050 for (size_t i = 0; i < count; ++i) { 1051 Object* obj = objects[i]; 1052 if (kUseThreadLocalAllocationStack && obj == nullptr) { 1053 continue; 1054 } 1055 if (space->HasAddress(obj)) { 1056 // This object is in the space, remove it from the array and add it to the sweep buffer 1057 // if needed. 1058 if (!mark_bitmap->Test(obj)) { 1059 if (chunk_free_pos >= kSweepArrayChunkFreeSize) { 1060 timings_.StartSplit("FreeList"); 1061 freed_objects += chunk_free_pos; 1062 freed_bytes += alloc_space->FreeList(self, chunk_free_pos, chunk_free_buffer); 1063 timings_.EndSplit(); 1064 chunk_free_pos = 0; 1065 } 1066 chunk_free_buffer[chunk_free_pos++] = obj; 1067 } 1068 } else { 1069 *(out++) = obj; 1070 } 1071 } 1072 if (chunk_free_pos > 0) { 1073 timings_.StartSplit("FreeList"); 1074 freed_objects += chunk_free_pos; 1075 freed_bytes += alloc_space->FreeList(self, chunk_free_pos, chunk_free_buffer); 1076 timings_.EndSplit(); 1077 chunk_free_pos = 0; 1078 } 1079 // All of the references which space contained are no longer in the allocation stack, update 1080 // the count. 1081 count = out - objects; 1082 } 1083 // Handle the large object space. 1084 space::LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace(); 1085 accounting::ObjectSet* large_live_objects = large_object_space->GetLiveObjects(); 1086 accounting::ObjectSet* large_mark_objects = large_object_space->GetMarkObjects(); 1087 if (swap_bitmaps) { 1088 std::swap(large_live_objects, large_mark_objects); 1089 } 1090 for (size_t i = 0; i < count; ++i) { 1091 Object* obj = objects[i]; 1092 // Handle large objects. 1093 if (kUseThreadLocalAllocationStack && obj == nullptr) { 1094 continue; 1095 } 1096 if (!large_mark_objects->Test(obj)) { 1097 ++freed_large_objects; 1098 freed_large_object_bytes += large_object_space->Free(self, obj); 1099 } 1100 } 1101 timings_.EndSplit(); 1102 1103 timings_.StartSplit("RecordFree"); 1104 VLOG(heap) << "Freed " << freed_objects << "/" << count 1105 << " objects with size " << PrettySize(freed_bytes); 1106 heap_->RecordFree(freed_objects + freed_large_objects, freed_bytes + freed_large_object_bytes); 1107 freed_objects_.FetchAndAdd(freed_objects); 1108 freed_large_objects_.FetchAndAdd(freed_large_objects); 1109 freed_bytes_.FetchAndAdd(freed_bytes); 1110 freed_large_object_bytes_.FetchAndAdd(freed_large_object_bytes); 1111 timings_.EndSplit(); 1112 1113 timings_.StartSplit("ResetStack"); 1114 allocations->Reset(); 1115 timings_.EndSplit(); 1116} 1117 1118void MarkSweep::Sweep(bool swap_bitmaps) { 1119 // Ensure that nobody inserted items in the live stack after we swapped the stacks. 1120 CHECK_GE(live_stack_freeze_size_, GetHeap()->GetLiveStack()->Size()); 1121 // Mark everything allocated since the last as GC live so that we can sweep concurrently, 1122 // knowing that new allocations won't be marked as live. 1123 timings_.StartSplit("MarkStackAsLive"); 1124 accounting::ObjectStack* live_stack = heap_->GetLiveStack(); 1125 heap_->MarkAllocStackAsLive(live_stack); 1126 live_stack->Reset(); 1127 timings_.EndSplit(); 1128 1129 DCHECK(mark_stack_->IsEmpty()); 1130 TimingLogger::ScopedSplit("Sweep", &timings_); 1131 for (const auto& space : GetHeap()->GetContinuousSpaces()) { 1132 if (space->IsContinuousMemMapAllocSpace()) { 1133 space::ContinuousMemMapAllocSpace* alloc_space = space->AsContinuousMemMapAllocSpace(); 1134 TimingLogger::ScopedSplit split( 1135 alloc_space->IsZygoteSpace() ? "SweepZygoteSpace" : "SweepMallocSpace", &timings_); 1136 size_t freed_objects = 0; 1137 size_t freed_bytes = 0; 1138 alloc_space->Sweep(swap_bitmaps, &freed_objects, &freed_bytes); 1139 heap_->RecordFree(freed_objects, freed_bytes); 1140 freed_objects_.FetchAndAdd(freed_objects); 1141 freed_bytes_.FetchAndAdd(freed_bytes); 1142 } 1143 } 1144 SweepLargeObjects(swap_bitmaps); 1145} 1146 1147void MarkSweep::SweepLargeObjects(bool swap_bitmaps) { 1148 TimingLogger::ScopedSplit("SweepLargeObjects", &timings_); 1149 size_t freed_objects = 0; 1150 size_t freed_bytes = 0; 1151 GetHeap()->GetLargeObjectsSpace()->Sweep(swap_bitmaps, &freed_objects, &freed_bytes); 1152 freed_large_objects_.FetchAndAdd(freed_objects); 1153 freed_large_object_bytes_.FetchAndAdd(freed_bytes); 1154 GetHeap()->RecordFree(freed_objects, freed_bytes); 1155} 1156 1157// Process the "referent" field in a java.lang.ref.Reference. If the referent has not yet been 1158// marked, put it on the appropriate list in the heap for later processing. 1159void MarkSweep::DelayReferenceReferent(mirror::Class* klass, mirror::Reference* ref) { 1160 DCHECK(klass != nullptr); 1161 if (kCountJavaLangRefs) { 1162 ++reference_count_; 1163 } 1164 heap_->DelayReferenceReferent(klass, ref, IsMarkedCallback, this); 1165} 1166 1167class MarkObjectVisitor { 1168 public: 1169 explicit MarkObjectVisitor(MarkSweep* const mark_sweep) ALWAYS_INLINE : mark_sweep_(mark_sweep) { 1170 } 1171 1172 void operator()(Object* obj, MemberOffset offset, bool /* is_static */) const 1173 ALWAYS_INLINE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) 1174 EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) { 1175 if (kCheckLocks) { 1176 Locks::mutator_lock_->AssertSharedHeld(Thread::Current()); 1177 Locks::heap_bitmap_lock_->AssertExclusiveHeld(Thread::Current()); 1178 } 1179 mark_sweep_->MarkObject(obj->GetFieldObject<mirror::Object>(offset, false)); 1180 } 1181 1182 private: 1183 MarkSweep* const mark_sweep_; 1184}; 1185 1186// Scans an object reference. Determines the type of the reference 1187// and dispatches to a specialized scanning routine. 1188void MarkSweep::ScanObject(Object* obj) { 1189 MarkObjectVisitor mark_visitor(this); 1190 DelayReferenceReferentVisitor ref_visitor(this); 1191 ScanObjectVisit(obj, mark_visitor, ref_visitor); 1192} 1193 1194void MarkSweep::ProcessMarkStackPausedCallback(void* arg) { 1195 reinterpret_cast<MarkSweep*>(arg)->ProcessMarkStack(true); 1196} 1197 1198void MarkSweep::ProcessMarkStackParallel(size_t thread_count) { 1199 Thread* self = Thread::Current(); 1200 ThreadPool* thread_pool = GetHeap()->GetThreadPool(); 1201 const size_t chunk_size = std::min(mark_stack_->Size() / thread_count + 1, 1202 static_cast<size_t>(MarkStackTask<false>::kMaxSize)); 1203 CHECK_GT(chunk_size, 0U); 1204 // Split the current mark stack up into work tasks. 1205 for (mirror::Object **it = mark_stack_->Begin(), **end = mark_stack_->End(); it < end; ) { 1206 const size_t delta = std::min(static_cast<size_t>(end - it), chunk_size); 1207 thread_pool->AddTask(self, new MarkStackTask<false>(thread_pool, this, delta, it)); 1208 it += delta; 1209 } 1210 thread_pool->SetMaxActiveWorkers(thread_count - 1); 1211 thread_pool->StartWorkers(self); 1212 thread_pool->Wait(self, true, true); 1213 thread_pool->StopWorkers(self); 1214 mark_stack_->Reset(); 1215 CHECK_EQ(work_chunks_created_, work_chunks_deleted_) << " some of the work chunks were leaked"; 1216} 1217 1218// Scan anything that's on the mark stack. 1219void MarkSweep::ProcessMarkStack(bool paused) { 1220 timings_.StartSplit(paused ? "(Paused)ProcessMarkStack" : "ProcessMarkStack"); 1221 size_t thread_count = GetThreadCount(paused); 1222 if (kParallelProcessMarkStack && thread_count > 1 && 1223 mark_stack_->Size() >= kMinimumParallelMarkStackSize) { 1224 ProcessMarkStackParallel(thread_count); 1225 } else { 1226 // TODO: Tune this. 1227 static const size_t kFifoSize = 4; 1228 BoundedFifoPowerOfTwo<Object*, kFifoSize> prefetch_fifo; 1229 for (;;) { 1230 Object* obj = NULL; 1231 if (kUseMarkStackPrefetch) { 1232 while (!mark_stack_->IsEmpty() && prefetch_fifo.size() < kFifoSize) { 1233 Object* obj = mark_stack_->PopBack(); 1234 DCHECK(obj != NULL); 1235 __builtin_prefetch(obj); 1236 prefetch_fifo.push_back(obj); 1237 } 1238 if (prefetch_fifo.empty()) { 1239 break; 1240 } 1241 obj = prefetch_fifo.front(); 1242 prefetch_fifo.pop_front(); 1243 } else { 1244 if (mark_stack_->IsEmpty()) { 1245 break; 1246 } 1247 obj = mark_stack_->PopBack(); 1248 } 1249 DCHECK(obj != nullptr); 1250 ScanObject(obj); 1251 } 1252 } 1253 timings_.EndSplit(); 1254} 1255 1256inline bool MarkSweep::IsMarked(const Object* object) const 1257 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) { 1258 if (immune_region_.ContainsObject(object)) { 1259 return true; 1260 } 1261 if (current_space_bitmap_->HasAddress(object)) { 1262 return current_space_bitmap_->Test(object); 1263 } 1264 return mark_bitmap_->Test(object); 1265} 1266 1267void MarkSweep::FinishPhase() { 1268 TimingLogger::ScopedSplit split("FinishPhase", &timings_); 1269 // Can't enqueue references if we hold the mutator lock. 1270 timings_.NewSplit("PostGcVerification"); 1271 heap_->PostGcVerification(this); 1272 if (kCountScannedTypes) { 1273 VLOG(gc) << "MarkSweep scanned classes=" << class_count_ << " arrays=" << array_count_ 1274 << " other=" << other_count_; 1275 } 1276 if (kCountTasks) { 1277 VLOG(gc) << "Total number of work chunks allocated: " << work_chunks_created_; 1278 } 1279 if (kMeasureOverhead) { 1280 VLOG(gc) << "Overhead time " << PrettyDuration(overhead_time_); 1281 } 1282 if (kProfileLargeObjects) { 1283 VLOG(gc) << "Large objects tested " << large_object_test_ << " marked " << large_object_mark_; 1284 } 1285 if (kCountJavaLangRefs) { 1286 VLOG(gc) << "References scanned " << reference_count_; 1287 } 1288 if (kCountMarkedObjects) { 1289 VLOG(gc) << "Marked: null=" << mark_null_count_ << " immune=" << mark_immune_count_ 1290 << " fastpath=" << mark_fastpath_count_ << " slowpath=" << mark_slowpath_count_; 1291 } 1292 CHECK(mark_stack_->IsEmpty()); // Ensure that the mark stack is empty. 1293 mark_stack_->Reset(); 1294 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_); 1295 heap_->ClearMarkedObjects(); 1296} 1297 1298void MarkSweep::RevokeAllThreadLocalBuffers() { 1299 if (kRevokeRosAllocThreadLocalBuffersAtCheckpoint && IsConcurrent()) { 1300 // If concurrent, rosalloc thread-local buffers are revoked at the 1301 // thread checkpoint. Bump pointer space thread-local buffers must 1302 // not be in use. 1303 GetHeap()->AssertAllBumpPointerSpaceThreadLocalBuffersAreRevoked(); 1304 } else { 1305 timings_.StartSplit("(Paused)RevokeAllThreadLocalBuffers"); 1306 GetHeap()->RevokeAllThreadLocalBuffers(); 1307 timings_.EndSplit(); 1308 } 1309} 1310 1311} // namespace collector 1312} // namespace gc 1313} // namespace art 1314