concurrent_copying.cc revision 763a31ed7a2bfad22a9cb07f5301a71c0f97ca49
1/* 2 * Copyright (C) 2014 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 "concurrent_copying.h" 18 19#include "art_field-inl.h" 20#include "base/stl_util.h" 21#include "debugger.h" 22#include "gc/accounting/heap_bitmap-inl.h" 23#include "gc/accounting/space_bitmap-inl.h" 24#include "gc/reference_processor.h" 25#include "gc/space/image_space.h" 26#include "gc/space/space-inl.h" 27#include "intern_table.h" 28#include "mirror/class-inl.h" 29#include "mirror/object-inl.h" 30#include "scoped_thread_state_change.h" 31#include "thread-inl.h" 32#include "thread_list.h" 33#include "well_known_classes.h" 34 35namespace art { 36namespace gc { 37namespace collector { 38 39static constexpr size_t kDefaultGcMarkStackSize = 2 * MB; 40 41ConcurrentCopying::ConcurrentCopying(Heap* heap, const std::string& name_prefix) 42 : GarbageCollector(heap, 43 name_prefix + (name_prefix.empty() ? "" : " ") + 44 "concurrent copying + mark sweep"), 45 region_space_(nullptr), gc_barrier_(new Barrier(0)), 46 gc_mark_stack_(accounting::ObjectStack::Create("concurrent copying gc mark stack", 47 kDefaultGcMarkStackSize, 48 kDefaultGcMarkStackSize)), 49 mark_stack_lock_("concurrent copying mark stack lock", kMarkSweepMarkStackLock), 50 thread_running_gc_(nullptr), 51 is_marking_(false), is_active_(false), is_asserting_to_space_invariant_(false), 52 heap_mark_bitmap_(nullptr), live_stack_freeze_size_(0), mark_stack_mode_(kMarkStackModeOff), 53 weak_ref_access_enabled_(true), 54 skipped_blocks_lock_("concurrent copying bytes blocks lock", kMarkSweepMarkStackLock), 55 rb_table_(heap_->GetReadBarrierTable()), 56 force_evacuate_all_(false) { 57 static_assert(space::RegionSpace::kRegionSize == accounting::ReadBarrierTable::kRegionSize, 58 "The region space size and the read barrier table region size must match"); 59 cc_heap_bitmap_.reset(new accounting::HeapBitmap(heap)); 60 Thread* self = Thread::Current(); 61 { 62 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_); 63 // Cache this so that we won't have to lock heap_bitmap_lock_ in 64 // Mark() which could cause a nested lock on heap_bitmap_lock_ 65 // when GC causes a RB while doing GC or a lock order violation 66 // (class_linker_lock_ and heap_bitmap_lock_). 67 heap_mark_bitmap_ = heap->GetMarkBitmap(); 68 } 69 { 70 MutexLock mu(self, mark_stack_lock_); 71 for (size_t i = 0; i < kMarkStackPoolSize; ++i) { 72 accounting::AtomicStack<mirror::Object>* mark_stack = 73 accounting::AtomicStack<mirror::Object>::Create( 74 "thread local mark stack", kMarkStackSize, kMarkStackSize); 75 pooled_mark_stacks_.push_back(mark_stack); 76 } 77 } 78} 79 80void ConcurrentCopying::MarkHeapReference(mirror::HeapReference<mirror::Object>* from_ref) { 81 // Used for preserving soft references, should be OK to not have a CAS here since there should be 82 // no other threads which can trigger read barriers on the same referent during reference 83 // processing. 84 from_ref->Assign(Mark(from_ref->AsMirrorPtr())); 85 DCHECK(!from_ref->IsNull()); 86} 87 88ConcurrentCopying::~ConcurrentCopying() { 89 STLDeleteElements(&pooled_mark_stacks_); 90} 91 92void ConcurrentCopying::RunPhases() { 93 CHECK(kUseBakerReadBarrier || kUseTableLookupReadBarrier); 94 CHECK(!is_active_); 95 is_active_ = true; 96 Thread* self = Thread::Current(); 97 thread_running_gc_ = self; 98 Locks::mutator_lock_->AssertNotHeld(self); 99 { 100 ReaderMutexLock mu(self, *Locks::mutator_lock_); 101 InitializePhase(); 102 } 103 FlipThreadRoots(); 104 { 105 ReaderMutexLock mu(self, *Locks::mutator_lock_); 106 MarkingPhase(); 107 } 108 // Verify no from space refs. This causes a pause. 109 if (kEnableNoFromSpaceRefsVerification || kIsDebugBuild) { 110 TimingLogger::ScopedTiming split("(Paused)VerifyNoFromSpaceReferences", GetTimings()); 111 ScopedPause pause(this); 112 CheckEmptyMarkStack(); 113 if (kVerboseMode) { 114 LOG(INFO) << "Verifying no from-space refs"; 115 } 116 VerifyNoFromSpaceReferences(); 117 if (kVerboseMode) { 118 LOG(INFO) << "Done verifying no from-space refs"; 119 } 120 CheckEmptyMarkStack(); 121 } 122 { 123 ReaderMutexLock mu(self, *Locks::mutator_lock_); 124 ReclaimPhase(); 125 } 126 FinishPhase(); 127 CHECK(is_active_); 128 is_active_ = false; 129 thread_running_gc_ = nullptr; 130} 131 132void ConcurrentCopying::BindBitmaps() { 133 Thread* self = Thread::Current(); 134 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_); 135 // Mark all of the spaces we never collect as immune. 136 for (const auto& space : heap_->GetContinuousSpaces()) { 137 if (space->GetGcRetentionPolicy() == space::kGcRetentionPolicyNeverCollect || 138 space->GetGcRetentionPolicy() == space::kGcRetentionPolicyFullCollect) { 139 CHECK(space->IsZygoteSpace() || space->IsImageSpace()); 140 immune_spaces_.AddSpace(space); 141 const char* bitmap_name = space->IsImageSpace() ? "cc image space bitmap" : 142 "cc zygote space bitmap"; 143 // TODO: try avoiding using bitmaps for image/zygote to save space. 144 accounting::ContinuousSpaceBitmap* bitmap = 145 accounting::ContinuousSpaceBitmap::Create(bitmap_name, space->Begin(), space->Capacity()); 146 cc_heap_bitmap_->AddContinuousSpaceBitmap(bitmap); 147 cc_bitmaps_.push_back(bitmap); 148 } else if (space == region_space_) { 149 accounting::ContinuousSpaceBitmap* bitmap = 150 accounting::ContinuousSpaceBitmap::Create("cc region space bitmap", 151 space->Begin(), space->Capacity()); 152 cc_heap_bitmap_->AddContinuousSpaceBitmap(bitmap); 153 cc_bitmaps_.push_back(bitmap); 154 region_space_bitmap_ = bitmap; 155 } 156 } 157} 158 159void ConcurrentCopying::InitializePhase() { 160 TimingLogger::ScopedTiming split("InitializePhase", GetTimings()); 161 if (kVerboseMode) { 162 LOG(INFO) << "GC InitializePhase"; 163 LOG(INFO) << "Region-space : " << reinterpret_cast<void*>(region_space_->Begin()) << "-" 164 << reinterpret_cast<void*>(region_space_->Limit()); 165 } 166 CheckEmptyMarkStack(); 167 immune_spaces_.Reset(); 168 bytes_moved_.StoreRelaxed(0); 169 objects_moved_.StoreRelaxed(0); 170 if (GetCurrentIteration()->GetGcCause() == kGcCauseExplicit || 171 GetCurrentIteration()->GetGcCause() == kGcCauseForNativeAlloc || 172 GetCurrentIteration()->GetClearSoftReferences()) { 173 force_evacuate_all_ = true; 174 } else { 175 force_evacuate_all_ = false; 176 } 177 BindBitmaps(); 178 if (kVerboseMode) { 179 LOG(INFO) << "force_evacuate_all=" << force_evacuate_all_; 180 LOG(INFO) << "Largest immune region: " << immune_spaces_.GetLargestImmuneRegion().Begin() 181 << "-" << immune_spaces_.GetLargestImmuneRegion().End(); 182 for (space::ContinuousSpace* space : immune_spaces_.GetSpaces()) { 183 LOG(INFO) << "Immune space: " << *space; 184 } 185 LOG(INFO) << "GC end of InitializePhase"; 186 } 187} 188 189// Used to switch the thread roots of a thread from from-space refs to to-space refs. 190class ThreadFlipVisitor : public Closure { 191 public: 192 ThreadFlipVisitor(ConcurrentCopying* concurrent_copying, bool use_tlab) 193 : concurrent_copying_(concurrent_copying), use_tlab_(use_tlab) { 194 } 195 196 virtual void Run(Thread* thread) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) { 197 // Note: self is not necessarily equal to thread since thread may be suspended. 198 Thread* self = Thread::Current(); 199 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc) 200 << thread->GetState() << " thread " << thread << " self " << self; 201 thread->SetIsGcMarking(true); 202 if (use_tlab_ && thread->HasTlab()) { 203 if (ConcurrentCopying::kEnableFromSpaceAccountingCheck) { 204 // This must come before the revoke. 205 size_t thread_local_objects = thread->GetThreadLocalObjectsAllocated(); 206 concurrent_copying_->region_space_->RevokeThreadLocalBuffers(thread); 207 reinterpret_cast<Atomic<size_t>*>(&concurrent_copying_->from_space_num_objects_at_first_pause_)-> 208 FetchAndAddSequentiallyConsistent(thread_local_objects); 209 } else { 210 concurrent_copying_->region_space_->RevokeThreadLocalBuffers(thread); 211 } 212 } 213 if (kUseThreadLocalAllocationStack) { 214 thread->RevokeThreadLocalAllocationStack(); 215 } 216 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_); 217 thread->VisitRoots(concurrent_copying_); 218 concurrent_copying_->GetBarrier().Pass(self); 219 } 220 221 private: 222 ConcurrentCopying* const concurrent_copying_; 223 const bool use_tlab_; 224}; 225 226// Called back from Runtime::FlipThreadRoots() during a pause. 227class FlipCallback : public Closure { 228 public: 229 explicit FlipCallback(ConcurrentCopying* concurrent_copying) 230 : concurrent_copying_(concurrent_copying) { 231 } 232 233 virtual void Run(Thread* thread) OVERRIDE REQUIRES(Locks::mutator_lock_) { 234 ConcurrentCopying* cc = concurrent_copying_; 235 TimingLogger::ScopedTiming split("(Paused)FlipCallback", cc->GetTimings()); 236 // Note: self is not necessarily equal to thread since thread may be suspended. 237 Thread* self = Thread::Current(); 238 CHECK(thread == self); 239 Locks::mutator_lock_->AssertExclusiveHeld(self); 240 cc->region_space_->SetFromSpace(cc->rb_table_, cc->force_evacuate_all_); 241 cc->SwapStacks(); 242 if (ConcurrentCopying::kEnableFromSpaceAccountingCheck) { 243 cc->RecordLiveStackFreezeSize(self); 244 cc->from_space_num_objects_at_first_pause_ = cc->region_space_->GetObjectsAllocated(); 245 cc->from_space_num_bytes_at_first_pause_ = cc->region_space_->GetBytesAllocated(); 246 } 247 cc->is_marking_ = true; 248 cc->mark_stack_mode_.StoreRelaxed(ConcurrentCopying::kMarkStackModeThreadLocal); 249 if (UNLIKELY(Runtime::Current()->IsActiveTransaction())) { 250 CHECK(Runtime::Current()->IsAotCompiler()); 251 TimingLogger::ScopedTiming split2("(Paused)VisitTransactionRoots", cc->GetTimings()); 252 Runtime::Current()->VisitTransactionRoots(cc); 253 } 254 } 255 256 private: 257 ConcurrentCopying* const concurrent_copying_; 258}; 259 260// Switch threads that from from-space to to-space refs. Forward/mark the thread roots. 261void ConcurrentCopying::FlipThreadRoots() { 262 TimingLogger::ScopedTiming split("FlipThreadRoots", GetTimings()); 263 if (kVerboseMode) { 264 LOG(INFO) << "time=" << region_space_->Time(); 265 region_space_->DumpNonFreeRegions(LOG(INFO)); 266 } 267 Thread* self = Thread::Current(); 268 Locks::mutator_lock_->AssertNotHeld(self); 269 gc_barrier_->Init(self, 0); 270 ThreadFlipVisitor thread_flip_visitor(this, heap_->use_tlab_); 271 FlipCallback flip_callback(this); 272 heap_->ThreadFlipBegin(self); // Sync with JNI critical calls. 273 size_t barrier_count = Runtime::Current()->FlipThreadRoots( 274 &thread_flip_visitor, &flip_callback, this); 275 heap_->ThreadFlipEnd(self); 276 { 277 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun); 278 gc_barrier_->Increment(self, barrier_count); 279 } 280 is_asserting_to_space_invariant_ = true; 281 QuasiAtomic::ThreadFenceForConstructor(); 282 if (kVerboseMode) { 283 LOG(INFO) << "time=" << region_space_->Time(); 284 region_space_->DumpNonFreeRegions(LOG(INFO)); 285 LOG(INFO) << "GC end of FlipThreadRoots"; 286 } 287} 288 289void ConcurrentCopying::SwapStacks() { 290 heap_->SwapStacks(); 291} 292 293void ConcurrentCopying::RecordLiveStackFreezeSize(Thread* self) { 294 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_); 295 live_stack_freeze_size_ = heap_->GetLiveStack()->Size(); 296} 297 298// Used to visit objects in the immune spaces. 299class ConcurrentCopyingImmuneSpaceObjVisitor { 300 public: 301 explicit ConcurrentCopyingImmuneSpaceObjVisitor(ConcurrentCopying* cc) 302 : collector_(cc) {} 303 304 void operator()(mirror::Object* obj) const SHARED_REQUIRES(Locks::mutator_lock_) 305 SHARED_REQUIRES(Locks::heap_bitmap_lock_) { 306 DCHECK(obj != nullptr); 307 DCHECK(collector_->immune_spaces_.ContainsObject(obj)); 308 accounting::ContinuousSpaceBitmap* cc_bitmap = 309 collector_->cc_heap_bitmap_->GetContinuousSpaceBitmap(obj); 310 DCHECK(cc_bitmap != nullptr) 311 << "An immune space object must have a bitmap"; 312 if (kIsDebugBuild) { 313 DCHECK(collector_->heap_->GetMarkBitmap()->Test(obj)) 314 << "Immune space object must be already marked"; 315 } 316 // This may or may not succeed, which is ok. 317 if (kUseBakerReadBarrier) { 318 obj->AtomicSetReadBarrierPointer(ReadBarrier::WhitePtr(), ReadBarrier::GrayPtr()); 319 } 320 if (cc_bitmap->AtomicTestAndSet(obj)) { 321 // Already marked. Do nothing. 322 } else { 323 // Newly marked. Set the gray bit and push it onto the mark stack. 324 CHECK(!kUseBakerReadBarrier || obj->GetReadBarrierPointer() == ReadBarrier::GrayPtr()); 325 collector_->PushOntoMarkStack(obj); 326 } 327 } 328 329 private: 330 ConcurrentCopying* const collector_; 331}; 332 333class EmptyCheckpoint : public Closure { 334 public: 335 explicit EmptyCheckpoint(ConcurrentCopying* concurrent_copying) 336 : concurrent_copying_(concurrent_copying) { 337 } 338 339 virtual void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS { 340 // Note: self is not necessarily equal to thread since thread may be suspended. 341 Thread* self = Thread::Current(); 342 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc) 343 << thread->GetState() << " thread " << thread << " self " << self; 344 // If thread is a running mutator, then act on behalf of the garbage collector. 345 // See the code in ThreadList::RunCheckpoint. 346 concurrent_copying_->GetBarrier().Pass(self); 347 } 348 349 private: 350 ConcurrentCopying* const concurrent_copying_; 351}; 352 353// Concurrently mark roots that are guarded by read barriers and process the mark stack. 354void ConcurrentCopying::MarkingPhase() { 355 TimingLogger::ScopedTiming split("MarkingPhase", GetTimings()); 356 if (kVerboseMode) { 357 LOG(INFO) << "GC MarkingPhase"; 358 } 359 CHECK(weak_ref_access_enabled_); 360 { 361 // Mark the image root. The WB-based collectors do not need to 362 // scan the image objects from roots by relying on the card table, 363 // but it's necessary for the RB to-space invariant to hold. 364 TimingLogger::ScopedTiming split1("VisitImageRoots", GetTimings()); 365 for (space::ContinuousSpace* space : heap_->GetContinuousSpaces()) { 366 if (space->IsImageSpace()) { 367 gc::space::ImageSpace* image = space->AsImageSpace(); 368 if (image != nullptr) { 369 mirror::ObjectArray<mirror::Object>* image_root = image->GetImageHeader().GetImageRoots(); 370 mirror::Object* marked_image_root = Mark(image_root); 371 CHECK_EQ(image_root, marked_image_root) << "An image object does not move"; 372 if (ReadBarrier::kEnableToSpaceInvariantChecks) { 373 AssertToSpaceInvariant(nullptr, MemberOffset(0), marked_image_root); 374 } 375 } 376 } 377 } 378 } 379 { 380 TimingLogger::ScopedTiming split2("VisitConcurrentRoots", GetTimings()); 381 Runtime::Current()->VisitConcurrentRoots(this, kVisitRootFlagAllRoots); 382 } 383 { 384 // TODO: don't visit the transaction roots if it's not active. 385 TimingLogger::ScopedTiming split5("VisitNonThreadRoots", GetTimings()); 386 Runtime::Current()->VisitNonThreadRoots(this); 387 } 388 389 // Immune spaces. 390 for (auto& space : immune_spaces_.GetSpaces()) { 391 DCHECK(space->IsImageSpace() || space->IsZygoteSpace()); 392 accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap(); 393 ConcurrentCopyingImmuneSpaceObjVisitor visitor(this); 394 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()), 395 reinterpret_cast<uintptr_t>(space->Limit()), 396 visitor); 397 } 398 399 Thread* self = Thread::Current(); 400 { 401 TimingLogger::ScopedTiming split7("ProcessMarkStack", GetTimings()); 402 // We transition through three mark stack modes (thread-local, shared, GC-exclusive). The 403 // primary reasons are the fact that we need to use a checkpoint to process thread-local mark 404 // stacks, but after we disable weak refs accesses, we can't use a checkpoint due to a deadlock 405 // issue because running threads potentially blocking at WaitHoldingLocks, and that once we 406 // reach the point where we process weak references, we can avoid using a lock when accessing 407 // the GC mark stack, which makes mark stack processing more efficient. 408 409 // Process the mark stack once in the thread local stack mode. This marks most of the live 410 // objects, aside from weak ref accesses with read barriers (Reference::GetReferent() and system 411 // weaks) that may happen concurrently while we processing the mark stack and newly mark/gray 412 // objects and push refs on the mark stack. 413 ProcessMarkStack(); 414 // Switch to the shared mark stack mode. That is, revoke and process thread-local mark stacks 415 // for the last time before transitioning to the shared mark stack mode, which would process new 416 // refs that may have been concurrently pushed onto the mark stack during the ProcessMarkStack() 417 // call above. At the same time, disable weak ref accesses using a per-thread flag. It's 418 // important to do these together in a single checkpoint so that we can ensure that mutators 419 // won't newly gray objects and push new refs onto the mark stack due to weak ref accesses and 420 // mutators safely transition to the shared mark stack mode (without leaving unprocessed refs on 421 // the thread-local mark stacks), without a race. This is why we use a thread-local weak ref 422 // access flag Thread::tls32_.weak_ref_access_enabled_ instead of the global ones. 423 SwitchToSharedMarkStackMode(); 424 CHECK(!self->GetWeakRefAccessEnabled()); 425 // Now that weak refs accesses are disabled, once we exhaust the shared mark stack again here 426 // (which may be non-empty if there were refs found on thread-local mark stacks during the above 427 // SwitchToSharedMarkStackMode() call), we won't have new refs to process, that is, mutators 428 // (via read barriers) have no way to produce any more refs to process. Marking converges once 429 // before we process weak refs below. 430 ProcessMarkStack(); 431 CheckEmptyMarkStack(); 432 // Switch to the GC exclusive mark stack mode so that we can process the mark stack without a 433 // lock from this point on. 434 SwitchToGcExclusiveMarkStackMode(); 435 CheckEmptyMarkStack(); 436 if (kVerboseMode) { 437 LOG(INFO) << "ProcessReferences"; 438 } 439 // Process weak references. This may produce new refs to process and have them processed via 440 // ProcessMarkStack (in the GC exclusive mark stack mode). 441 ProcessReferences(self); 442 CheckEmptyMarkStack(); 443 if (kVerboseMode) { 444 LOG(INFO) << "SweepSystemWeaks"; 445 } 446 SweepSystemWeaks(self); 447 if (kVerboseMode) { 448 LOG(INFO) << "SweepSystemWeaks done"; 449 } 450 // Process the mark stack here one last time because the above SweepSystemWeaks() call may have 451 // marked some objects (strings alive) as hash_set::Erase() can call the hash function for 452 // arbitrary elements in the weak intern table in InternTable::Table::SweepWeaks(). 453 ProcessMarkStack(); 454 CheckEmptyMarkStack(); 455 // Re-enable weak ref accesses. 456 ReenableWeakRefAccess(self); 457 // Free data for class loaders that we unloaded. 458 Runtime::Current()->GetClassLinker()->CleanupClassLoaders(); 459 // Marking is done. Disable marking. 460 DisableMarking(); 461 CheckEmptyMarkStack(); 462 } 463 464 CHECK(weak_ref_access_enabled_); 465 if (kVerboseMode) { 466 LOG(INFO) << "GC end of MarkingPhase"; 467 } 468} 469 470void ConcurrentCopying::ReenableWeakRefAccess(Thread* self) { 471 if (kVerboseMode) { 472 LOG(INFO) << "ReenableWeakRefAccess"; 473 } 474 weak_ref_access_enabled_.StoreRelaxed(true); // This is for new threads. 475 QuasiAtomic::ThreadFenceForConstructor(); 476 // Iterate all threads (don't need to or can't use a checkpoint) and re-enable weak ref access. 477 { 478 MutexLock mu(self, *Locks::thread_list_lock_); 479 std::list<Thread*> thread_list = Runtime::Current()->GetThreadList()->GetList(); 480 for (Thread* thread : thread_list) { 481 thread->SetWeakRefAccessEnabled(true); 482 } 483 } 484 // Unblock blocking threads. 485 GetHeap()->GetReferenceProcessor()->BroadcastForSlowPath(self); 486 Runtime::Current()->BroadcastForNewSystemWeaks(); 487} 488 489class DisableMarkingCheckpoint : public Closure { 490 public: 491 explicit DisableMarkingCheckpoint(ConcurrentCopying* concurrent_copying) 492 : concurrent_copying_(concurrent_copying) { 493 } 494 495 void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS { 496 // Note: self is not necessarily equal to thread since thread may be suspended. 497 Thread* self = Thread::Current(); 498 DCHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc) 499 << thread->GetState() << " thread " << thread << " self " << self; 500 // Disable the thread-local is_gc_marking flag. 501 // Note a thread that has just started right before this checkpoint may have already this flag 502 // set to false, which is ok. 503 thread->SetIsGcMarking(false); 504 // If thread is a running mutator, then act on behalf of the garbage collector. 505 // See the code in ThreadList::RunCheckpoint. 506 concurrent_copying_->GetBarrier().Pass(self); 507 } 508 509 private: 510 ConcurrentCopying* const concurrent_copying_; 511}; 512 513void ConcurrentCopying::IssueDisableMarkingCheckpoint() { 514 Thread* self = Thread::Current(); 515 DisableMarkingCheckpoint check_point(this); 516 ThreadList* thread_list = Runtime::Current()->GetThreadList(); 517 gc_barrier_->Init(self, 0); 518 size_t barrier_count = thread_list->RunCheckpoint(&check_point); 519 // If there are no threads to wait which implies that all the checkpoint functions are finished, 520 // then no need to release the mutator lock. 521 if (barrier_count == 0) { 522 return; 523 } 524 // Release locks then wait for all mutator threads to pass the barrier. 525 Locks::mutator_lock_->SharedUnlock(self); 526 { 527 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun); 528 gc_barrier_->Increment(self, barrier_count); 529 } 530 Locks::mutator_lock_->SharedLock(self); 531} 532 533void ConcurrentCopying::DisableMarking() { 534 // Change the global is_marking flag to false. Do a fence before doing a checkpoint to update the 535 // thread-local flags so that a new thread starting up will get the correct is_marking flag. 536 is_marking_ = false; 537 QuasiAtomic::ThreadFenceForConstructor(); 538 // Use a checkpoint to turn off the thread-local is_gc_marking flags and to ensure no threads are 539 // still in the middle of a read barrier which may have a from-space ref cached in a local 540 // variable. 541 IssueDisableMarkingCheckpoint(); 542 if (kUseTableLookupReadBarrier) { 543 heap_->rb_table_->ClearAll(); 544 DCHECK(heap_->rb_table_->IsAllCleared()); 545 } 546 is_mark_stack_push_disallowed_.StoreSequentiallyConsistent(1); 547 mark_stack_mode_.StoreSequentiallyConsistent(kMarkStackModeOff); 548} 549 550void ConcurrentCopying::IssueEmptyCheckpoint() { 551 Thread* self = Thread::Current(); 552 EmptyCheckpoint check_point(this); 553 ThreadList* thread_list = Runtime::Current()->GetThreadList(); 554 gc_barrier_->Init(self, 0); 555 size_t barrier_count = thread_list->RunCheckpoint(&check_point); 556 // If there are no threads to wait which implys that all the checkpoint functions are finished, 557 // then no need to release the mutator lock. 558 if (barrier_count == 0) { 559 return; 560 } 561 // Release locks then wait for all mutator threads to pass the barrier. 562 Locks::mutator_lock_->SharedUnlock(self); 563 { 564 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun); 565 gc_barrier_->Increment(self, barrier_count); 566 } 567 Locks::mutator_lock_->SharedLock(self); 568} 569 570void ConcurrentCopying::ExpandGcMarkStack() { 571 DCHECK(gc_mark_stack_->IsFull()); 572 const size_t new_size = gc_mark_stack_->Capacity() * 2; 573 std::vector<StackReference<mirror::Object>> temp(gc_mark_stack_->Begin(), 574 gc_mark_stack_->End()); 575 gc_mark_stack_->Resize(new_size); 576 for (auto& ref : temp) { 577 gc_mark_stack_->PushBack(ref.AsMirrorPtr()); 578 } 579 DCHECK(!gc_mark_stack_->IsFull()); 580} 581 582void ConcurrentCopying::PushOntoMarkStack(mirror::Object* to_ref) { 583 CHECK_EQ(is_mark_stack_push_disallowed_.LoadRelaxed(), 0) 584 << " " << to_ref << " " << PrettyTypeOf(to_ref); 585 Thread* self = Thread::Current(); // TODO: pass self as an argument from call sites? 586 CHECK(thread_running_gc_ != nullptr); 587 MarkStackMode mark_stack_mode = mark_stack_mode_.LoadRelaxed(); 588 if (LIKELY(mark_stack_mode == kMarkStackModeThreadLocal)) { 589 if (LIKELY(self == thread_running_gc_)) { 590 // If GC-running thread, use the GC mark stack instead of a thread-local mark stack. 591 CHECK(self->GetThreadLocalMarkStack() == nullptr); 592 if (UNLIKELY(gc_mark_stack_->IsFull())) { 593 ExpandGcMarkStack(); 594 } 595 gc_mark_stack_->PushBack(to_ref); 596 } else { 597 // Otherwise, use a thread-local mark stack. 598 accounting::AtomicStack<mirror::Object>* tl_mark_stack = self->GetThreadLocalMarkStack(); 599 if (UNLIKELY(tl_mark_stack == nullptr || tl_mark_stack->IsFull())) { 600 MutexLock mu(self, mark_stack_lock_); 601 // Get a new thread local mark stack. 602 accounting::AtomicStack<mirror::Object>* new_tl_mark_stack; 603 if (!pooled_mark_stacks_.empty()) { 604 // Use a pooled mark stack. 605 new_tl_mark_stack = pooled_mark_stacks_.back(); 606 pooled_mark_stacks_.pop_back(); 607 } else { 608 // None pooled. Create a new one. 609 new_tl_mark_stack = 610 accounting::AtomicStack<mirror::Object>::Create( 611 "thread local mark stack", 4 * KB, 4 * KB); 612 } 613 DCHECK(new_tl_mark_stack != nullptr); 614 DCHECK(new_tl_mark_stack->IsEmpty()); 615 new_tl_mark_stack->PushBack(to_ref); 616 self->SetThreadLocalMarkStack(new_tl_mark_stack); 617 if (tl_mark_stack != nullptr) { 618 // Store the old full stack into a vector. 619 revoked_mark_stacks_.push_back(tl_mark_stack); 620 } 621 } else { 622 tl_mark_stack->PushBack(to_ref); 623 } 624 } 625 } else if (mark_stack_mode == kMarkStackModeShared) { 626 // Access the shared GC mark stack with a lock. 627 MutexLock mu(self, mark_stack_lock_); 628 if (UNLIKELY(gc_mark_stack_->IsFull())) { 629 ExpandGcMarkStack(); 630 } 631 gc_mark_stack_->PushBack(to_ref); 632 } else { 633 CHECK_EQ(static_cast<uint32_t>(mark_stack_mode), 634 static_cast<uint32_t>(kMarkStackModeGcExclusive)) 635 << "ref=" << to_ref 636 << " self->gc_marking=" << self->GetIsGcMarking() 637 << " cc->is_marking=" << is_marking_; 638 CHECK(self == thread_running_gc_) 639 << "Only GC-running thread should access the mark stack " 640 << "in the GC exclusive mark stack mode"; 641 // Access the GC mark stack without a lock. 642 if (UNLIKELY(gc_mark_stack_->IsFull())) { 643 ExpandGcMarkStack(); 644 } 645 gc_mark_stack_->PushBack(to_ref); 646 } 647} 648 649accounting::ObjectStack* ConcurrentCopying::GetAllocationStack() { 650 return heap_->allocation_stack_.get(); 651} 652 653accounting::ObjectStack* ConcurrentCopying::GetLiveStack() { 654 return heap_->live_stack_.get(); 655} 656 657// The following visitors are that used to verify that there's no 658// references to the from-space left after marking. 659class ConcurrentCopyingVerifyNoFromSpaceRefsVisitor : public SingleRootVisitor { 660 public: 661 explicit ConcurrentCopyingVerifyNoFromSpaceRefsVisitor(ConcurrentCopying* collector) 662 : collector_(collector) {} 663 664 void operator()(mirror::Object* ref) const 665 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE { 666 if (ref == nullptr) { 667 // OK. 668 return; 669 } 670 collector_->AssertToSpaceInvariant(nullptr, MemberOffset(0), ref); 671 if (kUseBakerReadBarrier) { 672 if (collector_->RegionSpace()->IsInToSpace(ref)) { 673 CHECK(ref->GetReadBarrierPointer() == nullptr) 674 << "To-space ref " << ref << " " << PrettyTypeOf(ref) 675 << " has non-white rb_ptr " << ref->GetReadBarrierPointer(); 676 } else { 677 CHECK(ref->GetReadBarrierPointer() == ReadBarrier::BlackPtr() || 678 (ref->GetReadBarrierPointer() == ReadBarrier::WhitePtr() && 679 collector_->IsOnAllocStack(ref))) 680 << "Non-moving/unevac from space ref " << ref << " " << PrettyTypeOf(ref) 681 << " has non-black rb_ptr " << ref->GetReadBarrierPointer() 682 << " but isn't on the alloc stack (and has white rb_ptr)." 683 << " Is it in the non-moving space=" 684 << (collector_->GetHeap()->GetNonMovingSpace()->HasAddress(ref)); 685 } 686 } 687 } 688 689 void VisitRoot(mirror::Object* root, const RootInfo& info ATTRIBUTE_UNUSED) 690 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) { 691 DCHECK(root != nullptr); 692 operator()(root); 693 } 694 695 private: 696 ConcurrentCopying* const collector_; 697}; 698 699class ConcurrentCopyingVerifyNoFromSpaceRefsFieldVisitor { 700 public: 701 explicit ConcurrentCopyingVerifyNoFromSpaceRefsFieldVisitor(ConcurrentCopying* collector) 702 : collector_(collector) {} 703 704 void operator()(mirror::Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const 705 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE { 706 mirror::Object* ref = 707 obj->GetFieldObject<mirror::Object, kDefaultVerifyFlags, kWithoutReadBarrier>(offset); 708 ConcurrentCopyingVerifyNoFromSpaceRefsVisitor visitor(collector_); 709 visitor(ref); 710 } 711 void operator()(mirror::Class* klass, mirror::Reference* ref) const 712 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE { 713 CHECK(klass->IsTypeOfReferenceClass()); 714 this->operator()(ref, mirror::Reference::ReferentOffset(), false); 715 } 716 717 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const 718 SHARED_REQUIRES(Locks::mutator_lock_) { 719 if (!root->IsNull()) { 720 VisitRoot(root); 721 } 722 } 723 724 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const 725 SHARED_REQUIRES(Locks::mutator_lock_) { 726 ConcurrentCopyingVerifyNoFromSpaceRefsVisitor visitor(collector_); 727 visitor(root->AsMirrorPtr()); 728 } 729 730 private: 731 ConcurrentCopying* const collector_; 732}; 733 734class ConcurrentCopyingVerifyNoFromSpaceRefsObjectVisitor { 735 public: 736 explicit ConcurrentCopyingVerifyNoFromSpaceRefsObjectVisitor(ConcurrentCopying* collector) 737 : collector_(collector) {} 738 void operator()(mirror::Object* obj) const 739 SHARED_REQUIRES(Locks::mutator_lock_) { 740 ObjectCallback(obj, collector_); 741 } 742 static void ObjectCallback(mirror::Object* obj, void *arg) 743 SHARED_REQUIRES(Locks::mutator_lock_) { 744 CHECK(obj != nullptr); 745 ConcurrentCopying* collector = reinterpret_cast<ConcurrentCopying*>(arg); 746 space::RegionSpace* region_space = collector->RegionSpace(); 747 CHECK(!region_space->IsInFromSpace(obj)) << "Scanning object " << obj << " in from space"; 748 ConcurrentCopyingVerifyNoFromSpaceRefsFieldVisitor visitor(collector); 749 obj->VisitReferences(visitor, visitor); 750 if (kUseBakerReadBarrier) { 751 if (collector->RegionSpace()->IsInToSpace(obj)) { 752 CHECK(obj->GetReadBarrierPointer() == nullptr) 753 << "obj=" << obj << " non-white rb_ptr " << obj->GetReadBarrierPointer(); 754 } else { 755 CHECK(obj->GetReadBarrierPointer() == ReadBarrier::BlackPtr() || 756 (obj->GetReadBarrierPointer() == ReadBarrier::WhitePtr() && 757 collector->IsOnAllocStack(obj))) 758 << "Non-moving space/unevac from space ref " << obj << " " << PrettyTypeOf(obj) 759 << " has non-black rb_ptr " << obj->GetReadBarrierPointer() 760 << " but isn't on the alloc stack (and has white rb_ptr). Is it in the non-moving space=" 761 << (collector->GetHeap()->GetNonMovingSpace()->HasAddress(obj)); 762 } 763 } 764 } 765 766 private: 767 ConcurrentCopying* const collector_; 768}; 769 770// Verify there's no from-space references left after the marking phase. 771void ConcurrentCopying::VerifyNoFromSpaceReferences() { 772 Thread* self = Thread::Current(); 773 DCHECK(Locks::mutator_lock_->IsExclusiveHeld(self)); 774 // Verify all threads have is_gc_marking to be false 775 { 776 MutexLock mu(self, *Locks::thread_list_lock_); 777 std::list<Thread*> thread_list = Runtime::Current()->GetThreadList()->GetList(); 778 for (Thread* thread : thread_list) { 779 CHECK(!thread->GetIsGcMarking()); 780 } 781 } 782 ConcurrentCopyingVerifyNoFromSpaceRefsObjectVisitor visitor(this); 783 // Roots. 784 { 785 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_); 786 ConcurrentCopyingVerifyNoFromSpaceRefsVisitor ref_visitor(this); 787 Runtime::Current()->VisitRoots(&ref_visitor); 788 } 789 // The to-space. 790 region_space_->WalkToSpace(ConcurrentCopyingVerifyNoFromSpaceRefsObjectVisitor::ObjectCallback, 791 this); 792 // Non-moving spaces. 793 { 794 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_); 795 heap_->GetMarkBitmap()->Visit(visitor); 796 } 797 // The alloc stack. 798 { 799 ConcurrentCopyingVerifyNoFromSpaceRefsVisitor ref_visitor(this); 800 for (auto* it = heap_->allocation_stack_->Begin(), *end = heap_->allocation_stack_->End(); 801 it < end; ++it) { 802 mirror::Object* const obj = it->AsMirrorPtr(); 803 if (obj != nullptr && obj->GetClass() != nullptr) { 804 // TODO: need to call this only if obj is alive? 805 ref_visitor(obj); 806 visitor(obj); 807 } 808 } 809 } 810 // TODO: LOS. But only refs in LOS are classes. 811} 812 813// The following visitors are used to assert the to-space invariant. 814class ConcurrentCopyingAssertToSpaceInvariantRefsVisitor { 815 public: 816 explicit ConcurrentCopyingAssertToSpaceInvariantRefsVisitor(ConcurrentCopying* collector) 817 : collector_(collector) {} 818 819 void operator()(mirror::Object* ref) const 820 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE { 821 if (ref == nullptr) { 822 // OK. 823 return; 824 } 825 collector_->AssertToSpaceInvariant(nullptr, MemberOffset(0), ref); 826 } 827 828 private: 829 ConcurrentCopying* const collector_; 830}; 831 832class ConcurrentCopyingAssertToSpaceInvariantFieldVisitor { 833 public: 834 explicit ConcurrentCopyingAssertToSpaceInvariantFieldVisitor(ConcurrentCopying* collector) 835 : collector_(collector) {} 836 837 void operator()(mirror::Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const 838 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE { 839 mirror::Object* ref = 840 obj->GetFieldObject<mirror::Object, kDefaultVerifyFlags, kWithoutReadBarrier>(offset); 841 ConcurrentCopyingAssertToSpaceInvariantRefsVisitor visitor(collector_); 842 visitor(ref); 843 } 844 void operator()(mirror::Class* klass, mirror::Reference* ref ATTRIBUTE_UNUSED) const 845 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE { 846 CHECK(klass->IsTypeOfReferenceClass()); 847 } 848 849 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const 850 SHARED_REQUIRES(Locks::mutator_lock_) { 851 if (!root->IsNull()) { 852 VisitRoot(root); 853 } 854 } 855 856 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const 857 SHARED_REQUIRES(Locks::mutator_lock_) { 858 ConcurrentCopyingAssertToSpaceInvariantRefsVisitor visitor(collector_); 859 visitor(root->AsMirrorPtr()); 860 } 861 862 private: 863 ConcurrentCopying* const collector_; 864}; 865 866class ConcurrentCopyingAssertToSpaceInvariantObjectVisitor { 867 public: 868 explicit ConcurrentCopyingAssertToSpaceInvariantObjectVisitor(ConcurrentCopying* collector) 869 : collector_(collector) {} 870 void operator()(mirror::Object* obj) const 871 SHARED_REQUIRES(Locks::mutator_lock_) { 872 ObjectCallback(obj, collector_); 873 } 874 static void ObjectCallback(mirror::Object* obj, void *arg) 875 SHARED_REQUIRES(Locks::mutator_lock_) { 876 CHECK(obj != nullptr); 877 ConcurrentCopying* collector = reinterpret_cast<ConcurrentCopying*>(arg); 878 space::RegionSpace* region_space = collector->RegionSpace(); 879 CHECK(!region_space->IsInFromSpace(obj)) << "Scanning object " << obj << " in from space"; 880 collector->AssertToSpaceInvariant(nullptr, MemberOffset(0), obj); 881 ConcurrentCopyingAssertToSpaceInvariantFieldVisitor visitor(collector); 882 obj->VisitReferences(visitor, visitor); 883 } 884 885 private: 886 ConcurrentCopying* const collector_; 887}; 888 889class RevokeThreadLocalMarkStackCheckpoint : public Closure { 890 public: 891 RevokeThreadLocalMarkStackCheckpoint(ConcurrentCopying* concurrent_copying, 892 bool disable_weak_ref_access) 893 : concurrent_copying_(concurrent_copying), 894 disable_weak_ref_access_(disable_weak_ref_access) { 895 } 896 897 virtual void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS { 898 // Note: self is not necessarily equal to thread since thread may be suspended. 899 Thread* self = Thread::Current(); 900 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc) 901 << thread->GetState() << " thread " << thread << " self " << self; 902 // Revoke thread local mark stacks. 903 accounting::AtomicStack<mirror::Object>* tl_mark_stack = thread->GetThreadLocalMarkStack(); 904 if (tl_mark_stack != nullptr) { 905 MutexLock mu(self, concurrent_copying_->mark_stack_lock_); 906 concurrent_copying_->revoked_mark_stacks_.push_back(tl_mark_stack); 907 thread->SetThreadLocalMarkStack(nullptr); 908 } 909 // Disable weak ref access. 910 if (disable_weak_ref_access_) { 911 thread->SetWeakRefAccessEnabled(false); 912 } 913 // If thread is a running mutator, then act on behalf of the garbage collector. 914 // See the code in ThreadList::RunCheckpoint. 915 concurrent_copying_->GetBarrier().Pass(self); 916 } 917 918 private: 919 ConcurrentCopying* const concurrent_copying_; 920 const bool disable_weak_ref_access_; 921}; 922 923void ConcurrentCopying::RevokeThreadLocalMarkStacks(bool disable_weak_ref_access) { 924 Thread* self = Thread::Current(); 925 RevokeThreadLocalMarkStackCheckpoint check_point(this, disable_weak_ref_access); 926 ThreadList* thread_list = Runtime::Current()->GetThreadList(); 927 gc_barrier_->Init(self, 0); 928 size_t barrier_count = thread_list->RunCheckpoint(&check_point); 929 // If there are no threads to wait which implys that all the checkpoint functions are finished, 930 // then no need to release the mutator lock. 931 if (barrier_count == 0) { 932 return; 933 } 934 Locks::mutator_lock_->SharedUnlock(self); 935 { 936 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun); 937 gc_barrier_->Increment(self, barrier_count); 938 } 939 Locks::mutator_lock_->SharedLock(self); 940} 941 942void ConcurrentCopying::RevokeThreadLocalMarkStack(Thread* thread) { 943 Thread* self = Thread::Current(); 944 CHECK_EQ(self, thread); 945 accounting::AtomicStack<mirror::Object>* tl_mark_stack = thread->GetThreadLocalMarkStack(); 946 if (tl_mark_stack != nullptr) { 947 CHECK(is_marking_); 948 MutexLock mu(self, mark_stack_lock_); 949 revoked_mark_stacks_.push_back(tl_mark_stack); 950 thread->SetThreadLocalMarkStack(nullptr); 951 } 952} 953 954void ConcurrentCopying::ProcessMarkStack() { 955 if (kVerboseMode) { 956 LOG(INFO) << "ProcessMarkStack. "; 957 } 958 bool empty_prev = false; 959 while (true) { 960 bool empty = ProcessMarkStackOnce(); 961 if (empty_prev && empty) { 962 // Saw empty mark stack for a second time, done. 963 break; 964 } 965 empty_prev = empty; 966 } 967} 968 969bool ConcurrentCopying::ProcessMarkStackOnce() { 970 Thread* self = Thread::Current(); 971 CHECK(thread_running_gc_ != nullptr); 972 CHECK(self == thread_running_gc_); 973 CHECK(self->GetThreadLocalMarkStack() == nullptr); 974 size_t count = 0; 975 MarkStackMode mark_stack_mode = mark_stack_mode_.LoadRelaxed(); 976 if (mark_stack_mode == kMarkStackModeThreadLocal) { 977 // Process the thread-local mark stacks and the GC mark stack. 978 count += ProcessThreadLocalMarkStacks(false); 979 while (!gc_mark_stack_->IsEmpty()) { 980 mirror::Object* to_ref = gc_mark_stack_->PopBack(); 981 ProcessMarkStackRef(to_ref); 982 ++count; 983 } 984 gc_mark_stack_->Reset(); 985 } else if (mark_stack_mode == kMarkStackModeShared) { 986 // Process the shared GC mark stack with a lock. 987 { 988 MutexLock mu(self, mark_stack_lock_); 989 CHECK(revoked_mark_stacks_.empty()); 990 } 991 while (true) { 992 std::vector<mirror::Object*> refs; 993 { 994 // Copy refs with lock. Note the number of refs should be small. 995 MutexLock mu(self, mark_stack_lock_); 996 if (gc_mark_stack_->IsEmpty()) { 997 break; 998 } 999 for (StackReference<mirror::Object>* p = gc_mark_stack_->Begin(); 1000 p != gc_mark_stack_->End(); ++p) { 1001 refs.push_back(p->AsMirrorPtr()); 1002 } 1003 gc_mark_stack_->Reset(); 1004 } 1005 for (mirror::Object* ref : refs) { 1006 ProcessMarkStackRef(ref); 1007 ++count; 1008 } 1009 } 1010 } else { 1011 CHECK_EQ(static_cast<uint32_t>(mark_stack_mode), 1012 static_cast<uint32_t>(kMarkStackModeGcExclusive)); 1013 { 1014 MutexLock mu(self, mark_stack_lock_); 1015 CHECK(revoked_mark_stacks_.empty()); 1016 } 1017 // Process the GC mark stack in the exclusive mode. No need to take the lock. 1018 while (!gc_mark_stack_->IsEmpty()) { 1019 mirror::Object* to_ref = gc_mark_stack_->PopBack(); 1020 ProcessMarkStackRef(to_ref); 1021 ++count; 1022 } 1023 gc_mark_stack_->Reset(); 1024 } 1025 1026 // Return true if the stack was empty. 1027 return count == 0; 1028} 1029 1030size_t ConcurrentCopying::ProcessThreadLocalMarkStacks(bool disable_weak_ref_access) { 1031 // Run a checkpoint to collect all thread local mark stacks and iterate over them all. 1032 RevokeThreadLocalMarkStacks(disable_weak_ref_access); 1033 size_t count = 0; 1034 std::vector<accounting::AtomicStack<mirror::Object>*> mark_stacks; 1035 { 1036 MutexLock mu(Thread::Current(), mark_stack_lock_); 1037 // Make a copy of the mark stack vector. 1038 mark_stacks = revoked_mark_stacks_; 1039 revoked_mark_stacks_.clear(); 1040 } 1041 for (accounting::AtomicStack<mirror::Object>* mark_stack : mark_stacks) { 1042 for (StackReference<mirror::Object>* p = mark_stack->Begin(); p != mark_stack->End(); ++p) { 1043 mirror::Object* to_ref = p->AsMirrorPtr(); 1044 ProcessMarkStackRef(to_ref); 1045 ++count; 1046 } 1047 { 1048 MutexLock mu(Thread::Current(), mark_stack_lock_); 1049 if (pooled_mark_stacks_.size() >= kMarkStackPoolSize) { 1050 // The pool has enough. Delete it. 1051 delete mark_stack; 1052 } else { 1053 // Otherwise, put it into the pool for later reuse. 1054 mark_stack->Reset(); 1055 pooled_mark_stacks_.push_back(mark_stack); 1056 } 1057 } 1058 } 1059 return count; 1060} 1061 1062inline void ConcurrentCopying::ProcessMarkStackRef(mirror::Object* to_ref) { 1063 DCHECK(!region_space_->IsInFromSpace(to_ref)); 1064 if (kUseBakerReadBarrier) { 1065 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr()) 1066 << " " << to_ref << " " << to_ref->GetReadBarrierPointer() 1067 << " is_marked=" << IsMarked(to_ref); 1068 } 1069 // Scan ref fields. 1070 Scan(to_ref); 1071 // Mark the gray ref as white or black. 1072 if (kUseBakerReadBarrier) { 1073 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr()) 1074 << " " << to_ref << " " << to_ref->GetReadBarrierPointer() 1075 << " is_marked=" << IsMarked(to_ref); 1076 } 1077#ifdef USE_BAKER_OR_BROOKS_READ_BARRIER 1078 if (UNLIKELY((to_ref->GetClass<kVerifyNone, kWithoutReadBarrier>()->IsTypeOfReferenceClass() && 1079 to_ref->AsReference()->GetReferent<kWithoutReadBarrier>() != nullptr && 1080 !IsInToSpace(to_ref->AsReference()->GetReferent<kWithoutReadBarrier>())))) { 1081 // Leave this Reference gray in the queue so that GetReferent() will trigger a read barrier. We 1082 // will change it to black or white later in ReferenceQueue::DequeuePendingReference(). 1083 CHECK(to_ref->AsReference()->IsEnqueued()) << "Left unenqueued ref gray " << to_ref; 1084 } else { 1085 // We may occasionally leave a Reference black or white in the queue if its referent happens to 1086 // be concurrently marked after the Scan() call above has enqueued the Reference, in which case 1087 // the above IsInToSpace() evaluates to true and we change the color from gray to black or white 1088 // here in this else block. 1089 if (kUseBakerReadBarrier) { 1090 if (region_space_->IsInToSpace(to_ref)) { 1091 // If to-space, change from gray to white. 1092 bool success = to_ref->AtomicSetReadBarrierPointer(ReadBarrier::GrayPtr(), 1093 ReadBarrier::WhitePtr()); 1094 CHECK(success) << "Must succeed as we won the race."; 1095 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::WhitePtr()); 1096 } else { 1097 // If non-moving space/unevac from space, change from gray 1098 // to black. We can't change gray to white because it's not 1099 // safe to use CAS if two threads change values in opposite 1100 // directions (A->B and B->A). So, we change it to black to 1101 // indicate non-moving objects that have been marked 1102 // through. Note we'd need to change from black to white 1103 // later (concurrently). 1104 bool success = to_ref->AtomicSetReadBarrierPointer(ReadBarrier::GrayPtr(), 1105 ReadBarrier::BlackPtr()); 1106 CHECK(success) << "Must succeed as we won the race."; 1107 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::BlackPtr()); 1108 } 1109 } 1110 } 1111#else 1112 DCHECK(!kUseBakerReadBarrier); 1113#endif 1114 if (ReadBarrier::kEnableToSpaceInvariantChecks || kIsDebugBuild) { 1115 ConcurrentCopyingAssertToSpaceInvariantObjectVisitor visitor(this); 1116 visitor(to_ref); 1117 } 1118} 1119 1120void ConcurrentCopying::SwitchToSharedMarkStackMode() { 1121 Thread* self = Thread::Current(); 1122 CHECK(thread_running_gc_ != nullptr); 1123 CHECK_EQ(self, thread_running_gc_); 1124 CHECK(self->GetThreadLocalMarkStack() == nullptr); 1125 MarkStackMode before_mark_stack_mode = mark_stack_mode_.LoadRelaxed(); 1126 CHECK_EQ(static_cast<uint32_t>(before_mark_stack_mode), 1127 static_cast<uint32_t>(kMarkStackModeThreadLocal)); 1128 mark_stack_mode_.StoreRelaxed(kMarkStackModeShared); 1129 CHECK(weak_ref_access_enabled_.LoadRelaxed()); 1130 weak_ref_access_enabled_.StoreRelaxed(false); 1131 QuasiAtomic::ThreadFenceForConstructor(); 1132 // Process the thread local mark stacks one last time after switching to the shared mark stack 1133 // mode and disable weak ref accesses. 1134 ProcessThreadLocalMarkStacks(true); 1135 if (kVerboseMode) { 1136 LOG(INFO) << "Switched to shared mark stack mode and disabled weak ref access"; 1137 } 1138} 1139 1140void ConcurrentCopying::SwitchToGcExclusiveMarkStackMode() { 1141 Thread* self = Thread::Current(); 1142 CHECK(thread_running_gc_ != nullptr); 1143 CHECK_EQ(self, thread_running_gc_); 1144 CHECK(self->GetThreadLocalMarkStack() == nullptr); 1145 MarkStackMode before_mark_stack_mode = mark_stack_mode_.LoadRelaxed(); 1146 CHECK_EQ(static_cast<uint32_t>(before_mark_stack_mode), 1147 static_cast<uint32_t>(kMarkStackModeShared)); 1148 mark_stack_mode_.StoreRelaxed(kMarkStackModeGcExclusive); 1149 QuasiAtomic::ThreadFenceForConstructor(); 1150 if (kVerboseMode) { 1151 LOG(INFO) << "Switched to GC exclusive mark stack mode"; 1152 } 1153} 1154 1155void ConcurrentCopying::CheckEmptyMarkStack() { 1156 Thread* self = Thread::Current(); 1157 CHECK(thread_running_gc_ != nullptr); 1158 CHECK_EQ(self, thread_running_gc_); 1159 CHECK(self->GetThreadLocalMarkStack() == nullptr); 1160 MarkStackMode mark_stack_mode = mark_stack_mode_.LoadRelaxed(); 1161 if (mark_stack_mode == kMarkStackModeThreadLocal) { 1162 // Thread-local mark stack mode. 1163 RevokeThreadLocalMarkStacks(false); 1164 MutexLock mu(Thread::Current(), mark_stack_lock_); 1165 if (!revoked_mark_stacks_.empty()) { 1166 for (accounting::AtomicStack<mirror::Object>* mark_stack : revoked_mark_stacks_) { 1167 while (!mark_stack->IsEmpty()) { 1168 mirror::Object* obj = mark_stack->PopBack(); 1169 if (kUseBakerReadBarrier) { 1170 mirror::Object* rb_ptr = obj->GetReadBarrierPointer(); 1171 LOG(INFO) << "On mark queue : " << obj << " " << PrettyTypeOf(obj) << " rb_ptr=" << rb_ptr 1172 << " is_marked=" << IsMarked(obj); 1173 } else { 1174 LOG(INFO) << "On mark queue : " << obj << " " << PrettyTypeOf(obj) 1175 << " is_marked=" << IsMarked(obj); 1176 } 1177 } 1178 } 1179 LOG(FATAL) << "mark stack is not empty"; 1180 } 1181 } else { 1182 // Shared, GC-exclusive, or off. 1183 MutexLock mu(Thread::Current(), mark_stack_lock_); 1184 CHECK(gc_mark_stack_->IsEmpty()); 1185 CHECK(revoked_mark_stacks_.empty()); 1186 } 1187} 1188 1189void ConcurrentCopying::SweepSystemWeaks(Thread* self) { 1190 TimingLogger::ScopedTiming split("SweepSystemWeaks", GetTimings()); 1191 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_); 1192 Runtime::Current()->SweepSystemWeaks(this); 1193} 1194 1195void ConcurrentCopying::Sweep(bool swap_bitmaps) { 1196 { 1197 TimingLogger::ScopedTiming t("MarkStackAsLive", GetTimings()); 1198 accounting::ObjectStack* live_stack = heap_->GetLiveStack(); 1199 if (kEnableFromSpaceAccountingCheck) { 1200 CHECK_GE(live_stack_freeze_size_, live_stack->Size()); 1201 } 1202 heap_->MarkAllocStackAsLive(live_stack); 1203 live_stack->Reset(); 1204 } 1205 CheckEmptyMarkStack(); 1206 TimingLogger::ScopedTiming split("Sweep", GetTimings()); 1207 for (const auto& space : GetHeap()->GetContinuousSpaces()) { 1208 if (space->IsContinuousMemMapAllocSpace()) { 1209 space::ContinuousMemMapAllocSpace* alloc_space = space->AsContinuousMemMapAllocSpace(); 1210 if (space == region_space_ || immune_spaces_.ContainsSpace(space)) { 1211 continue; 1212 } 1213 TimingLogger::ScopedTiming split2( 1214 alloc_space->IsZygoteSpace() ? "SweepZygoteSpace" : "SweepAllocSpace", GetTimings()); 1215 RecordFree(alloc_space->Sweep(swap_bitmaps)); 1216 } 1217 } 1218 SweepLargeObjects(swap_bitmaps); 1219} 1220 1221void ConcurrentCopying::SweepLargeObjects(bool swap_bitmaps) { 1222 TimingLogger::ScopedTiming split("SweepLargeObjects", GetTimings()); 1223 RecordFreeLOS(heap_->GetLargeObjectsSpace()->Sweep(swap_bitmaps)); 1224} 1225 1226class ConcurrentCopyingClearBlackPtrsVisitor { 1227 public: 1228 explicit ConcurrentCopyingClearBlackPtrsVisitor(ConcurrentCopying* cc) 1229 : collector_(cc) {} 1230#ifndef USE_BAKER_OR_BROOKS_READ_BARRIER 1231 NO_RETURN 1232#endif 1233 void operator()(mirror::Object* obj) const SHARED_REQUIRES(Locks::mutator_lock_) 1234 SHARED_REQUIRES(Locks::heap_bitmap_lock_) { 1235 DCHECK(obj != nullptr); 1236 DCHECK(collector_->heap_->GetMarkBitmap()->Test(obj)) << obj; 1237 DCHECK_EQ(obj->GetReadBarrierPointer(), ReadBarrier::BlackPtr()) << obj; 1238 obj->AtomicSetReadBarrierPointer(ReadBarrier::BlackPtr(), ReadBarrier::WhitePtr()); 1239 DCHECK_EQ(obj->GetReadBarrierPointer(), ReadBarrier::WhitePtr()) << obj; 1240 } 1241 1242 private: 1243 ConcurrentCopying* const collector_; 1244}; 1245 1246// Clear the black ptrs in non-moving objects back to white. 1247void ConcurrentCopying::ClearBlackPtrs() { 1248 CHECK(kUseBakerReadBarrier); 1249 TimingLogger::ScopedTiming split("ClearBlackPtrs", GetTimings()); 1250 ConcurrentCopyingClearBlackPtrsVisitor visitor(this); 1251 for (auto& space : heap_->GetContinuousSpaces()) { 1252 if (space == region_space_) { 1253 continue; 1254 } 1255 accounting::ContinuousSpaceBitmap* mark_bitmap = space->GetMarkBitmap(); 1256 if (kVerboseMode) { 1257 LOG(INFO) << "ClearBlackPtrs: " << *space << " bitmap: " << *mark_bitmap; 1258 } 1259 mark_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()), 1260 reinterpret_cast<uintptr_t>(space->Limit()), 1261 visitor); 1262 } 1263 space::LargeObjectSpace* large_object_space = heap_->GetLargeObjectsSpace(); 1264 large_object_space->GetMarkBitmap()->VisitMarkedRange( 1265 reinterpret_cast<uintptr_t>(large_object_space->Begin()), 1266 reinterpret_cast<uintptr_t>(large_object_space->End()), 1267 visitor); 1268 // Objects on the allocation stack? 1269 if (ReadBarrier::kEnableReadBarrierInvariantChecks || kIsDebugBuild) { 1270 size_t count = GetAllocationStack()->Size(); 1271 auto* it = GetAllocationStack()->Begin(); 1272 auto* end = GetAllocationStack()->End(); 1273 for (size_t i = 0; i < count; ++i, ++it) { 1274 CHECK_LT(it, end); 1275 mirror::Object* obj = it->AsMirrorPtr(); 1276 if (obj != nullptr) { 1277 // Must have been cleared above. 1278 CHECK_EQ(obj->GetReadBarrierPointer(), ReadBarrier::WhitePtr()) << obj; 1279 } 1280 } 1281 } 1282} 1283 1284void ConcurrentCopying::ReclaimPhase() { 1285 TimingLogger::ScopedTiming split("ReclaimPhase", GetTimings()); 1286 if (kVerboseMode) { 1287 LOG(INFO) << "GC ReclaimPhase"; 1288 } 1289 Thread* self = Thread::Current(); 1290 1291 { 1292 // Double-check that the mark stack is empty. 1293 // Note: need to set this after VerifyNoFromSpaceRef(). 1294 is_asserting_to_space_invariant_ = false; 1295 QuasiAtomic::ThreadFenceForConstructor(); 1296 if (kVerboseMode) { 1297 LOG(INFO) << "Issue an empty check point. "; 1298 } 1299 IssueEmptyCheckpoint(); 1300 // Disable the check. 1301 is_mark_stack_push_disallowed_.StoreSequentiallyConsistent(0); 1302 CheckEmptyMarkStack(); 1303 } 1304 1305 { 1306 // Record freed objects. 1307 TimingLogger::ScopedTiming split2("RecordFree", GetTimings()); 1308 // Don't include thread-locals that are in the to-space. 1309 uint64_t from_bytes = region_space_->GetBytesAllocatedInFromSpace(); 1310 uint64_t from_objects = region_space_->GetObjectsAllocatedInFromSpace(); 1311 uint64_t unevac_from_bytes = region_space_->GetBytesAllocatedInUnevacFromSpace(); 1312 uint64_t unevac_from_objects = region_space_->GetObjectsAllocatedInUnevacFromSpace(); 1313 uint64_t to_bytes = bytes_moved_.LoadSequentiallyConsistent(); 1314 uint64_t to_objects = objects_moved_.LoadSequentiallyConsistent(); 1315 if (kEnableFromSpaceAccountingCheck) { 1316 CHECK_EQ(from_space_num_objects_at_first_pause_, from_objects + unevac_from_objects); 1317 CHECK_EQ(from_space_num_bytes_at_first_pause_, from_bytes + unevac_from_bytes); 1318 } 1319 CHECK_LE(to_objects, from_objects); 1320 CHECK_LE(to_bytes, from_bytes); 1321 int64_t freed_bytes = from_bytes - to_bytes; 1322 int64_t freed_objects = from_objects - to_objects; 1323 if (kVerboseMode) { 1324 LOG(INFO) << "RecordFree:" 1325 << " from_bytes=" << from_bytes << " from_objects=" << from_objects 1326 << " unevac_from_bytes=" << unevac_from_bytes << " unevac_from_objects=" << unevac_from_objects 1327 << " to_bytes=" << to_bytes << " to_objects=" << to_objects 1328 << " freed_bytes=" << freed_bytes << " freed_objects=" << freed_objects 1329 << " from_space size=" << region_space_->FromSpaceSize() 1330 << " unevac_from_space size=" << region_space_->UnevacFromSpaceSize() 1331 << " to_space size=" << region_space_->ToSpaceSize(); 1332 LOG(INFO) << "(before) num_bytes_allocated=" << heap_->num_bytes_allocated_.LoadSequentiallyConsistent(); 1333 } 1334 RecordFree(ObjectBytePair(freed_objects, freed_bytes)); 1335 if (kVerboseMode) { 1336 LOG(INFO) << "(after) num_bytes_allocated=" << heap_->num_bytes_allocated_.LoadSequentiallyConsistent(); 1337 } 1338 } 1339 1340 { 1341 TimingLogger::ScopedTiming split3("ComputeUnevacFromSpaceLiveRatio", GetTimings()); 1342 ComputeUnevacFromSpaceLiveRatio(); 1343 } 1344 1345 { 1346 TimingLogger::ScopedTiming split4("ClearFromSpace", GetTimings()); 1347 region_space_->ClearFromSpace(); 1348 } 1349 1350 { 1351 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_); 1352 if (kUseBakerReadBarrier) { 1353 ClearBlackPtrs(); 1354 } 1355 Sweep(false); 1356 SwapBitmaps(); 1357 heap_->UnBindBitmaps(); 1358 1359 // Remove bitmaps for the immune spaces. 1360 while (!cc_bitmaps_.empty()) { 1361 accounting::ContinuousSpaceBitmap* cc_bitmap = cc_bitmaps_.back(); 1362 cc_heap_bitmap_->RemoveContinuousSpaceBitmap(cc_bitmap); 1363 delete cc_bitmap; 1364 cc_bitmaps_.pop_back(); 1365 } 1366 region_space_bitmap_ = nullptr; 1367 } 1368 1369 CheckEmptyMarkStack(); 1370 1371 if (kVerboseMode) { 1372 LOG(INFO) << "GC end of ReclaimPhase"; 1373 } 1374} 1375 1376class ConcurrentCopyingComputeUnevacFromSpaceLiveRatioVisitor { 1377 public: 1378 explicit ConcurrentCopyingComputeUnevacFromSpaceLiveRatioVisitor(ConcurrentCopying* cc) 1379 : collector_(cc) {} 1380 void operator()(mirror::Object* ref) const SHARED_REQUIRES(Locks::mutator_lock_) 1381 SHARED_REQUIRES(Locks::heap_bitmap_lock_) { 1382 DCHECK(ref != nullptr); 1383 DCHECK(collector_->region_space_bitmap_->Test(ref)) << ref; 1384 DCHECK(collector_->region_space_->IsInUnevacFromSpace(ref)) << ref; 1385 if (kUseBakerReadBarrier) { 1386 DCHECK_EQ(ref->GetReadBarrierPointer(), ReadBarrier::BlackPtr()) << ref; 1387 // Clear the black ptr. 1388 ref->AtomicSetReadBarrierPointer(ReadBarrier::BlackPtr(), ReadBarrier::WhitePtr()); 1389 DCHECK_EQ(ref->GetReadBarrierPointer(), ReadBarrier::WhitePtr()) << ref; 1390 } 1391 size_t obj_size = ref->SizeOf(); 1392 size_t alloc_size = RoundUp(obj_size, space::RegionSpace::kAlignment); 1393 collector_->region_space_->AddLiveBytes(ref, alloc_size); 1394 } 1395 1396 private: 1397 ConcurrentCopying* const collector_; 1398}; 1399 1400// Compute how much live objects are left in regions. 1401void ConcurrentCopying::ComputeUnevacFromSpaceLiveRatio() { 1402 region_space_->AssertAllRegionLiveBytesZeroOrCleared(); 1403 ConcurrentCopyingComputeUnevacFromSpaceLiveRatioVisitor visitor(this); 1404 region_space_bitmap_->VisitMarkedRange(reinterpret_cast<uintptr_t>(region_space_->Begin()), 1405 reinterpret_cast<uintptr_t>(region_space_->Limit()), 1406 visitor); 1407} 1408 1409// Assert the to-space invariant. 1410void ConcurrentCopying::AssertToSpaceInvariant(mirror::Object* obj, MemberOffset offset, 1411 mirror::Object* ref) { 1412 CHECK(heap_->collector_type_ == kCollectorTypeCC) << static_cast<size_t>(heap_->collector_type_); 1413 if (is_asserting_to_space_invariant_) { 1414 if (region_space_->IsInToSpace(ref)) { 1415 // OK. 1416 return; 1417 } else if (region_space_->IsInUnevacFromSpace(ref)) { 1418 CHECK(region_space_bitmap_->Test(ref)) << ref; 1419 } else if (region_space_->IsInFromSpace(ref)) { 1420 // Not OK. Do extra logging. 1421 if (obj != nullptr) { 1422 LogFromSpaceRefHolder(obj, offset); 1423 } 1424 ref->GetLockWord(false).Dump(LOG(INTERNAL_FATAL)); 1425 CHECK(false) << "Found from-space ref " << ref << " " << PrettyTypeOf(ref); 1426 } else { 1427 AssertToSpaceInvariantInNonMovingSpace(obj, ref); 1428 } 1429 } 1430} 1431 1432class RootPrinter { 1433 public: 1434 RootPrinter() { } 1435 1436 template <class MirrorType> 1437 ALWAYS_INLINE void VisitRootIfNonNull(mirror::CompressedReference<MirrorType>* root) 1438 SHARED_REQUIRES(Locks::mutator_lock_) { 1439 if (!root->IsNull()) { 1440 VisitRoot(root); 1441 } 1442 } 1443 1444 template <class MirrorType> 1445 void VisitRoot(mirror::Object** root) 1446 SHARED_REQUIRES(Locks::mutator_lock_) { 1447 LOG(INTERNAL_FATAL) << "root=" << root << " ref=" << *root; 1448 } 1449 1450 template <class MirrorType> 1451 void VisitRoot(mirror::CompressedReference<MirrorType>* root) 1452 SHARED_REQUIRES(Locks::mutator_lock_) { 1453 LOG(INTERNAL_FATAL) << "root=" << root << " ref=" << root->AsMirrorPtr(); 1454 } 1455}; 1456 1457void ConcurrentCopying::AssertToSpaceInvariant(GcRootSource* gc_root_source, 1458 mirror::Object* ref) { 1459 CHECK(heap_->collector_type_ == kCollectorTypeCC) << static_cast<size_t>(heap_->collector_type_); 1460 if (is_asserting_to_space_invariant_) { 1461 if (region_space_->IsInToSpace(ref)) { 1462 // OK. 1463 return; 1464 } else if (region_space_->IsInUnevacFromSpace(ref)) { 1465 CHECK(region_space_bitmap_->Test(ref)) << ref; 1466 } else if (region_space_->IsInFromSpace(ref)) { 1467 // Not OK. Do extra logging. 1468 if (gc_root_source == nullptr) { 1469 // No info. 1470 } else if (gc_root_source->HasArtField()) { 1471 ArtField* field = gc_root_source->GetArtField(); 1472 LOG(INTERNAL_FATAL) << "gc root in field " << field << " " << PrettyField(field); 1473 RootPrinter root_printer; 1474 field->VisitRoots(root_printer); 1475 } else if (gc_root_source->HasArtMethod()) { 1476 ArtMethod* method = gc_root_source->GetArtMethod(); 1477 LOG(INTERNAL_FATAL) << "gc root in method " << method << " " << PrettyMethod(method); 1478 RootPrinter root_printer; 1479 method->VisitRoots(root_printer, sizeof(void*)); 1480 } 1481 ref->GetLockWord(false).Dump(LOG(INTERNAL_FATAL)); 1482 region_space_->DumpNonFreeRegions(LOG(INTERNAL_FATAL)); 1483 PrintFileToLog("/proc/self/maps", LogSeverity::INTERNAL_FATAL); 1484 MemMap::DumpMaps(LOG(INTERNAL_FATAL), true); 1485 CHECK(false) << "Found from-space ref " << ref << " " << PrettyTypeOf(ref); 1486 } else { 1487 AssertToSpaceInvariantInNonMovingSpace(nullptr, ref); 1488 } 1489 } 1490} 1491 1492void ConcurrentCopying::LogFromSpaceRefHolder(mirror::Object* obj, MemberOffset offset) { 1493 if (kUseBakerReadBarrier) { 1494 LOG(INFO) << "holder=" << obj << " " << PrettyTypeOf(obj) 1495 << " holder rb_ptr=" << obj->GetReadBarrierPointer(); 1496 } else { 1497 LOG(INFO) << "holder=" << obj << " " << PrettyTypeOf(obj); 1498 } 1499 if (region_space_->IsInFromSpace(obj)) { 1500 LOG(INFO) << "holder is in the from-space."; 1501 } else if (region_space_->IsInToSpace(obj)) { 1502 LOG(INFO) << "holder is in the to-space."; 1503 } else if (region_space_->IsInUnevacFromSpace(obj)) { 1504 LOG(INFO) << "holder is in the unevac from-space."; 1505 if (region_space_bitmap_->Test(obj)) { 1506 LOG(INFO) << "holder is marked in the region space bitmap."; 1507 } else { 1508 LOG(INFO) << "holder is not marked in the region space bitmap."; 1509 } 1510 } else { 1511 // In a non-moving space. 1512 if (immune_spaces_.ContainsObject(obj)) { 1513 LOG(INFO) << "holder is in an immune image or the zygote space."; 1514 accounting::ContinuousSpaceBitmap* cc_bitmap = 1515 cc_heap_bitmap_->GetContinuousSpaceBitmap(obj); 1516 CHECK(cc_bitmap != nullptr) 1517 << "An immune space object must have a bitmap."; 1518 if (cc_bitmap->Test(obj)) { 1519 LOG(INFO) << "holder is marked in the bit map."; 1520 } else { 1521 LOG(INFO) << "holder is NOT marked in the bit map."; 1522 } 1523 } else { 1524 LOG(INFO) << "holder is in a non-immune, non-moving (or main) space."; 1525 accounting::ContinuousSpaceBitmap* mark_bitmap = 1526 heap_mark_bitmap_->GetContinuousSpaceBitmap(obj); 1527 accounting::LargeObjectBitmap* los_bitmap = 1528 heap_mark_bitmap_->GetLargeObjectBitmap(obj); 1529 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range"; 1530 bool is_los = mark_bitmap == nullptr; 1531 if (!is_los && mark_bitmap->Test(obj)) { 1532 LOG(INFO) << "holder is marked in the mark bit map."; 1533 } else if (is_los && los_bitmap->Test(obj)) { 1534 LOG(INFO) << "holder is marked in the los bit map."; 1535 } else { 1536 // If ref is on the allocation stack, then it is considered 1537 // mark/alive (but not necessarily on the live stack.) 1538 if (IsOnAllocStack(obj)) { 1539 LOG(INFO) << "holder is on the alloc stack."; 1540 } else { 1541 LOG(INFO) << "holder is not marked or on the alloc stack."; 1542 } 1543 } 1544 } 1545 } 1546 LOG(INFO) << "offset=" << offset.SizeValue(); 1547} 1548 1549void ConcurrentCopying::AssertToSpaceInvariantInNonMovingSpace(mirror::Object* obj, 1550 mirror::Object* ref) { 1551 // In a non-moving spaces. Check that the ref is marked. 1552 if (immune_spaces_.ContainsObject(ref)) { 1553 accounting::ContinuousSpaceBitmap* cc_bitmap = 1554 cc_heap_bitmap_->GetContinuousSpaceBitmap(ref); 1555 CHECK(cc_bitmap != nullptr) 1556 << "An immune space ref must have a bitmap. " << ref; 1557 if (kUseBakerReadBarrier) { 1558 CHECK(cc_bitmap->Test(ref)) 1559 << "Unmarked immune space ref. obj=" << obj << " rb_ptr=" 1560 << obj->GetReadBarrierPointer() << " ref=" << ref; 1561 } else { 1562 CHECK(cc_bitmap->Test(ref)) 1563 << "Unmarked immune space ref. obj=" << obj << " ref=" << ref; 1564 } 1565 } else { 1566 accounting::ContinuousSpaceBitmap* mark_bitmap = 1567 heap_mark_bitmap_->GetContinuousSpaceBitmap(ref); 1568 accounting::LargeObjectBitmap* los_bitmap = 1569 heap_mark_bitmap_->GetLargeObjectBitmap(ref); 1570 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range"; 1571 bool is_los = mark_bitmap == nullptr; 1572 if ((!is_los && mark_bitmap->Test(ref)) || 1573 (is_los && los_bitmap->Test(ref))) { 1574 // OK. 1575 } else { 1576 // If ref is on the allocation stack, then it may not be 1577 // marked live, but considered marked/alive (but not 1578 // necessarily on the live stack). 1579 CHECK(IsOnAllocStack(ref)) << "Unmarked ref that's not on the allocation stack. " 1580 << "obj=" << obj << " ref=" << ref; 1581 } 1582 } 1583} 1584 1585// Used to scan ref fields of an object. 1586class ConcurrentCopyingRefFieldsVisitor { 1587 public: 1588 explicit ConcurrentCopyingRefFieldsVisitor(ConcurrentCopying* collector) 1589 : collector_(collector) {} 1590 1591 void operator()(mirror::Object* obj, MemberOffset offset, bool /* is_static */) 1592 const ALWAYS_INLINE SHARED_REQUIRES(Locks::mutator_lock_) 1593 SHARED_REQUIRES(Locks::heap_bitmap_lock_) { 1594 collector_->Process(obj, offset); 1595 } 1596 1597 void operator()(mirror::Class* klass, mirror::Reference* ref) const 1598 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE { 1599 CHECK(klass->IsTypeOfReferenceClass()); 1600 collector_->DelayReferenceReferent(klass, ref); 1601 } 1602 1603 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const 1604 ALWAYS_INLINE 1605 SHARED_REQUIRES(Locks::mutator_lock_) { 1606 if (!root->IsNull()) { 1607 VisitRoot(root); 1608 } 1609 } 1610 1611 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const 1612 ALWAYS_INLINE 1613 SHARED_REQUIRES(Locks::mutator_lock_) { 1614 collector_->MarkRoot(root); 1615 } 1616 1617 private: 1618 ConcurrentCopying* const collector_; 1619}; 1620 1621// Scan ref fields of an object. 1622inline void ConcurrentCopying::Scan(mirror::Object* to_ref) { 1623 DCHECK(!region_space_->IsInFromSpace(to_ref)); 1624 ConcurrentCopyingRefFieldsVisitor visitor(this); 1625 to_ref->VisitReferences(visitor, visitor); 1626} 1627 1628// Process a field. 1629inline void ConcurrentCopying::Process(mirror::Object* obj, MemberOffset offset) { 1630 mirror::Object* ref = obj->GetFieldObject< 1631 mirror::Object, kVerifyNone, kWithoutReadBarrier, false>(offset); 1632 mirror::Object* to_ref = Mark(ref); 1633 if (to_ref == ref) { 1634 return; 1635 } 1636 // This may fail if the mutator writes to the field at the same time. But it's ok. 1637 mirror::Object* expected_ref = ref; 1638 mirror::Object* new_ref = to_ref; 1639 do { 1640 if (expected_ref != 1641 obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier, false>(offset)) { 1642 // It was updated by the mutator. 1643 break; 1644 } 1645 } while (!obj->CasFieldWeakRelaxedObjectWithoutWriteBarrier< 1646 false, false, kVerifyNone>(offset, expected_ref, new_ref)); 1647} 1648 1649// Process some roots. 1650inline void ConcurrentCopying::VisitRoots( 1651 mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED) { 1652 for (size_t i = 0; i < count; ++i) { 1653 mirror::Object** root = roots[i]; 1654 mirror::Object* ref = *root; 1655 mirror::Object* to_ref = Mark(ref); 1656 if (to_ref == ref) { 1657 continue; 1658 } 1659 Atomic<mirror::Object*>* addr = reinterpret_cast<Atomic<mirror::Object*>*>(root); 1660 mirror::Object* expected_ref = ref; 1661 mirror::Object* new_ref = to_ref; 1662 do { 1663 if (expected_ref != addr->LoadRelaxed()) { 1664 // It was updated by the mutator. 1665 break; 1666 } 1667 } while (!addr->CompareExchangeWeakRelaxed(expected_ref, new_ref)); 1668 } 1669} 1670 1671inline void ConcurrentCopying::MarkRoot(mirror::CompressedReference<mirror::Object>* root) { 1672 DCHECK(!root->IsNull()); 1673 mirror::Object* const ref = root->AsMirrorPtr(); 1674 mirror::Object* to_ref = Mark(ref); 1675 if (to_ref != ref) { 1676 auto* addr = reinterpret_cast<Atomic<mirror::CompressedReference<mirror::Object>>*>(root); 1677 auto expected_ref = mirror::CompressedReference<mirror::Object>::FromMirrorPtr(ref); 1678 auto new_ref = mirror::CompressedReference<mirror::Object>::FromMirrorPtr(to_ref); 1679 // If the cas fails, then it was updated by the mutator. 1680 do { 1681 if (ref != addr->LoadRelaxed().AsMirrorPtr()) { 1682 // It was updated by the mutator. 1683 break; 1684 } 1685 } while (!addr->CompareExchangeWeakRelaxed(expected_ref, new_ref)); 1686 } 1687} 1688 1689inline void ConcurrentCopying::VisitRoots( 1690 mirror::CompressedReference<mirror::Object>** roots, size_t count, 1691 const RootInfo& info ATTRIBUTE_UNUSED) { 1692 for (size_t i = 0; i < count; ++i) { 1693 mirror::CompressedReference<mirror::Object>* const root = roots[i]; 1694 if (!root->IsNull()) { 1695 MarkRoot(root); 1696 } 1697 } 1698} 1699 1700// Fill the given memory block with a dummy object. Used to fill in a 1701// copy of objects that was lost in race. 1702void ConcurrentCopying::FillWithDummyObject(mirror::Object* dummy_obj, size_t byte_size) { 1703 CHECK_ALIGNED(byte_size, kObjectAlignment); 1704 memset(dummy_obj, 0, byte_size); 1705 mirror::Class* int_array_class = mirror::IntArray::GetArrayClass(); 1706 CHECK(int_array_class != nullptr); 1707 AssertToSpaceInvariant(nullptr, MemberOffset(0), int_array_class); 1708 size_t component_size = int_array_class->GetComponentSize(); 1709 CHECK_EQ(component_size, sizeof(int32_t)); 1710 size_t data_offset = mirror::Array::DataOffset(component_size).SizeValue(); 1711 if (data_offset > byte_size) { 1712 // An int array is too big. Use java.lang.Object. 1713 mirror::Class* java_lang_Object = WellKnownClasses::ToClass(WellKnownClasses::java_lang_Object); 1714 AssertToSpaceInvariant(nullptr, MemberOffset(0), java_lang_Object); 1715 CHECK_EQ(byte_size, java_lang_Object->GetObjectSize()); 1716 dummy_obj->SetClass(java_lang_Object); 1717 CHECK_EQ(byte_size, dummy_obj->SizeOf()); 1718 } else { 1719 // Use an int array. 1720 dummy_obj->SetClass(int_array_class); 1721 CHECK(dummy_obj->IsArrayInstance()); 1722 int32_t length = (byte_size - data_offset) / component_size; 1723 dummy_obj->AsArray()->SetLength(length); 1724 CHECK_EQ(dummy_obj->AsArray()->GetLength(), length) 1725 << "byte_size=" << byte_size << " length=" << length 1726 << " component_size=" << component_size << " data_offset=" << data_offset; 1727 CHECK_EQ(byte_size, dummy_obj->SizeOf()) 1728 << "byte_size=" << byte_size << " length=" << length 1729 << " component_size=" << component_size << " data_offset=" << data_offset; 1730 } 1731} 1732 1733// Reuse the memory blocks that were copy of objects that were lost in race. 1734mirror::Object* ConcurrentCopying::AllocateInSkippedBlock(size_t alloc_size) { 1735 // Try to reuse the blocks that were unused due to CAS failures. 1736 CHECK_ALIGNED(alloc_size, space::RegionSpace::kAlignment); 1737 Thread* self = Thread::Current(); 1738 size_t min_object_size = RoundUp(sizeof(mirror::Object), space::RegionSpace::kAlignment); 1739 MutexLock mu(self, skipped_blocks_lock_); 1740 auto it = skipped_blocks_map_.lower_bound(alloc_size); 1741 if (it == skipped_blocks_map_.end()) { 1742 // Not found. 1743 return nullptr; 1744 } 1745 { 1746 size_t byte_size = it->first; 1747 CHECK_GE(byte_size, alloc_size); 1748 if (byte_size > alloc_size && byte_size - alloc_size < min_object_size) { 1749 // If remainder would be too small for a dummy object, retry with a larger request size. 1750 it = skipped_blocks_map_.lower_bound(alloc_size + min_object_size); 1751 if (it == skipped_blocks_map_.end()) { 1752 // Not found. 1753 return nullptr; 1754 } 1755 CHECK_ALIGNED(it->first - alloc_size, space::RegionSpace::kAlignment); 1756 CHECK_GE(it->first - alloc_size, min_object_size) 1757 << "byte_size=" << byte_size << " it->first=" << it->first << " alloc_size=" << alloc_size; 1758 } 1759 } 1760 // Found a block. 1761 CHECK(it != skipped_blocks_map_.end()); 1762 size_t byte_size = it->first; 1763 uint8_t* addr = it->second; 1764 CHECK_GE(byte_size, alloc_size); 1765 CHECK(region_space_->IsInToSpace(reinterpret_cast<mirror::Object*>(addr))); 1766 CHECK_ALIGNED(byte_size, space::RegionSpace::kAlignment); 1767 if (kVerboseMode) { 1768 LOG(INFO) << "Reusing skipped bytes : " << reinterpret_cast<void*>(addr) << ", " << byte_size; 1769 } 1770 skipped_blocks_map_.erase(it); 1771 memset(addr, 0, byte_size); 1772 if (byte_size > alloc_size) { 1773 // Return the remainder to the map. 1774 CHECK_ALIGNED(byte_size - alloc_size, space::RegionSpace::kAlignment); 1775 CHECK_GE(byte_size - alloc_size, min_object_size); 1776 FillWithDummyObject(reinterpret_cast<mirror::Object*>(addr + alloc_size), 1777 byte_size - alloc_size); 1778 CHECK(region_space_->IsInToSpace(reinterpret_cast<mirror::Object*>(addr + alloc_size))); 1779 skipped_blocks_map_.insert(std::make_pair(byte_size - alloc_size, addr + alloc_size)); 1780 } 1781 return reinterpret_cast<mirror::Object*>(addr); 1782} 1783 1784mirror::Object* ConcurrentCopying::Copy(mirror::Object* from_ref) { 1785 DCHECK(region_space_->IsInFromSpace(from_ref)); 1786 // No read barrier to avoid nested RB that might violate the to-space 1787 // invariant. Note that from_ref is a from space ref so the SizeOf() 1788 // call will access the from-space meta objects, but it's ok and necessary. 1789 size_t obj_size = from_ref->SizeOf<kDefaultVerifyFlags, kWithoutReadBarrier>(); 1790 size_t region_space_alloc_size = RoundUp(obj_size, space::RegionSpace::kAlignment); 1791 size_t region_space_bytes_allocated = 0U; 1792 size_t non_moving_space_bytes_allocated = 0U; 1793 size_t bytes_allocated = 0U; 1794 size_t dummy; 1795 mirror::Object* to_ref = region_space_->AllocNonvirtual<true>( 1796 region_space_alloc_size, ®ion_space_bytes_allocated, nullptr, &dummy); 1797 bytes_allocated = region_space_bytes_allocated; 1798 if (to_ref != nullptr) { 1799 DCHECK_EQ(region_space_alloc_size, region_space_bytes_allocated); 1800 } 1801 bool fall_back_to_non_moving = false; 1802 if (UNLIKELY(to_ref == nullptr)) { 1803 // Failed to allocate in the region space. Try the skipped blocks. 1804 to_ref = AllocateInSkippedBlock(region_space_alloc_size); 1805 if (to_ref != nullptr) { 1806 // Succeeded to allocate in a skipped block. 1807 if (heap_->use_tlab_) { 1808 // This is necessary for the tlab case as it's not accounted in the space. 1809 region_space_->RecordAlloc(to_ref); 1810 } 1811 bytes_allocated = region_space_alloc_size; 1812 } else { 1813 // Fall back to the non-moving space. 1814 fall_back_to_non_moving = true; 1815 if (kVerboseMode) { 1816 LOG(INFO) << "Out of memory in the to-space. Fall back to non-moving. skipped_bytes=" 1817 << to_space_bytes_skipped_.LoadSequentiallyConsistent() 1818 << " skipped_objects=" << to_space_objects_skipped_.LoadSequentiallyConsistent(); 1819 } 1820 fall_back_to_non_moving = true; 1821 to_ref = heap_->non_moving_space_->Alloc(Thread::Current(), obj_size, 1822 &non_moving_space_bytes_allocated, nullptr, &dummy); 1823 CHECK(to_ref != nullptr) << "Fall-back non-moving space allocation failed"; 1824 bytes_allocated = non_moving_space_bytes_allocated; 1825 // Mark it in the mark bitmap. 1826 accounting::ContinuousSpaceBitmap* mark_bitmap = 1827 heap_mark_bitmap_->GetContinuousSpaceBitmap(to_ref); 1828 CHECK(mark_bitmap != nullptr); 1829 CHECK(!mark_bitmap->AtomicTestAndSet(to_ref)); 1830 } 1831 } 1832 DCHECK(to_ref != nullptr); 1833 1834 // Attempt to install the forward pointer. This is in a loop as the 1835 // lock word atomic write can fail. 1836 while (true) { 1837 // Copy the object. TODO: copy only the lockword in the second iteration and on? 1838 memcpy(to_ref, from_ref, obj_size); 1839 1840 LockWord old_lock_word = to_ref->GetLockWord(false); 1841 1842 if (old_lock_word.GetState() == LockWord::kForwardingAddress) { 1843 // Lost the race. Another thread (either GC or mutator) stored 1844 // the forwarding pointer first. Make the lost copy (to_ref) 1845 // look like a valid but dead (dummy) object and keep it for 1846 // future reuse. 1847 FillWithDummyObject(to_ref, bytes_allocated); 1848 if (!fall_back_to_non_moving) { 1849 DCHECK(region_space_->IsInToSpace(to_ref)); 1850 if (bytes_allocated > space::RegionSpace::kRegionSize) { 1851 // Free the large alloc. 1852 region_space_->FreeLarge(to_ref, bytes_allocated); 1853 } else { 1854 // Record the lost copy for later reuse. 1855 heap_->num_bytes_allocated_.FetchAndAddSequentiallyConsistent(bytes_allocated); 1856 to_space_bytes_skipped_.FetchAndAddSequentiallyConsistent(bytes_allocated); 1857 to_space_objects_skipped_.FetchAndAddSequentiallyConsistent(1); 1858 MutexLock mu(Thread::Current(), skipped_blocks_lock_); 1859 skipped_blocks_map_.insert(std::make_pair(bytes_allocated, 1860 reinterpret_cast<uint8_t*>(to_ref))); 1861 } 1862 } else { 1863 DCHECK(heap_->non_moving_space_->HasAddress(to_ref)); 1864 DCHECK_EQ(bytes_allocated, non_moving_space_bytes_allocated); 1865 // Free the non-moving-space chunk. 1866 accounting::ContinuousSpaceBitmap* mark_bitmap = 1867 heap_mark_bitmap_->GetContinuousSpaceBitmap(to_ref); 1868 CHECK(mark_bitmap != nullptr); 1869 CHECK(mark_bitmap->Clear(to_ref)); 1870 heap_->non_moving_space_->Free(Thread::Current(), to_ref); 1871 } 1872 1873 // Get the winner's forward ptr. 1874 mirror::Object* lost_fwd_ptr = to_ref; 1875 to_ref = reinterpret_cast<mirror::Object*>(old_lock_word.ForwardingAddress()); 1876 CHECK(to_ref != nullptr); 1877 CHECK_NE(to_ref, lost_fwd_ptr); 1878 CHECK(region_space_->IsInToSpace(to_ref) || heap_->non_moving_space_->HasAddress(to_ref)); 1879 CHECK_NE(to_ref->GetLockWord(false).GetState(), LockWord::kForwardingAddress); 1880 return to_ref; 1881 } 1882 1883 // Set the gray ptr. 1884 if (kUseBakerReadBarrier) { 1885 to_ref->SetReadBarrierPointer(ReadBarrier::GrayPtr()); 1886 } 1887 1888 LockWord new_lock_word = LockWord::FromForwardingAddress(reinterpret_cast<size_t>(to_ref)); 1889 1890 // Try to atomically write the fwd ptr. 1891 bool success = from_ref->CasLockWordWeakSequentiallyConsistent(old_lock_word, new_lock_word); 1892 if (LIKELY(success)) { 1893 // The CAS succeeded. 1894 objects_moved_.FetchAndAddSequentiallyConsistent(1); 1895 bytes_moved_.FetchAndAddSequentiallyConsistent(region_space_alloc_size); 1896 if (LIKELY(!fall_back_to_non_moving)) { 1897 DCHECK(region_space_->IsInToSpace(to_ref)); 1898 } else { 1899 DCHECK(heap_->non_moving_space_->HasAddress(to_ref)); 1900 DCHECK_EQ(bytes_allocated, non_moving_space_bytes_allocated); 1901 } 1902 if (kUseBakerReadBarrier) { 1903 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr()); 1904 } 1905 DCHECK(GetFwdPtr(from_ref) == to_ref); 1906 CHECK_NE(to_ref->GetLockWord(false).GetState(), LockWord::kForwardingAddress); 1907 PushOntoMarkStack(to_ref); 1908 return to_ref; 1909 } else { 1910 // The CAS failed. It may have lost the race or may have failed 1911 // due to monitor/hashcode ops. Either way, retry. 1912 } 1913 } 1914} 1915 1916mirror::Object* ConcurrentCopying::IsMarked(mirror::Object* from_ref) { 1917 DCHECK(from_ref != nullptr); 1918 space::RegionSpace::RegionType rtype = region_space_->GetRegionType(from_ref); 1919 if (rtype == space::RegionSpace::RegionType::kRegionTypeToSpace) { 1920 // It's already marked. 1921 return from_ref; 1922 } 1923 mirror::Object* to_ref; 1924 if (rtype == space::RegionSpace::RegionType::kRegionTypeFromSpace) { 1925 to_ref = GetFwdPtr(from_ref); 1926 DCHECK(to_ref == nullptr || region_space_->IsInToSpace(to_ref) || 1927 heap_->non_moving_space_->HasAddress(to_ref)) 1928 << "from_ref=" << from_ref << " to_ref=" << to_ref; 1929 } else if (rtype == space::RegionSpace::RegionType::kRegionTypeUnevacFromSpace) { 1930 if (region_space_bitmap_->Test(from_ref)) { 1931 to_ref = from_ref; 1932 } else { 1933 to_ref = nullptr; 1934 } 1935 } else { 1936 // from_ref is in a non-moving space. 1937 if (immune_spaces_.ContainsObject(from_ref)) { 1938 accounting::ContinuousSpaceBitmap* cc_bitmap = 1939 cc_heap_bitmap_->GetContinuousSpaceBitmap(from_ref); 1940 DCHECK(cc_bitmap != nullptr) 1941 << "An immune space object must have a bitmap"; 1942 if (kIsDebugBuild) { 1943 DCHECK(heap_mark_bitmap_->GetContinuousSpaceBitmap(from_ref)->Test(from_ref)) 1944 << "Immune space object must be already marked"; 1945 } 1946 if (cc_bitmap->Test(from_ref)) { 1947 // Already marked. 1948 to_ref = from_ref; 1949 } else { 1950 // Newly marked. 1951 to_ref = nullptr; 1952 } 1953 } else { 1954 // Non-immune non-moving space. Use the mark bitmap. 1955 accounting::ContinuousSpaceBitmap* mark_bitmap = 1956 heap_mark_bitmap_->GetContinuousSpaceBitmap(from_ref); 1957 accounting::LargeObjectBitmap* los_bitmap = 1958 heap_mark_bitmap_->GetLargeObjectBitmap(from_ref); 1959 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range"; 1960 bool is_los = mark_bitmap == nullptr; 1961 if (!is_los && mark_bitmap->Test(from_ref)) { 1962 // Already marked. 1963 to_ref = from_ref; 1964 } else if (is_los && los_bitmap->Test(from_ref)) { 1965 // Already marked in LOS. 1966 to_ref = from_ref; 1967 } else { 1968 // Not marked. 1969 if (IsOnAllocStack(from_ref)) { 1970 // If on the allocation stack, it's considered marked. 1971 to_ref = from_ref; 1972 } else { 1973 // Not marked. 1974 to_ref = nullptr; 1975 } 1976 } 1977 } 1978 } 1979 return to_ref; 1980} 1981 1982bool ConcurrentCopying::IsOnAllocStack(mirror::Object* ref) { 1983 QuasiAtomic::ThreadFenceAcquire(); 1984 accounting::ObjectStack* alloc_stack = GetAllocationStack(); 1985 return alloc_stack->Contains(ref); 1986} 1987 1988mirror::Object* ConcurrentCopying::MarkNonMoving(mirror::Object* ref) { 1989 // ref is in a non-moving space (from_ref == to_ref). 1990 DCHECK(!region_space_->HasAddress(ref)) << ref; 1991 if (immune_spaces_.ContainsObject(ref)) { 1992 accounting::ContinuousSpaceBitmap* cc_bitmap = 1993 cc_heap_bitmap_->GetContinuousSpaceBitmap(ref); 1994 DCHECK(cc_bitmap != nullptr) 1995 << "An immune space object must have a bitmap"; 1996 if (kIsDebugBuild) { 1997 DCHECK(heap_mark_bitmap_->GetContinuousSpaceBitmap(ref)->Test(ref)) 1998 << "Immune space object must be already marked"; 1999 } 2000 // This may or may not succeed, which is ok. 2001 if (kUseBakerReadBarrier) { 2002 ref->AtomicSetReadBarrierPointer(ReadBarrier::WhitePtr(), ReadBarrier::GrayPtr()); 2003 } 2004 if (cc_bitmap->AtomicTestAndSet(ref)) { 2005 // Already marked. 2006 } else { 2007 // Newly marked. 2008 if (kUseBakerReadBarrier) { 2009 DCHECK_EQ(ref->GetReadBarrierPointer(), ReadBarrier::GrayPtr()); 2010 } 2011 PushOntoMarkStack(ref); 2012 } 2013 } else { 2014 // Use the mark bitmap. 2015 accounting::ContinuousSpaceBitmap* mark_bitmap = 2016 heap_mark_bitmap_->GetContinuousSpaceBitmap(ref); 2017 accounting::LargeObjectBitmap* los_bitmap = 2018 heap_mark_bitmap_->GetLargeObjectBitmap(ref); 2019 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range"; 2020 bool is_los = mark_bitmap == nullptr; 2021 if (!is_los && mark_bitmap->Test(ref)) { 2022 // Already marked. 2023 if (kUseBakerReadBarrier) { 2024 DCHECK(ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr() || 2025 ref->GetReadBarrierPointer() == ReadBarrier::BlackPtr()); 2026 } 2027 } else if (is_los && los_bitmap->Test(ref)) { 2028 // Already marked in LOS. 2029 if (kUseBakerReadBarrier) { 2030 DCHECK(ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr() || 2031 ref->GetReadBarrierPointer() == ReadBarrier::BlackPtr()); 2032 } 2033 } else { 2034 // Not marked. 2035 if (IsOnAllocStack(ref)) { 2036 // If it's on the allocation stack, it's considered marked. Keep it white. 2037 // Objects on the allocation stack need not be marked. 2038 if (!is_los) { 2039 DCHECK(!mark_bitmap->Test(ref)); 2040 } else { 2041 DCHECK(!los_bitmap->Test(ref)); 2042 } 2043 if (kUseBakerReadBarrier) { 2044 DCHECK_EQ(ref->GetReadBarrierPointer(), ReadBarrier::WhitePtr()); 2045 } 2046 } else { 2047 // Not marked or on the allocation stack. Try to mark it. 2048 // This may or may not succeed, which is ok. 2049 if (kUseBakerReadBarrier) { 2050 ref->AtomicSetReadBarrierPointer(ReadBarrier::WhitePtr(), ReadBarrier::GrayPtr()); 2051 } 2052 if (!is_los && mark_bitmap->AtomicTestAndSet(ref)) { 2053 // Already marked. 2054 } else if (is_los && los_bitmap->AtomicTestAndSet(ref)) { 2055 // Already marked in LOS. 2056 } else { 2057 // Newly marked. 2058 if (kUseBakerReadBarrier) { 2059 DCHECK_EQ(ref->GetReadBarrierPointer(), ReadBarrier::GrayPtr()); 2060 } 2061 PushOntoMarkStack(ref); 2062 } 2063 } 2064 } 2065 } 2066 return ref; 2067} 2068 2069void ConcurrentCopying::FinishPhase() { 2070 { 2071 MutexLock mu(Thread::Current(), mark_stack_lock_); 2072 CHECK_EQ(pooled_mark_stacks_.size(), kMarkStackPoolSize); 2073 } 2074 region_space_ = nullptr; 2075 { 2076 MutexLock mu(Thread::Current(), skipped_blocks_lock_); 2077 skipped_blocks_map_.clear(); 2078 } 2079 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_); 2080 heap_->ClearMarkedObjects(); 2081} 2082 2083bool ConcurrentCopying::IsMarkedHeapReference(mirror::HeapReference<mirror::Object>* field) { 2084 mirror::Object* from_ref = field->AsMirrorPtr(); 2085 mirror::Object* to_ref = IsMarked(from_ref); 2086 if (to_ref == nullptr) { 2087 return false; 2088 } 2089 if (from_ref != to_ref) { 2090 QuasiAtomic::ThreadFenceRelease(); 2091 field->Assign(to_ref); 2092 QuasiAtomic::ThreadFenceSequentiallyConsistent(); 2093 } 2094 return true; 2095} 2096 2097mirror::Object* ConcurrentCopying::MarkObject(mirror::Object* from_ref) { 2098 return Mark(from_ref); 2099} 2100 2101void ConcurrentCopying::DelayReferenceReferent(mirror::Class* klass, mirror::Reference* reference) { 2102 heap_->GetReferenceProcessor()->DelayReferenceReferent(klass, reference, this); 2103} 2104 2105void ConcurrentCopying::ProcessReferences(Thread* self) { 2106 TimingLogger::ScopedTiming split("ProcessReferences", GetTimings()); 2107 // We don't really need to lock the heap bitmap lock as we use CAS to mark in bitmaps. 2108 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_); 2109 GetHeap()->GetReferenceProcessor()->ProcessReferences( 2110 true /*concurrent*/, GetTimings(), GetCurrentIteration()->GetClearSoftReferences(), this); 2111} 2112 2113void ConcurrentCopying::RevokeAllThreadLocalBuffers() { 2114 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings()); 2115 region_space_->RevokeAllThreadLocalBuffers(); 2116} 2117 2118} // namespace collector 2119} // namespace gc 2120} // namespace art 2121