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