• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "barrier.h"
21 #include "base/enums.h"
22 #include "base/file_utils.h"
23 #include "base/histogram-inl.h"
24 #include "base/quasi_atomic.h"
25 #include "base/stl_util.h"
26 #include "base/systrace.h"
27 #include "class_root-inl.h"
28 #include "debugger.h"
29 #include "gc/accounting/atomic_stack.h"
30 #include "gc/accounting/heap_bitmap-inl.h"
31 #include "gc/accounting/mod_union_table-inl.h"
32 #include "gc/accounting/read_barrier_table.h"
33 #include "gc/accounting/space_bitmap-inl.h"
34 #include "gc/gc_pause_listener.h"
35 #include "gc/reference_processor.h"
36 #include "gc/space/image_space.h"
37 #include "gc/space/space-inl.h"
38 #include "gc/verification.h"
39 #include "image-inl.h"
40 #include "intern_table.h"
41 #include "mirror/class-inl.h"
42 #include "mirror/object-inl.h"
43 #include "mirror/object-refvisitor-inl.h"
44 #include "mirror/object_reference.h"
45 #include "scoped_thread_state_change-inl.h"
46 #include "thread-inl.h"
47 #include "thread_list.h"
48 #include "well_known_classes.h"
49 
50 namespace art {
51 namespace gc {
52 namespace collector {
53 
54 static constexpr size_t kDefaultGcMarkStackSize = 2 * MB;
55 // If kFilterModUnionCards then we attempt to filter cards that don't need to be dirty in the mod
56 // union table. Disabled since it does not seem to help the pause much.
57 static constexpr bool kFilterModUnionCards = kIsDebugBuild;
58 // If kDisallowReadBarrierDuringScan is true then the GC aborts if there are any read barrier that
59 // occur during ConcurrentCopying::Scan in GC thread. May be used to diagnose possibly unnecessary
60 // read barriers. Only enabled for kIsDebugBuild to avoid performance hit.
61 static constexpr bool kDisallowReadBarrierDuringScan = kIsDebugBuild;
62 // Slow path mark stack size, increase this if the stack is getting full and it is causing
63 // performance problems.
64 static constexpr size_t kReadBarrierMarkStackSize = 512 * KB;
65 // Size (in the number of objects) of the sweep array free buffer.
66 static constexpr size_t kSweepArrayChunkFreeSize = 1024;
67 // Verify that there are no missing card marks.
68 static constexpr bool kVerifyNoMissingCardMarks = kIsDebugBuild;
69 
ConcurrentCopying(Heap * heap,bool young_gen,bool use_generational_cc,const std::string & name_prefix,bool measure_read_barrier_slow_path)70 ConcurrentCopying::ConcurrentCopying(Heap* heap,
71                                      bool young_gen,
72                                      bool use_generational_cc,
73                                      const std::string& name_prefix,
74                                      bool measure_read_barrier_slow_path)
75     : GarbageCollector(heap,
76                        name_prefix + (name_prefix.empty() ? "" : " ") +
77                        "concurrent copying"),
78       region_space_(nullptr),
79       gc_barrier_(new Barrier(0)),
80       gc_mark_stack_(accounting::ObjectStack::Create("concurrent copying gc mark stack",
81                                                      kDefaultGcMarkStackSize,
82                                                      kDefaultGcMarkStackSize)),
83       use_generational_cc_(use_generational_cc),
84       young_gen_(young_gen),
85       rb_mark_bit_stack_(accounting::ObjectStack::Create("rb copying gc mark stack",
86                                                          kReadBarrierMarkStackSize,
87                                                          kReadBarrierMarkStackSize)),
88       rb_mark_bit_stack_full_(false),
89       mark_stack_lock_("concurrent copying mark stack lock", kMarkSweepMarkStackLock),
90       thread_running_gc_(nullptr),
91       is_marking_(false),
92       is_using_read_barrier_entrypoints_(false),
93       is_active_(false),
94       is_asserting_to_space_invariant_(false),
95       region_space_bitmap_(nullptr),
96       heap_mark_bitmap_(nullptr),
97       live_stack_freeze_size_(0),
98       from_space_num_objects_at_first_pause_(0),
99       from_space_num_bytes_at_first_pause_(0),
100       mark_stack_mode_(kMarkStackModeOff),
101       weak_ref_access_enabled_(true),
102       copied_live_bytes_ratio_sum_(0.f),
103       gc_count_(0),
104       reclaimed_bytes_ratio_sum_(0.f),
105       cumulative_bytes_moved_(0),
106       cumulative_objects_moved_(0),
107       skipped_blocks_lock_("concurrent copying bytes blocks lock", kMarkSweepMarkStackLock),
108       measure_read_barrier_slow_path_(measure_read_barrier_slow_path),
109       mark_from_read_barrier_measurements_(false),
110       rb_slow_path_ns_(0),
111       rb_slow_path_count_(0),
112       rb_slow_path_count_gc_(0),
113       rb_slow_path_histogram_lock_("Read barrier histogram lock"),
114       rb_slow_path_time_histogram_("Mutator time in read barrier slow path", 500, 32),
115       rb_slow_path_count_total_(0),
116       rb_slow_path_count_gc_total_(0),
117       rb_table_(heap_->GetReadBarrierTable()),
118       force_evacuate_all_(false),
119       gc_grays_immune_objects_(false),
120       immune_gray_stack_lock_("concurrent copying immune gray stack lock",
121                               kMarkSweepMarkStackLock),
122       num_bytes_allocated_before_gc_(0) {
123   static_assert(space::RegionSpace::kRegionSize == accounting::ReadBarrierTable::kRegionSize,
124                 "The region space size and the read barrier table region size must match");
125   CHECK(use_generational_cc_ || !young_gen_);
126   Thread* self = Thread::Current();
127   {
128     ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
129     // Cache this so that we won't have to lock heap_bitmap_lock_ in
130     // Mark() which could cause a nested lock on heap_bitmap_lock_
131     // when GC causes a RB while doing GC or a lock order violation
132     // (class_linker_lock_ and heap_bitmap_lock_).
133     heap_mark_bitmap_ = heap->GetMarkBitmap();
134   }
135   {
136     MutexLock mu(self, mark_stack_lock_);
137     for (size_t i = 0; i < kMarkStackPoolSize; ++i) {
138       accounting::AtomicStack<mirror::Object>* mark_stack =
139           accounting::AtomicStack<mirror::Object>::Create(
140               "thread local mark stack", kMarkStackSize, kMarkStackSize);
141       pooled_mark_stacks_.push_back(mark_stack);
142     }
143   }
144   if (use_generational_cc_) {
145     // Allocate sweep array free buffer.
146     std::string error_msg;
147     sweep_array_free_buffer_mem_map_ = MemMap::MapAnonymous(
148         "concurrent copying sweep array free buffer",
149         RoundUp(kSweepArrayChunkFreeSize * sizeof(mirror::Object*), kPageSize),
150         PROT_READ | PROT_WRITE,
151         /*low_4gb=*/ false,
152         &error_msg);
153     CHECK(sweep_array_free_buffer_mem_map_.IsValid())
154         << "Couldn't allocate sweep array free buffer: " << error_msg;
155   }
156   // Return type of these functions are different. And even though the base class
157   // is same, using ternary operator complains.
158   metrics::ArtMetrics* metrics = GetMetrics();
159   are_metrics_initialized_ = true;
160   if (young_gen_) {
161     gc_time_histogram_ = metrics->YoungGcCollectionTime();
162     metrics_gc_count_ = metrics->YoungGcCount();
163     gc_throughput_histogram_ = metrics->YoungGcThroughput();
164     gc_tracing_throughput_hist_ = metrics->YoungGcTracingThroughput();
165     gc_throughput_avg_ = metrics->YoungGcThroughputAvg();
166     gc_tracing_throughput_avg_ = metrics->YoungGcTracingThroughputAvg();
167   } else {
168     gc_time_histogram_ = metrics->FullGcCollectionTime();
169     metrics_gc_count_ = metrics->FullGcCount();
170     gc_throughput_histogram_ = metrics->FullGcThroughput();
171     gc_tracing_throughput_hist_ = metrics->FullGcTracingThroughput();
172     gc_throughput_avg_ = metrics->FullGcThroughputAvg();
173     gc_tracing_throughput_avg_ = metrics->FullGcTracingThroughputAvg();
174   }
175 }
176 
MarkHeapReference(mirror::HeapReference<mirror::Object> * field,bool do_atomic_update)177 void ConcurrentCopying::MarkHeapReference(mirror::HeapReference<mirror::Object>* field,
178                                           bool do_atomic_update) {
179   Thread* const self = Thread::Current();
180   if (UNLIKELY(do_atomic_update)) {
181     // Used to mark the referent in DelayReferenceReferent in transaction mode.
182     mirror::Object* from_ref = field->AsMirrorPtr();
183     if (from_ref == nullptr) {
184       return;
185     }
186     mirror::Object* to_ref = Mark(self, from_ref);
187     if (from_ref != to_ref) {
188       do {
189         if (field->AsMirrorPtr() != from_ref) {
190           // Concurrently overwritten by a mutator.
191           break;
192         }
193       } while (!field->CasWeakRelaxed(from_ref, to_ref));
194     }
195   } else {
196     // Used for preserving soft references, should be OK to not have a CAS here since there should be
197     // no other threads which can trigger read barriers on the same referent during reference
198     // processing.
199     field->Assign(Mark(self, field->AsMirrorPtr()));
200   }
201 }
202 
~ConcurrentCopying()203 ConcurrentCopying::~ConcurrentCopying() {
204   STLDeleteElements(&pooled_mark_stacks_);
205 }
206 
RunPhases()207 void ConcurrentCopying::RunPhases() {
208   CHECK(kUseBakerReadBarrier || kUseTableLookupReadBarrier);
209   CHECK(!is_active_);
210   is_active_ = true;
211   Thread* self = Thread::Current();
212   thread_running_gc_ = self;
213   Locks::mutator_lock_->AssertNotHeld(self);
214   {
215     ReaderMutexLock mu(self, *Locks::mutator_lock_);
216     InitializePhase();
217     // In case of forced evacuation, all regions are evacuated and hence no
218     // need to compute live_bytes.
219     if (use_generational_cc_ && !young_gen_ && !force_evacuate_all_) {
220       MarkingPhase();
221     }
222   }
223   if (kUseBakerReadBarrier && kGrayDirtyImmuneObjects) {
224     // Switch to read barrier mark entrypoints before we gray the objects. This is required in case
225     // a mutator sees a gray bit and dispatches on the entrypoint. (b/37876887).
226     ActivateReadBarrierEntrypoints();
227     // Gray dirty immune objects concurrently to reduce GC pause times. We re-process gray cards in
228     // the pause.
229     ReaderMutexLock mu(self, *Locks::mutator_lock_);
230     GrayAllDirtyImmuneObjects();
231   }
232   FlipThreadRoots();
233   {
234     ReaderMutexLock mu(self, *Locks::mutator_lock_);
235     CopyingPhase();
236   }
237   // Verify no from space refs. This causes a pause.
238   if (kEnableNoFromSpaceRefsVerification) {
239     TimingLogger::ScopedTiming split("(Paused)VerifyNoFromSpaceReferences", GetTimings());
240     ScopedPause pause(this, false);
241     CheckEmptyMarkStack();
242     if (kVerboseMode) {
243       LOG(INFO) << "Verifying no from-space refs";
244     }
245     VerifyNoFromSpaceReferences();
246     if (kVerboseMode) {
247       LOG(INFO) << "Done verifying no from-space refs";
248     }
249     CheckEmptyMarkStack();
250   }
251   {
252     ReaderMutexLock mu(self, *Locks::mutator_lock_);
253     ReclaimPhase();
254   }
255   FinishPhase();
256   CHECK(is_active_);
257   is_active_ = false;
258   thread_running_gc_ = nullptr;
259 }
260 
261 class ConcurrentCopying::ActivateReadBarrierEntrypointsCheckpoint : public Closure {
262  public:
ActivateReadBarrierEntrypointsCheckpoint(ConcurrentCopying * concurrent_copying)263   explicit ActivateReadBarrierEntrypointsCheckpoint(ConcurrentCopying* concurrent_copying)
264       : concurrent_copying_(concurrent_copying) {}
265 
Run(Thread * thread)266   void Run(Thread* thread) override NO_THREAD_SAFETY_ANALYSIS {
267     // Note: self is not necessarily equal to thread since thread may be suspended.
268     Thread* self = Thread::Current();
269     DCHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
270         << thread->GetState() << " thread " << thread << " self " << self;
271     // Switch to the read barrier entrypoints.
272     thread->SetReadBarrierEntrypoints();
273     // If thread is a running mutator, then act on behalf of the garbage collector.
274     // See the code in ThreadList::RunCheckpoint.
275     concurrent_copying_->GetBarrier().Pass(self);
276   }
277 
278  private:
279   ConcurrentCopying* const concurrent_copying_;
280 };
281 
282 class ConcurrentCopying::ActivateReadBarrierEntrypointsCallback : public Closure {
283  public:
ActivateReadBarrierEntrypointsCallback(ConcurrentCopying * concurrent_copying)284   explicit ActivateReadBarrierEntrypointsCallback(ConcurrentCopying* concurrent_copying)
285       : concurrent_copying_(concurrent_copying) {}
286 
Run(Thread * self ATTRIBUTE_UNUSED)287   void Run(Thread* self ATTRIBUTE_UNUSED) override REQUIRES(Locks::thread_list_lock_) {
288     // This needs to run under the thread_list_lock_ critical section in ThreadList::RunCheckpoint()
289     // to avoid a race with ThreadList::Register().
290     CHECK(!concurrent_copying_->is_using_read_barrier_entrypoints_);
291     concurrent_copying_->is_using_read_barrier_entrypoints_ = true;
292   }
293 
294  private:
295   ConcurrentCopying* const concurrent_copying_;
296 };
297 
ActivateReadBarrierEntrypoints()298 void ConcurrentCopying::ActivateReadBarrierEntrypoints() {
299   Thread* const self = Thread::Current();
300   ActivateReadBarrierEntrypointsCheckpoint checkpoint(this);
301   ThreadList* thread_list = Runtime::Current()->GetThreadList();
302   gc_barrier_->Init(self, 0);
303   ActivateReadBarrierEntrypointsCallback callback(this);
304   const size_t barrier_count = thread_list->RunCheckpoint(&checkpoint, &callback);
305   // If there are no threads to wait which implies that all the checkpoint functions are finished,
306   // then no need to release the mutator lock.
307   if (barrier_count == 0) {
308     return;
309   }
310   ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
311   gc_barrier_->Increment(self, barrier_count);
312 }
313 
CreateInterRegionRefBitmaps()314 void ConcurrentCopying::CreateInterRegionRefBitmaps() {
315   DCHECK(use_generational_cc_);
316   DCHECK(!region_space_inter_region_bitmap_.IsValid());
317   DCHECK(!non_moving_space_inter_region_bitmap_.IsValid());
318   DCHECK(region_space_ != nullptr);
319   DCHECK(heap_->non_moving_space_ != nullptr);
320   // Region-space
321   region_space_inter_region_bitmap_ = accounting::ContinuousSpaceBitmap::Create(
322       "region-space inter region ref bitmap",
323       reinterpret_cast<uint8_t*>(region_space_->Begin()),
324       region_space_->Limit() - region_space_->Begin());
325   CHECK(region_space_inter_region_bitmap_.IsValid())
326       << "Couldn't allocate region-space inter region ref bitmap";
327 
328   // non-moving-space
329   non_moving_space_inter_region_bitmap_ = accounting::ContinuousSpaceBitmap::Create(
330       "non-moving-space inter region ref bitmap",
331       reinterpret_cast<uint8_t*>(heap_->non_moving_space_->Begin()),
332       heap_->non_moving_space_->Limit() - heap_->non_moving_space_->Begin());
333   CHECK(non_moving_space_inter_region_bitmap_.IsValid())
334       << "Couldn't allocate non-moving-space inter region ref bitmap";
335 }
336 
BindBitmaps()337 void ConcurrentCopying::BindBitmaps() {
338   Thread* self = Thread::Current();
339   WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
340   // Mark all of the spaces we never collect as immune.
341   for (const auto& space : heap_->GetContinuousSpaces()) {
342     if (space->GetGcRetentionPolicy() == space::kGcRetentionPolicyNeverCollect ||
343         space->GetGcRetentionPolicy() == space::kGcRetentionPolicyFullCollect) {
344       CHECK(space->IsZygoteSpace() || space->IsImageSpace());
345       immune_spaces_.AddSpace(space);
346     } else {
347       CHECK(!space->IsZygoteSpace());
348       CHECK(!space->IsImageSpace());
349       CHECK(space == region_space_ || space == heap_->non_moving_space_);
350       if (use_generational_cc_) {
351         if (space == region_space_) {
352           region_space_bitmap_ = region_space_->GetMarkBitmap();
353         } else if (young_gen_ && space->IsContinuousMemMapAllocSpace()) {
354           DCHECK_EQ(space->GetGcRetentionPolicy(), space::kGcRetentionPolicyAlwaysCollect);
355           space->AsContinuousMemMapAllocSpace()->BindLiveToMarkBitmap();
356         }
357         if (young_gen_) {
358           // Age all of the cards for the region space so that we know which evac regions to scan.
359           heap_->GetCardTable()->ModifyCardsAtomic(space->Begin(),
360                                                    space->End(),
361                                                    AgeCardVisitor(),
362                                                    VoidFunctor());
363         } else {
364           // In a full-heap GC cycle, the card-table corresponding to region-space and
365           // non-moving space can be cleared, because this cycle only needs to
366           // capture writes during the marking phase of this cycle to catch
367           // objects that skipped marking due to heap mutation. Furthermore,
368           // if the next GC is a young-gen cycle, then it only needs writes to
369           // be captured after the thread-flip of this GC cycle, as that is when
370           // the young-gen for the next GC cycle starts getting populated.
371           heap_->GetCardTable()->ClearCardRange(space->Begin(), space->Limit());
372         }
373       } else {
374         if (space == region_space_) {
375           // It is OK to clear the bitmap with mutators running since the only place it is read is
376           // VisitObjects which has exclusion with CC.
377           region_space_bitmap_ = region_space_->GetMarkBitmap();
378           region_space_bitmap_->Clear();
379         }
380       }
381     }
382   }
383   if (use_generational_cc_ && young_gen_) {
384     for (const auto& space : GetHeap()->GetDiscontinuousSpaces()) {
385       CHECK(space->IsLargeObjectSpace());
386       space->AsLargeObjectSpace()->CopyLiveToMarked();
387     }
388   }
389 }
390 
InitializePhase()391 void ConcurrentCopying::InitializePhase() {
392   TimingLogger::ScopedTiming split("InitializePhase", GetTimings());
393   num_bytes_allocated_before_gc_ = static_cast<int64_t>(heap_->GetBytesAllocated());
394   if (kVerboseMode) {
395     LOG(INFO) << "GC InitializePhase";
396     LOG(INFO) << "Region-space : " << reinterpret_cast<void*>(region_space_->Begin()) << "-"
397               << reinterpret_cast<void*>(region_space_->Limit());
398   }
399   CheckEmptyMarkStack();
400   rb_mark_bit_stack_full_ = false;
401   mark_from_read_barrier_measurements_ = measure_read_barrier_slow_path_;
402   if (measure_read_barrier_slow_path_) {
403     rb_slow_path_ns_.store(0, std::memory_order_relaxed);
404     rb_slow_path_count_.store(0, std::memory_order_relaxed);
405     rb_slow_path_count_gc_.store(0, std::memory_order_relaxed);
406   }
407 
408   immune_spaces_.Reset();
409   bytes_moved_.store(0, std::memory_order_relaxed);
410   objects_moved_.store(0, std::memory_order_relaxed);
411   bytes_moved_gc_thread_ = 0;
412   objects_moved_gc_thread_ = 0;
413   bytes_scanned_ = 0;
414   GcCause gc_cause = GetCurrentIteration()->GetGcCause();
415 
416   force_evacuate_all_ = false;
417   if (!use_generational_cc_ || !young_gen_) {
418     if (gc_cause == kGcCauseExplicit ||
419         gc_cause == kGcCauseCollectorTransition ||
420         GetCurrentIteration()->GetClearSoftReferences()) {
421       force_evacuate_all_ = true;
422     }
423   }
424   if (kUseBakerReadBarrier) {
425     updated_all_immune_objects_.store(false, std::memory_order_relaxed);
426     // GC may gray immune objects in the thread flip.
427     gc_grays_immune_objects_ = true;
428     if (kIsDebugBuild) {
429       MutexLock mu(Thread::Current(), immune_gray_stack_lock_);
430       DCHECK(immune_gray_stack_.empty());
431     }
432   }
433   if (use_generational_cc_) {
434     done_scanning_.store(false, std::memory_order_release);
435   }
436   BindBitmaps();
437   if (kVerboseMode) {
438     LOG(INFO) << "young_gen=" << std::boolalpha << young_gen_ << std::noboolalpha;
439     LOG(INFO) << "force_evacuate_all=" << std::boolalpha << force_evacuate_all_ << std::noboolalpha;
440     LOG(INFO) << "Largest immune region: " << immune_spaces_.GetLargestImmuneRegion().Begin()
441               << "-" << immune_spaces_.GetLargestImmuneRegion().End();
442     for (space::ContinuousSpace* space : immune_spaces_.GetSpaces()) {
443       LOG(INFO) << "Immune space: " << *space;
444     }
445     LOG(INFO) << "GC end of InitializePhase";
446   }
447   if (use_generational_cc_ && !young_gen_) {
448     region_space_bitmap_->Clear();
449   }
450   mark_stack_mode_.store(ConcurrentCopying::kMarkStackModeThreadLocal, std::memory_order_relaxed);
451   // Mark all of the zygote large objects without graying them.
452   MarkZygoteLargeObjects();
453 }
454 
455 // Used to switch the thread roots of a thread from from-space refs to to-space refs.
456 class ConcurrentCopying::ThreadFlipVisitor : public Closure, public RootVisitor {
457  public:
ThreadFlipVisitor(ConcurrentCopying * concurrent_copying,bool use_tlab)458   ThreadFlipVisitor(ConcurrentCopying* concurrent_copying, bool use_tlab)
459       : concurrent_copying_(concurrent_copying), use_tlab_(use_tlab) {
460   }
461 
Run(Thread * thread)462   void Run(Thread* thread) override REQUIRES_SHARED(Locks::mutator_lock_) {
463     // Note: self is not necessarily equal to thread since thread may be suspended.
464     Thread* self = Thread::Current();
465     CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
466         << thread->GetState() << " thread " << thread << " self " << self;
467     thread->SetIsGcMarkingAndUpdateEntrypoints(true);
468     if (use_tlab_ && thread->HasTlab()) {
469       // We should not reuse the partially utilized TLABs revoked here as they
470       // are going to be part of from-space.
471       if (ConcurrentCopying::kEnableFromSpaceAccountingCheck) {
472         // This must come before the revoke.
473         size_t thread_local_objects = thread->GetThreadLocalObjectsAllocated();
474         concurrent_copying_->region_space_->RevokeThreadLocalBuffers(thread, /*reuse=*/ false);
475         reinterpret_cast<Atomic<size_t>*>(
476             &concurrent_copying_->from_space_num_objects_at_first_pause_)->
477                 fetch_add(thread_local_objects, std::memory_order_relaxed);
478       } else {
479         concurrent_copying_->region_space_->RevokeThreadLocalBuffers(thread, /*reuse=*/ false);
480       }
481     }
482     if (kUseThreadLocalAllocationStack) {
483       thread->RevokeThreadLocalAllocationStack();
484     }
485     ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
486     // We can use the non-CAS VisitRoots functions below because we update thread-local GC roots
487     // only.
488     thread->VisitRoots(this, kVisitRootFlagAllRoots);
489     concurrent_copying_->GetBarrier().Pass(self);
490   }
491 
VisitRoots(mirror::Object *** roots,size_t count,const RootInfo & info ATTRIBUTE_UNUSED)492   void VisitRoots(mirror::Object*** roots,
493                   size_t count,
494                   const RootInfo& info ATTRIBUTE_UNUSED) override
495       REQUIRES_SHARED(Locks::mutator_lock_) {
496     Thread* self = Thread::Current();
497     for (size_t i = 0; i < count; ++i) {
498       mirror::Object** root = roots[i];
499       mirror::Object* ref = *root;
500       if (ref != nullptr) {
501         mirror::Object* to_ref = concurrent_copying_->Mark(self, ref);
502         if (to_ref != ref) {
503           *root = to_ref;
504         }
505       }
506     }
507   }
508 
VisitRoots(mirror::CompressedReference<mirror::Object> ** roots,size_t count,const RootInfo & info ATTRIBUTE_UNUSED)509   void VisitRoots(mirror::CompressedReference<mirror::Object>** roots,
510                   size_t count,
511                   const RootInfo& info ATTRIBUTE_UNUSED) override
512       REQUIRES_SHARED(Locks::mutator_lock_) {
513     Thread* self = Thread::Current();
514     for (size_t i = 0; i < count; ++i) {
515       mirror::CompressedReference<mirror::Object>* const root = roots[i];
516       if (!root->IsNull()) {
517         mirror::Object* ref = root->AsMirrorPtr();
518         mirror::Object* to_ref = concurrent_copying_->Mark(self, ref);
519         if (to_ref != ref) {
520           root->Assign(to_ref);
521         }
522       }
523     }
524   }
525 
526  private:
527   ConcurrentCopying* const concurrent_copying_;
528   const bool use_tlab_;
529 };
530 
531 // Called back from Runtime::FlipThreadRoots() during a pause.
532 class ConcurrentCopying::FlipCallback : public Closure {
533  public:
FlipCallback(ConcurrentCopying * concurrent_copying)534   explicit FlipCallback(ConcurrentCopying* concurrent_copying)
535       : concurrent_copying_(concurrent_copying) {
536   }
537 
Run(Thread * thread)538   void Run(Thread* thread) override REQUIRES(Locks::mutator_lock_) {
539     ConcurrentCopying* cc = concurrent_copying_;
540     TimingLogger::ScopedTiming split("(Paused)FlipCallback", cc->GetTimings());
541     // Note: self is not necessarily equal to thread since thread may be suspended.
542     Thread* self = Thread::Current();
543     if (kVerifyNoMissingCardMarks && cc->young_gen_) {
544       cc->VerifyNoMissingCardMarks();
545     }
546     CHECK_EQ(thread, self);
547     Locks::mutator_lock_->AssertExclusiveHeld(self);
548     space::RegionSpace::EvacMode evac_mode = space::RegionSpace::kEvacModeLivePercentNewlyAllocated;
549     if (cc->young_gen_) {
550       CHECK(!cc->force_evacuate_all_);
551       evac_mode = space::RegionSpace::kEvacModeNewlyAllocated;
552     } else if (cc->force_evacuate_all_) {
553       evac_mode = space::RegionSpace::kEvacModeForceAll;
554     }
555     {
556       TimingLogger::ScopedTiming split2("(Paused)SetFromSpace", cc->GetTimings());
557       // Only change live bytes for 1-phase full heap CC.
558       cc->region_space_->SetFromSpace(
559           cc->rb_table_,
560           evac_mode,
561           /*clear_live_bytes=*/ !cc->use_generational_cc_);
562     }
563     cc->SwapStacks();
564     if (ConcurrentCopying::kEnableFromSpaceAccountingCheck) {
565       cc->RecordLiveStackFreezeSize(self);
566       cc->from_space_num_objects_at_first_pause_ = cc->region_space_->GetObjectsAllocated();
567       cc->from_space_num_bytes_at_first_pause_ = cc->region_space_->GetBytesAllocated();
568     }
569     cc->is_marking_ = true;
570     if (kIsDebugBuild && !cc->use_generational_cc_) {
571       cc->region_space_->AssertAllRegionLiveBytesZeroOrCleared();
572     }
573     if (UNLIKELY(Runtime::Current()->IsActiveTransaction())) {
574       CHECK(Runtime::Current()->IsAotCompiler());
575       TimingLogger::ScopedTiming split3("(Paused)VisitTransactionRoots", cc->GetTimings());
576       Runtime::Current()->VisitTransactionRoots(cc);
577     }
578     if (kUseBakerReadBarrier && kGrayDirtyImmuneObjects) {
579       cc->GrayAllNewlyDirtyImmuneObjects();
580       if (kIsDebugBuild) {
581         // Check that all non-gray immune objects only reference immune objects.
582         cc->VerifyGrayImmuneObjects();
583       }
584     }
585     // May be null during runtime creation, in this case leave java_lang_Object null.
586     // This is safe since single threaded behavior should mean FillWithFakeObject does not
587     // happen when java_lang_Object_ is null.
588     if (WellKnownClasses::java_lang_Object != nullptr) {
589       cc->java_lang_Object_ = down_cast<mirror::Class*>(cc->Mark(thread,
590           WellKnownClasses::ToClass(WellKnownClasses::java_lang_Object).Ptr()));
591     } else {
592       cc->java_lang_Object_ = nullptr;
593     }
594   }
595 
596  private:
597   ConcurrentCopying* const concurrent_copying_;
598 };
599 
600 class ConcurrentCopying::VerifyGrayImmuneObjectsVisitor {
601  public:
VerifyGrayImmuneObjectsVisitor(ConcurrentCopying * collector)602   explicit VerifyGrayImmuneObjectsVisitor(ConcurrentCopying* collector)
603       : collector_(collector) {}
604 
operator ()(ObjPtr<mirror::Object> obj,MemberOffset offset,bool) const605   void operator()(ObjPtr<mirror::Object> obj, MemberOffset offset, bool /* is_static */)
606       const ALWAYS_INLINE REQUIRES_SHARED(Locks::mutator_lock_)
607       REQUIRES_SHARED(Locks::heap_bitmap_lock_) {
608     CheckReference(obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(offset),
609                    obj, offset);
610   }
611 
operator ()(ObjPtr<mirror::Class> klass,ObjPtr<mirror::Reference> ref) const612   void operator()(ObjPtr<mirror::Class> klass, ObjPtr<mirror::Reference> ref) const
613       REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
614     CHECK(klass->IsTypeOfReferenceClass());
615     CheckReference(ref->GetReferent<kWithoutReadBarrier>(),
616                    ref,
617                    mirror::Reference::ReferentOffset());
618   }
619 
VisitRootIfNonNull(mirror::CompressedReference<mirror::Object> * root) const620   void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
621       ALWAYS_INLINE
622       REQUIRES_SHARED(Locks::mutator_lock_) {
623     if (!root->IsNull()) {
624       VisitRoot(root);
625     }
626   }
627 
VisitRoot(mirror::CompressedReference<mirror::Object> * root) const628   void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
629       ALWAYS_INLINE
630       REQUIRES_SHARED(Locks::mutator_lock_) {
631     CheckReference(root->AsMirrorPtr(), nullptr, MemberOffset(0));
632   }
633 
634  private:
635   ConcurrentCopying* const collector_;
636 
CheckReference(ObjPtr<mirror::Object> ref,ObjPtr<mirror::Object> holder,MemberOffset offset) const637   void CheckReference(ObjPtr<mirror::Object> ref,
638                       ObjPtr<mirror::Object> holder,
639                       MemberOffset offset) const
640       REQUIRES_SHARED(Locks::mutator_lock_) {
641     if (ref != nullptr) {
642       if (!collector_->immune_spaces_.ContainsObject(ref.Ptr())) {
643         // Not immune, must be a zygote large object.
644         space::LargeObjectSpace* large_object_space =
645             Runtime::Current()->GetHeap()->GetLargeObjectsSpace();
646         CHECK(large_object_space->Contains(ref.Ptr()) &&
647               large_object_space->IsZygoteLargeObject(Thread::Current(), ref.Ptr()))
648             << "Non gray object references non immune, non zygote large object "<< ref << " "
649             << mirror::Object::PrettyTypeOf(ref) << " in holder " << holder << " "
650             << mirror::Object::PrettyTypeOf(holder) << " offset=" << offset.Uint32Value();
651       } else {
652         // Make sure the large object class is immune since we will never scan the large object.
653         CHECK(collector_->immune_spaces_.ContainsObject(
654             ref->GetClass<kVerifyNone, kWithoutReadBarrier>()));
655       }
656     }
657   }
658 };
659 
VerifyGrayImmuneObjects()660 void ConcurrentCopying::VerifyGrayImmuneObjects() {
661   TimingLogger::ScopedTiming split(__FUNCTION__, GetTimings());
662   for (auto& space : immune_spaces_.GetSpaces()) {
663     DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
664     accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
665     VerifyGrayImmuneObjectsVisitor visitor(this);
666     live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()),
667                                   reinterpret_cast<uintptr_t>(space->Limit()),
668                                   [&visitor](mirror::Object* obj)
669         REQUIRES_SHARED(Locks::mutator_lock_) {
670       // If an object is not gray, it should only have references to things in the immune spaces.
671       if (obj->GetReadBarrierState() != ReadBarrier::GrayState()) {
672         obj->VisitReferences</*kVisitNativeRoots=*/true,
673                              kDefaultVerifyFlags,
674                              kWithoutReadBarrier>(visitor, visitor);
675       }
676     });
677   }
678 }
679 
680 class ConcurrentCopying::VerifyNoMissingCardMarkVisitor {
681  public:
VerifyNoMissingCardMarkVisitor(ConcurrentCopying * cc,ObjPtr<mirror::Object> holder)682   VerifyNoMissingCardMarkVisitor(ConcurrentCopying* cc, ObjPtr<mirror::Object> holder)
683     : cc_(cc),
684       holder_(holder) {}
685 
operator ()(ObjPtr<mirror::Object> obj,MemberOffset offset,bool is_static ATTRIBUTE_UNUSED) const686   void operator()(ObjPtr<mirror::Object> obj,
687                   MemberOffset offset,
688                   bool is_static ATTRIBUTE_UNUSED) const
689       REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
690     if (offset.Uint32Value() != mirror::Object::ClassOffset().Uint32Value()) {
691      CheckReference(obj->GetFieldObject<mirror::Object, kDefaultVerifyFlags, kWithoutReadBarrier>(
692          offset), offset.Uint32Value());
693     }
694   }
operator ()(ObjPtr<mirror::Class> klass,ObjPtr<mirror::Reference> ref) const695   void operator()(ObjPtr<mirror::Class> klass,
696                   ObjPtr<mirror::Reference> ref) const
697       REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
698     CHECK(klass->IsTypeOfReferenceClass());
699     this->operator()(ref, mirror::Reference::ReferentOffset(), false);
700   }
701 
VisitRootIfNonNull(mirror::CompressedReference<mirror::Object> * root) const702   void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
703       REQUIRES_SHARED(Locks::mutator_lock_) {
704     if (!root->IsNull()) {
705       VisitRoot(root);
706     }
707   }
708 
VisitRoot(mirror::CompressedReference<mirror::Object> * root) const709   void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
710       REQUIRES_SHARED(Locks::mutator_lock_) {
711     CheckReference(root->AsMirrorPtr());
712   }
713 
CheckReference(mirror::Object * ref,int32_t offset=-1) const714   void CheckReference(mirror::Object* ref, int32_t offset = -1) const
715       REQUIRES_SHARED(Locks::mutator_lock_) {
716     if (ref != nullptr && cc_->region_space_->IsInNewlyAllocatedRegion(ref)) {
717       LOG(FATAL_WITHOUT_ABORT)
718         << holder_->PrettyTypeOf() << "(" << holder_.Ptr() << ") references object "
719         << ref->PrettyTypeOf() << "(" << ref << ") in newly allocated region at offset=" << offset;
720       LOG(FATAL_WITHOUT_ABORT) << "time=" << cc_->region_space_->Time();
721       constexpr const char* kIndent = "  ";
722       LOG(FATAL_WITHOUT_ABORT) << cc_->DumpReferenceInfo(holder_.Ptr(), "holder_", kIndent);
723       LOG(FATAL_WITHOUT_ABORT) << cc_->DumpReferenceInfo(ref, "ref", kIndent);
724       LOG(FATAL) << "Unexpected reference to newly allocated region.";
725     }
726   }
727 
728  private:
729   ConcurrentCopying* const cc_;
730   const ObjPtr<mirror::Object> holder_;
731 };
732 
VerifyNoMissingCardMarks()733 void ConcurrentCopying::VerifyNoMissingCardMarks() {
734   auto visitor = [&](mirror::Object* obj)
735       REQUIRES(Locks::mutator_lock_)
736       REQUIRES(!mark_stack_lock_) {
737     // Objects on clean cards should never have references to newly allocated regions. Note
738     // that aged cards are also not clean.
739     if (heap_->GetCardTable()->GetCard(obj) == gc::accounting::CardTable::kCardClean) {
740       VerifyNoMissingCardMarkVisitor internal_visitor(this, /*holder=*/ obj);
741       obj->VisitReferences</*kVisitNativeRoots=*/true, kVerifyNone, kWithoutReadBarrier>(
742           internal_visitor, internal_visitor);
743     }
744   };
745   TimingLogger::ScopedTiming split(__FUNCTION__, GetTimings());
746   region_space_->Walk(visitor);
747   {
748     ReaderMutexLock rmu(Thread::Current(), *Locks::heap_bitmap_lock_);
749     heap_->GetLiveBitmap()->Visit(visitor);
750   }
751 }
752 
753 // Switch threads that from from-space to to-space refs. Forward/mark the thread roots.
FlipThreadRoots()754 void ConcurrentCopying::FlipThreadRoots() {
755   TimingLogger::ScopedTiming split("FlipThreadRoots", GetTimings());
756   if (kVerboseMode || heap_->dump_region_info_before_gc_) {
757     LOG(INFO) << "time=" << region_space_->Time();
758     region_space_->DumpNonFreeRegions(LOG_STREAM(INFO));
759   }
760   Thread* self = Thread::Current();
761   Locks::mutator_lock_->AssertNotHeld(self);
762   gc_barrier_->Init(self, 0);
763   ThreadFlipVisitor thread_flip_visitor(this, heap_->use_tlab_);
764   FlipCallback flip_callback(this);
765 
766   size_t barrier_count = Runtime::Current()->GetThreadList()->FlipThreadRoots(
767       &thread_flip_visitor, &flip_callback, this, GetHeap()->GetGcPauseListener());
768 
769   {
770     ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
771     gc_barrier_->Increment(self, barrier_count);
772   }
773   is_asserting_to_space_invariant_ = true;
774   QuasiAtomic::ThreadFenceForConstructor();
775   if (kVerboseMode) {
776     LOG(INFO) << "time=" << region_space_->Time();
777     region_space_->DumpNonFreeRegions(LOG_STREAM(INFO));
778     LOG(INFO) << "GC end of FlipThreadRoots";
779   }
780 }
781 
782 template <bool kConcurrent>
783 class ConcurrentCopying::GrayImmuneObjectVisitor {
784  public:
GrayImmuneObjectVisitor(Thread * self)785   explicit GrayImmuneObjectVisitor(Thread* self) : self_(self) {}
786 
operator ()(mirror::Object * obj) const787   ALWAYS_INLINE void operator()(mirror::Object* obj) const REQUIRES_SHARED(Locks::mutator_lock_) {
788     if (kUseBakerReadBarrier && obj->GetReadBarrierState() == ReadBarrier::NonGrayState()) {
789       if (kConcurrent) {
790         Locks::mutator_lock_->AssertSharedHeld(self_);
791         obj->AtomicSetReadBarrierState(ReadBarrier::NonGrayState(), ReadBarrier::GrayState());
792         // Mod union table VisitObjects may visit the same object multiple times so we can't check
793         // the result of the atomic set.
794       } else {
795         Locks::mutator_lock_->AssertExclusiveHeld(self_);
796         obj->SetReadBarrierState(ReadBarrier::GrayState());
797       }
798     }
799   }
800 
Callback(mirror::Object * obj,void * arg)801   static void Callback(mirror::Object* obj, void* arg) REQUIRES_SHARED(Locks::mutator_lock_) {
802     reinterpret_cast<GrayImmuneObjectVisitor<kConcurrent>*>(arg)->operator()(obj);
803   }
804 
805  private:
806   Thread* const self_;
807 };
808 
GrayAllDirtyImmuneObjects()809 void ConcurrentCopying::GrayAllDirtyImmuneObjects() {
810   TimingLogger::ScopedTiming split("GrayAllDirtyImmuneObjects", GetTimings());
811   accounting::CardTable* const card_table = heap_->GetCardTable();
812   Thread* const self = Thread::Current();
813   using VisitorType = GrayImmuneObjectVisitor</* kIsConcurrent= */ true>;
814   VisitorType visitor(self);
815   WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
816   for (space::ContinuousSpace* space : immune_spaces_.GetSpaces()) {
817     DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
818     accounting::ModUnionTable* table = heap_->FindModUnionTableFromSpace(space);
819     // Mark all the objects on dirty cards since these may point to objects in other space.
820     // Once these are marked, the GC will eventually clear them later.
821     // Table is non null for boot image and zygote spaces. It is only null for application image
822     // spaces.
823     if (table != nullptr) {
824       table->ProcessCards();
825       table->VisitObjects(&VisitorType::Callback, &visitor);
826       // Don't clear cards here since we need to rescan in the pause. If we cleared the cards here,
827       // there would be races with the mutator marking new cards.
828     } else {
829       // Keep cards aged if we don't have a mod-union table since we may need to scan them in future
830       // GCs. This case is for app images.
831       card_table->ModifyCardsAtomic(
832           space->Begin(),
833           space->End(),
834           [](uint8_t card) {
835             return (card != gc::accounting::CardTable::kCardClean)
836                 ? gc::accounting::CardTable::kCardAged
837                 : card;
838           },
839           /* card modified visitor */ VoidFunctor());
840       card_table->Scan</*kClearCard=*/ false>(space->GetMarkBitmap(),
841                                               space->Begin(),
842                                               space->End(),
843                                               visitor,
844                                               gc::accounting::CardTable::kCardAged);
845     }
846   }
847 }
848 
GrayAllNewlyDirtyImmuneObjects()849 void ConcurrentCopying::GrayAllNewlyDirtyImmuneObjects() {
850   TimingLogger::ScopedTiming split("(Paused)GrayAllNewlyDirtyImmuneObjects", GetTimings());
851   accounting::CardTable* const card_table = heap_->GetCardTable();
852   using VisitorType = GrayImmuneObjectVisitor</* kIsConcurrent= */ false>;
853   Thread* const self = Thread::Current();
854   VisitorType visitor(self);
855   WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
856   for (space::ContinuousSpace* space : immune_spaces_.GetSpaces()) {
857     DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
858     accounting::ModUnionTable* table = heap_->FindModUnionTableFromSpace(space);
859 
860     // Don't need to scan aged cards since we did these before the pause. Note that scanning cards
861     // also handles the mod-union table cards.
862     card_table->Scan</*kClearCard=*/ false>(space->GetMarkBitmap(),
863                                             space->Begin(),
864                                             space->End(),
865                                             visitor,
866                                             gc::accounting::CardTable::kCardDirty);
867     if (table != nullptr) {
868       // Add the cards to the mod-union table so that we can clear cards to save RAM.
869       table->ProcessCards();
870       TimingLogger::ScopedTiming split2("(Paused)ClearCards", GetTimings());
871       card_table->ClearCardRange(space->Begin(),
872                                  AlignDown(space->End(), accounting::CardTable::kCardSize));
873     }
874   }
875   // Since all of the objects that may point to other spaces are gray, we can avoid all the read
876   // barriers in the immune spaces.
877   updated_all_immune_objects_.store(true, std::memory_order_relaxed);
878 }
879 
SwapStacks()880 void ConcurrentCopying::SwapStacks() {
881   heap_->SwapStacks();
882 }
883 
RecordLiveStackFreezeSize(Thread * self)884 void ConcurrentCopying::RecordLiveStackFreezeSize(Thread* self) {
885   WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
886   live_stack_freeze_size_ = heap_->GetLiveStack()->Size();
887 }
888 
889 // Used to visit objects in the immune spaces.
ScanImmuneObject(mirror::Object * obj)890 inline void ConcurrentCopying::ScanImmuneObject(mirror::Object* obj) {
891   DCHECK(obj != nullptr);
892   DCHECK(immune_spaces_.ContainsObject(obj));
893   // Update the fields without graying it or pushing it onto the mark stack.
894   if (use_generational_cc_ && young_gen_) {
895     // Young GC does not care about references to unevac space. It is safe to not gray these as
896     // long as scan immune objects happens after scanning the dirty cards.
897     Scan<true>(obj);
898   } else {
899     Scan<false>(obj);
900   }
901 }
902 
903 class ConcurrentCopying::ImmuneSpaceScanObjVisitor {
904  public:
ImmuneSpaceScanObjVisitor(ConcurrentCopying * cc)905   explicit ImmuneSpaceScanObjVisitor(ConcurrentCopying* cc)
906       : collector_(cc) {}
907 
operator ()(mirror::Object * obj) const908   ALWAYS_INLINE void operator()(mirror::Object* obj) const REQUIRES_SHARED(Locks::mutator_lock_) {
909     if (kUseBakerReadBarrier && kGrayDirtyImmuneObjects) {
910       // Only need to scan gray objects.
911       if (obj->GetReadBarrierState() == ReadBarrier::GrayState()) {
912         collector_->ScanImmuneObject(obj);
913         // Done scanning the object, go back to black (non-gray).
914         bool success = obj->AtomicSetReadBarrierState(ReadBarrier::GrayState(),
915                                                       ReadBarrier::NonGrayState());
916         CHECK(success)
917             << Runtime::Current()->GetHeap()->GetVerification()->DumpObjectInfo(obj, "failed CAS");
918       }
919     } else {
920       collector_->ScanImmuneObject(obj);
921     }
922   }
923 
Callback(mirror::Object * obj,void * arg)924   static void Callback(mirror::Object* obj, void* arg) REQUIRES_SHARED(Locks::mutator_lock_) {
925     reinterpret_cast<ImmuneSpaceScanObjVisitor*>(arg)->operator()(obj);
926   }
927 
928  private:
929   ConcurrentCopying* const collector_;
930 };
931 
932 template <bool kAtomicTestAndSet>
933 class ConcurrentCopying::CaptureRootsForMarkingVisitor : public RootVisitor {
934  public:
CaptureRootsForMarkingVisitor(ConcurrentCopying * cc,Thread * self)935   explicit CaptureRootsForMarkingVisitor(ConcurrentCopying* cc, Thread* self)
936       : collector_(cc), self_(self) {}
937 
VisitRoots(mirror::Object *** roots,size_t count,const RootInfo & info ATTRIBUTE_UNUSED)938   void VisitRoots(mirror::Object*** roots,
939                   size_t count,
940                   const RootInfo& info ATTRIBUTE_UNUSED) override
941       REQUIRES_SHARED(Locks::mutator_lock_) {
942     for (size_t i = 0; i < count; ++i) {
943       mirror::Object** root = roots[i];
944       mirror::Object* ref = *root;
945       if (ref != nullptr && !collector_->TestAndSetMarkBitForRef<kAtomicTestAndSet>(ref)) {
946         collector_->PushOntoMarkStack(self_, ref);
947       }
948     }
949   }
950 
VisitRoots(mirror::CompressedReference<mirror::Object> ** roots,size_t count,const RootInfo & info ATTRIBUTE_UNUSED)951   void VisitRoots(mirror::CompressedReference<mirror::Object>** roots,
952                   size_t count,
953                   const RootInfo& info ATTRIBUTE_UNUSED) override
954       REQUIRES_SHARED(Locks::mutator_lock_) {
955     for (size_t i = 0; i < count; ++i) {
956       mirror::CompressedReference<mirror::Object>* const root = roots[i];
957       if (!root->IsNull()) {
958         mirror::Object* ref = root->AsMirrorPtr();
959         if (!collector_->TestAndSetMarkBitForRef<kAtomicTestAndSet>(ref)) {
960           collector_->PushOntoMarkStack(self_, ref);
961         }
962       }
963     }
964   }
965 
966  private:
967   ConcurrentCopying* const collector_;
968   Thread* const self_;
969 };
970 
971 class ConcurrentCopying::RevokeThreadLocalMarkStackCheckpoint : public Closure {
972  public:
RevokeThreadLocalMarkStackCheckpoint(ConcurrentCopying * concurrent_copying,bool disable_weak_ref_access)973   RevokeThreadLocalMarkStackCheckpoint(ConcurrentCopying* concurrent_copying,
974                                        bool disable_weak_ref_access)
975       : concurrent_copying_(concurrent_copying),
976         disable_weak_ref_access_(disable_weak_ref_access) {
977   }
978 
Run(Thread * thread)979   void Run(Thread* thread) override NO_THREAD_SAFETY_ANALYSIS {
980     // Note: self is not necessarily equal to thread since thread may be suspended.
981     Thread* const self = Thread::Current();
982     CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
983         << thread->GetState() << " thread " << thread << " self " << self;
984     // Revoke thread local mark stacks.
985     {
986       MutexLock mu(self, concurrent_copying_->mark_stack_lock_);
987       accounting::AtomicStack<mirror::Object>* tl_mark_stack = thread->GetThreadLocalMarkStack();
988       if (tl_mark_stack != nullptr) {
989         concurrent_copying_->revoked_mark_stacks_.push_back(tl_mark_stack);
990         thread->SetThreadLocalMarkStack(nullptr);
991       }
992     }
993     // Disable weak ref access.
994     if (disable_weak_ref_access_) {
995       thread->SetWeakRefAccessEnabled(false);
996     }
997     // If thread is a running mutator, then act on behalf of the garbage collector.
998     // See the code in ThreadList::RunCheckpoint.
999     concurrent_copying_->GetBarrier().Pass(self);
1000   }
1001 
1002  protected:
1003   ConcurrentCopying* const concurrent_copying_;
1004 
1005  private:
1006   const bool disable_weak_ref_access_;
1007 };
1008 
1009 class ConcurrentCopying::CaptureThreadRootsForMarkingAndCheckpoint :
1010   public RevokeThreadLocalMarkStackCheckpoint {
1011  public:
CaptureThreadRootsForMarkingAndCheckpoint(ConcurrentCopying * cc)1012   explicit CaptureThreadRootsForMarkingAndCheckpoint(ConcurrentCopying* cc) :
1013     RevokeThreadLocalMarkStackCheckpoint(cc, /* disable_weak_ref_access */ false) {}
1014 
Run(Thread * thread)1015   void Run(Thread* thread) override
1016       REQUIRES_SHARED(Locks::mutator_lock_) {
1017     Thread* const self = Thread::Current();
1018     ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1019     // We can use the non-CAS VisitRoots functions below because we update thread-local GC roots
1020     // only.
1021     CaptureRootsForMarkingVisitor</*kAtomicTestAndSet*/ true> visitor(concurrent_copying_, self);
1022     thread->VisitRoots(&visitor, kVisitRootFlagAllRoots);
1023     // If thread_running_gc_ performed the root visit then its thread-local
1024     // mark-stack should be null as we directly push to gc_mark_stack_.
1025     CHECK(self == thread || self->GetThreadLocalMarkStack() == nullptr);
1026     // Barrier handling is done in the base class' Run() below.
1027     RevokeThreadLocalMarkStackCheckpoint::Run(thread);
1028   }
1029 };
1030 
CaptureThreadRootsForMarking()1031 void ConcurrentCopying::CaptureThreadRootsForMarking() {
1032   TimingLogger::ScopedTiming split("CaptureThreadRootsForMarking", GetTimings());
1033   if (kVerboseMode) {
1034     LOG(INFO) << "time=" << region_space_->Time();
1035     region_space_->DumpNonFreeRegions(LOG_STREAM(INFO));
1036   }
1037   Thread* const self = Thread::Current();
1038   CaptureThreadRootsForMarkingAndCheckpoint check_point(this);
1039   ThreadList* thread_list = Runtime::Current()->GetThreadList();
1040   gc_barrier_->Init(self, 0);
1041   size_t barrier_count = thread_list->RunCheckpoint(&check_point, /* callback */ nullptr);
1042   // If there are no threads to wait which implys that all the checkpoint functions are finished,
1043   // then no need to release the mutator lock.
1044   if (barrier_count == 0) {
1045     return;
1046   }
1047   Locks::mutator_lock_->SharedUnlock(self);
1048   {
1049     ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
1050     gc_barrier_->Increment(self, barrier_count);
1051   }
1052   Locks::mutator_lock_->SharedLock(self);
1053   if (kVerboseMode) {
1054     LOG(INFO) << "time=" << region_space_->Time();
1055     region_space_->DumpNonFreeRegions(LOG_STREAM(INFO));
1056     LOG(INFO) << "GC end of CaptureThreadRootsForMarking";
1057   }
1058 }
1059 
1060 // Used to scan ref fields of an object.
1061 template <bool kHandleInterRegionRefs>
1062 class ConcurrentCopying::ComputeLiveBytesAndMarkRefFieldsVisitor {
1063  public:
ComputeLiveBytesAndMarkRefFieldsVisitor(ConcurrentCopying * collector,size_t obj_region_idx)1064   explicit ComputeLiveBytesAndMarkRefFieldsVisitor(ConcurrentCopying* collector,
1065                                                    size_t obj_region_idx)
1066       : collector_(collector),
1067       obj_region_idx_(obj_region_idx),
1068       contains_inter_region_idx_(false) {}
1069 
operator ()(mirror::Object * obj,MemberOffset offset,bool) const1070   void operator()(mirror::Object* obj, MemberOffset offset, bool /* is_static */) const
1071       ALWAYS_INLINE
1072       REQUIRES_SHARED(Locks::mutator_lock_)
1073       REQUIRES_SHARED(Locks::heap_bitmap_lock_) {
1074     DCHECK_EQ(collector_->RegionSpace()->RegionIdxForRef(obj), obj_region_idx_);
1075     DCHECK(kHandleInterRegionRefs || collector_->immune_spaces_.ContainsObject(obj));
1076     mirror::Object* ref =
1077             obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(offset);
1078     // TODO(lokeshgidra): Remove the following condition once b/173676071 is fixed.
1079     if (UNLIKELY(ref == nullptr && offset == mirror::Object::ClassOffset())) {
1080       // It has been verified as a race condition (see b/173676071)! After a small
1081       // wait when we reload the class pointer, it turns out to be a valid class
1082       // object. So as a workaround, we can continue execution and log an error
1083       // that this happened.
1084       for (size_t i = 0; i < 1000; i++) {
1085         // Wait for 1ms at a time. Don't wait for more than 1 second in total.
1086         usleep(1000);
1087         ref = obj->GetClass<kVerifyNone, kWithoutReadBarrier>();
1088         if (ref != nullptr) {
1089           LOG(ERROR) << "klass pointer for obj: "
1090                      << obj << " (" << mirror::Object::PrettyTypeOf(obj)
1091                      << ") found to be null first. Reloading after a small wait fetched klass: "
1092                      << ref << " (" << mirror::Object::PrettyTypeOf(ref) << ")";
1093           break;
1094         }
1095       }
1096 
1097       if (UNLIKELY(ref == nullptr)) {
1098         // It must be heap corruption. Remove memory protection and dump data.
1099         collector_->region_space_->Unprotect();
1100         LOG(FATAL_WITHOUT_ABORT) << "klass pointer for ref: " << obj << " found to be null.";
1101         collector_->heap_->GetVerification()->LogHeapCorruption(obj, offset, ref, /* fatal */ true);
1102       }
1103     }
1104     CheckReference(ref);
1105   }
1106 
operator ()(ObjPtr<mirror::Class> klass,ObjPtr<mirror::Reference> ref) const1107   void operator()(ObjPtr<mirror::Class> klass, ObjPtr<mirror::Reference> ref) const
1108       REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
1109     DCHECK(klass->IsTypeOfReferenceClass());
1110     // If the referent is not null, then we must re-visit the object during
1111     // copying phase to enqueue it for delayed processing and setting
1112     // read-barrier state to gray to ensure that call to GetReferent() triggers
1113     // the read-barrier. We use same data structure that is used to remember
1114     // objects with inter-region refs for this purpose too.
1115     if (kHandleInterRegionRefs
1116         && !contains_inter_region_idx_
1117         && ref->AsReference()->GetReferent<kWithoutReadBarrier>() != nullptr) {
1118       contains_inter_region_idx_ = true;
1119     }
1120   }
1121 
VisitRootIfNonNull(mirror::CompressedReference<mirror::Object> * root) const1122   void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
1123       ALWAYS_INLINE
1124       REQUIRES_SHARED(Locks::mutator_lock_) {
1125     if (!root->IsNull()) {
1126       VisitRoot(root);
1127     }
1128   }
1129 
VisitRoot(mirror::CompressedReference<mirror::Object> * root) const1130   void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
1131       ALWAYS_INLINE
1132       REQUIRES_SHARED(Locks::mutator_lock_) {
1133     CheckReference(root->AsMirrorPtr());
1134   }
1135 
ContainsInterRegionRefs() const1136   bool ContainsInterRegionRefs() const ALWAYS_INLINE REQUIRES_SHARED(Locks::mutator_lock_) {
1137     return contains_inter_region_idx_;
1138   }
1139 
1140  private:
CheckReference(mirror::Object * ref) const1141   void CheckReference(mirror::Object* ref) const
1142       REQUIRES_SHARED(Locks::mutator_lock_) {
1143     if (ref == nullptr) {
1144       // Nothing to do.
1145       return;
1146     }
1147     if (!collector_->TestAndSetMarkBitForRef(ref)) {
1148       collector_->PushOntoLocalMarkStack(ref);
1149     }
1150     if (kHandleInterRegionRefs && !contains_inter_region_idx_) {
1151       size_t ref_region_idx = collector_->RegionSpace()->RegionIdxForRef(ref);
1152       // If a region-space object refers to an outside object, we will have a
1153       // mismatch of region idx, but the object need not be re-visited in
1154       // copying phase.
1155       if (ref_region_idx != static_cast<size_t>(-1) && obj_region_idx_ != ref_region_idx) {
1156         contains_inter_region_idx_ = true;
1157       }
1158     }
1159   }
1160 
1161   ConcurrentCopying* const collector_;
1162   const size_t obj_region_idx_;
1163   mutable bool contains_inter_region_idx_;
1164 };
1165 
AddLiveBytesAndScanRef(mirror::Object * ref)1166 void ConcurrentCopying::AddLiveBytesAndScanRef(mirror::Object* ref) {
1167   DCHECK(ref != nullptr);
1168   DCHECK(!immune_spaces_.ContainsObject(ref));
1169   DCHECK(TestMarkBitmapForRef(ref));
1170   size_t obj_region_idx = static_cast<size_t>(-1);
1171   if (LIKELY(region_space_->HasAddress(ref))) {
1172     obj_region_idx = region_space_->RegionIdxForRefUnchecked(ref);
1173     // Add live bytes to the corresponding region
1174     if (!region_space_->IsRegionNewlyAllocated(obj_region_idx)) {
1175       // Newly Allocated regions are always chosen for evacuation. So no need
1176       // to update live_bytes_.
1177       size_t obj_size = ref->SizeOf<kDefaultVerifyFlags>();
1178       size_t alloc_size = RoundUp(obj_size, space::RegionSpace::kAlignment);
1179       region_space_->AddLiveBytes(ref, alloc_size);
1180     }
1181   }
1182   ComputeLiveBytesAndMarkRefFieldsVisitor</*kHandleInterRegionRefs*/ true>
1183       visitor(this, obj_region_idx);
1184   ref->VisitReferences</*kVisitNativeRoots=*/ true, kDefaultVerifyFlags, kWithoutReadBarrier>(
1185       visitor, visitor);
1186   // Mark the corresponding card dirty if the object contains any
1187   // inter-region reference.
1188   if (visitor.ContainsInterRegionRefs()) {
1189     if (obj_region_idx == static_cast<size_t>(-1)) {
1190       // If an inter-region ref has been found in a non-region-space, then it
1191       // must be non-moving-space. This is because this function cannot be
1192       // called on a immune-space object, and a large-object-space object has
1193       // only class object reference, which is either in some immune-space, or
1194       // in non-moving-space.
1195       DCHECK(heap_->non_moving_space_->HasAddress(ref));
1196       non_moving_space_inter_region_bitmap_.Set(ref);
1197     } else {
1198       region_space_inter_region_bitmap_.Set(ref);
1199     }
1200   }
1201 }
1202 
1203 template <bool kAtomic>
TestAndSetMarkBitForRef(mirror::Object * ref)1204 bool ConcurrentCopying::TestAndSetMarkBitForRef(mirror::Object* ref) {
1205   accounting::ContinuousSpaceBitmap* bitmap = nullptr;
1206   accounting::LargeObjectBitmap* los_bitmap = nullptr;
1207   if (LIKELY(region_space_->HasAddress(ref))) {
1208     bitmap = region_space_bitmap_;
1209   } else if (heap_->GetNonMovingSpace()->HasAddress(ref)) {
1210     bitmap = heap_->GetNonMovingSpace()->GetMarkBitmap();
1211   } else if (immune_spaces_.ContainsObject(ref)) {
1212     // References to immune space objects are always live.
1213     DCHECK(heap_mark_bitmap_->GetContinuousSpaceBitmap(ref)->Test(ref));
1214     return true;
1215   } else {
1216     // Should be a large object. Must be page aligned and the LOS must exist.
1217     if (kIsDebugBuild
1218         && (!IsAligned<kPageSize>(ref) || heap_->GetLargeObjectsSpace() == nullptr)) {
1219       // It must be heap corruption. Remove memory protection and dump data.
1220       region_space_->Unprotect();
1221       heap_->GetVerification()->LogHeapCorruption(/* obj */ nullptr,
1222                                                   MemberOffset(0),
1223                                                   ref,
1224                                                   /* fatal */ true);
1225     }
1226     los_bitmap = heap_->GetLargeObjectsSpace()->GetMarkBitmap();
1227   }
1228   if (kAtomic) {
1229     return (bitmap != nullptr) ? bitmap->AtomicTestAndSet(ref) : los_bitmap->AtomicTestAndSet(ref);
1230   } else {
1231     return (bitmap != nullptr) ? bitmap->Set(ref) : los_bitmap->Set(ref);
1232   }
1233 }
1234 
TestMarkBitmapForRef(mirror::Object * ref)1235 bool ConcurrentCopying::TestMarkBitmapForRef(mirror::Object* ref) {
1236   if (LIKELY(region_space_->HasAddress(ref))) {
1237     return region_space_bitmap_->Test(ref);
1238   } else if (heap_->GetNonMovingSpace()->HasAddress(ref)) {
1239     return heap_->GetNonMovingSpace()->GetMarkBitmap()->Test(ref);
1240   } else if (immune_spaces_.ContainsObject(ref)) {
1241     // References to immune space objects are always live.
1242     DCHECK(heap_mark_bitmap_->GetContinuousSpaceBitmap(ref)->Test(ref));
1243     return true;
1244   } else {
1245     // Should be a large object. Must be page aligned and the LOS must exist.
1246     if (kIsDebugBuild
1247         && (!IsAligned<kPageSize>(ref) || heap_->GetLargeObjectsSpace() == nullptr)) {
1248       // It must be heap corruption. Remove memory protection and dump data.
1249       region_space_->Unprotect();
1250       heap_->GetVerification()->LogHeapCorruption(/* obj */ nullptr,
1251                                                   MemberOffset(0),
1252                                                   ref,
1253                                                   /* fatal */ true);
1254     }
1255     return heap_->GetLargeObjectsSpace()->GetMarkBitmap()->Test(ref);
1256   }
1257 }
1258 
PushOntoLocalMarkStack(mirror::Object * ref)1259 void ConcurrentCopying::PushOntoLocalMarkStack(mirror::Object* ref) {
1260   if (kIsDebugBuild) {
1261     Thread *self = Thread::Current();
1262     DCHECK_EQ(thread_running_gc_, self);
1263     DCHECK(self->GetThreadLocalMarkStack() == nullptr);
1264   }
1265   DCHECK_EQ(mark_stack_mode_.load(std::memory_order_relaxed), kMarkStackModeThreadLocal);
1266   if (UNLIKELY(gc_mark_stack_->IsFull())) {
1267     ExpandGcMarkStack();
1268   }
1269   gc_mark_stack_->PushBack(ref);
1270 }
1271 
ProcessMarkStackForMarkingAndComputeLiveBytes()1272 void ConcurrentCopying::ProcessMarkStackForMarkingAndComputeLiveBytes() {
1273   // Process thread-local mark stack containing thread roots
1274   ProcessThreadLocalMarkStacks(/* disable_weak_ref_access */ false,
1275                                /* checkpoint_callback */ nullptr,
1276                                [this] (mirror::Object* ref)
1277                                    REQUIRES_SHARED(Locks::mutator_lock_) {
1278                                  AddLiveBytesAndScanRef(ref);
1279                                });
1280   {
1281     MutexLock mu(thread_running_gc_, mark_stack_lock_);
1282     CHECK(revoked_mark_stacks_.empty());
1283     CHECK_EQ(pooled_mark_stacks_.size(), kMarkStackPoolSize);
1284   }
1285 
1286   while (!gc_mark_stack_->IsEmpty()) {
1287     mirror::Object* ref = gc_mark_stack_->PopBack();
1288     AddLiveBytesAndScanRef(ref);
1289   }
1290 }
1291 
1292 class ConcurrentCopying::ImmuneSpaceCaptureRefsVisitor {
1293  public:
ImmuneSpaceCaptureRefsVisitor(ConcurrentCopying * cc)1294   explicit ImmuneSpaceCaptureRefsVisitor(ConcurrentCopying* cc) : collector_(cc) {}
1295 
operator ()(mirror::Object * obj) const1296   ALWAYS_INLINE void operator()(mirror::Object* obj) const REQUIRES_SHARED(Locks::mutator_lock_) {
1297     ComputeLiveBytesAndMarkRefFieldsVisitor</*kHandleInterRegionRefs*/ false>
1298         visitor(collector_, /*obj_region_idx*/ static_cast<size_t>(-1));
1299     obj->VisitReferences</*kVisitNativeRoots=*/true, kDefaultVerifyFlags, kWithoutReadBarrier>(
1300         visitor, visitor);
1301   }
1302 
Callback(mirror::Object * obj,void * arg)1303   static void Callback(mirror::Object* obj, void* arg) REQUIRES_SHARED(Locks::mutator_lock_) {
1304     reinterpret_cast<ImmuneSpaceCaptureRefsVisitor*>(arg)->operator()(obj);
1305   }
1306 
1307  private:
1308   ConcurrentCopying* const collector_;
1309 };
1310 
1311 /* Invariants for two-phase CC
1312  * ===========================
1313  * A) Definitions
1314  * ---------------
1315  * 1) Black: marked in bitmap, rb_state is non-gray, and not in mark stack
1316  * 2) Black-clean: marked in bitmap, and corresponding card is clean/aged
1317  * 3) Black-dirty: marked in bitmap, and corresponding card is dirty
1318  * 4) Gray: marked in bitmap, and exists in mark stack
1319  * 5) Gray-dirty: marked in bitmap, rb_state is gray, corresponding card is
1320  *    dirty, and exists in mark stack
1321  * 6) White: unmarked in bitmap, rb_state is non-gray, and not in mark stack
1322  *
1323  * B) Before marking phase
1324  * -----------------------
1325  * 1) All objects are white
1326  * 2) Cards are either clean or aged (cannot be asserted without a STW pause)
1327  * 3) Mark bitmap is cleared
1328  * 4) Mark stack is empty
1329  *
1330  * C) During marking phase
1331  * ------------------------
1332  * 1) If a black object holds an inter-region or white reference, then its
1333  *    corresponding card is dirty. In other words, it changes from being
1334  *    black-clean to black-dirty
1335  * 2) No black-clean object points to a white object
1336  *
1337  * D) After marking phase
1338  * -----------------------
1339  * 1) There are no gray objects
1340  * 2) All newly allocated objects are in from space
1341  * 3) No white object can be reachable, directly or otherwise, from a
1342  *    black-clean object
1343  *
1344  * E) During copying phase
1345  * ------------------------
1346  * 1) Mutators cannot observe white and black-dirty objects
1347  * 2) New allocations are in to-space (newly allocated regions are part of to-space)
1348  * 3) An object in mark stack must have its rb_state = Gray
1349  *
1350  * F) During card table scan
1351  * --------------------------
1352  * 1) Referents corresponding to root references are gray or in to-space
1353  * 2) Every path from an object that is read or written by a mutator during
1354  *    this period to a dirty black object goes through some gray object.
1355  *    Mutators preserve this by graying black objects as needed during this
1356  *    period. Ensures that a mutator never encounters a black dirty object.
1357  *
1358  * G) After card table scan
1359  * ------------------------
1360  * 1) There are no black-dirty objects
1361  * 2) Referents corresponding to root references are gray, black-clean or in
1362  *    to-space
1363  *
1364  * H) After copying phase
1365  * -----------------------
1366  * 1) Mark stack is empty
1367  * 2) No references into evacuated from-space
1368  * 3) No reference to an object which is unmarked and is also not in newly
1369  *    allocated region. In other words, no reference to white objects.
1370 */
1371 
MarkingPhase()1372 void ConcurrentCopying::MarkingPhase() {
1373   TimingLogger::ScopedTiming split("MarkingPhase", GetTimings());
1374   if (kVerboseMode) {
1375     LOG(INFO) << "GC MarkingPhase";
1376   }
1377   accounting::CardTable* const card_table = heap_->GetCardTable();
1378   Thread* const self = Thread::Current();
1379   CHECK_EQ(self, thread_running_gc_);
1380   // Clear live_bytes_ of every non-free region, except the ones that are newly
1381   // allocated.
1382   region_space_->SetAllRegionLiveBytesZero();
1383   if (kIsDebugBuild) {
1384     region_space_->AssertAllRegionLiveBytesZeroOrCleared();
1385   }
1386   // Scan immune spaces
1387   {
1388     TimingLogger::ScopedTiming split2("ScanImmuneSpaces", GetTimings());
1389     for (auto& space : immune_spaces_.GetSpaces()) {
1390       DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
1391       accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
1392       accounting::ModUnionTable* table = heap_->FindModUnionTableFromSpace(space);
1393       ImmuneSpaceCaptureRefsVisitor visitor(this);
1394       if (table != nullptr) {
1395         table->VisitObjects(ImmuneSpaceCaptureRefsVisitor::Callback, &visitor);
1396       } else {
1397         WriterMutexLock rmu(Thread::Current(), *Locks::heap_bitmap_lock_);
1398         card_table->Scan<false>(
1399             live_bitmap,
1400             space->Begin(),
1401             space->Limit(),
1402             visitor,
1403             accounting::CardTable::kCardDirty - 1);
1404       }
1405     }
1406   }
1407   // Scan runtime roots
1408   {
1409     TimingLogger::ScopedTiming split2("VisitConcurrentRoots", GetTimings());
1410     CaptureRootsForMarkingVisitor visitor(this, self);
1411     Runtime::Current()->VisitConcurrentRoots(&visitor, kVisitRootFlagAllRoots);
1412   }
1413   {
1414     // TODO: don't visit the transaction roots if it's not active.
1415     TimingLogger::ScopedTiming split2("VisitNonThreadRoots", GetTimings());
1416     CaptureRootsForMarkingVisitor visitor(this, self);
1417     Runtime::Current()->VisitNonThreadRoots(&visitor);
1418   }
1419   // Capture thread roots
1420   CaptureThreadRootsForMarking();
1421   // Process mark stack
1422   ProcessMarkStackForMarkingAndComputeLiveBytes();
1423 
1424   if (kVerboseMode) {
1425     LOG(INFO) << "GC end of MarkingPhase";
1426   }
1427 }
1428 
1429 template <bool kNoUnEvac>
ScanDirtyObject(mirror::Object * obj)1430 void ConcurrentCopying::ScanDirtyObject(mirror::Object* obj) {
1431   Scan<kNoUnEvac>(obj);
1432   // Set the read-barrier state of a reference-type object to gray if its
1433   // referent is not marked yet. This is to ensure that if GetReferent() is
1434   // called, it triggers the read-barrier to process the referent before use.
1435   if (UNLIKELY((obj->GetClass<kVerifyNone, kWithoutReadBarrier>()->IsTypeOfReferenceClass()))) {
1436     mirror::Object* referent =
1437         obj->AsReference<kVerifyNone, kWithoutReadBarrier>()->GetReferent<kWithoutReadBarrier>();
1438     if (referent != nullptr && !IsInToSpace(referent)) {
1439       obj->AtomicSetReadBarrierState(ReadBarrier::NonGrayState(), ReadBarrier::GrayState());
1440     }
1441   }
1442 }
1443 
1444 // Concurrently mark roots that are guarded by read barriers and process the mark stack.
CopyingPhase()1445 void ConcurrentCopying::CopyingPhase() {
1446   TimingLogger::ScopedTiming split("CopyingPhase", GetTimings());
1447   if (kVerboseMode) {
1448     LOG(INFO) << "GC CopyingPhase";
1449   }
1450   Thread* self = Thread::Current();
1451   accounting::CardTable* const card_table = heap_->GetCardTable();
1452   if (kIsDebugBuild) {
1453     MutexLock mu(self, *Locks::thread_list_lock_);
1454     CHECK(weak_ref_access_enabled_);
1455   }
1456 
1457   // Scan immune spaces.
1458   // Update all the fields in the immune spaces first without graying the objects so that we
1459   // minimize dirty pages in the immune spaces. Note mutators can concurrently access and gray some
1460   // of the objects.
1461   if (kUseBakerReadBarrier) {
1462     gc_grays_immune_objects_ = false;
1463   }
1464   if (use_generational_cc_) {
1465     if (kVerboseMode) {
1466       LOG(INFO) << "GC ScanCardsForSpace";
1467     }
1468     TimingLogger::ScopedTiming split2("ScanCardsForSpace", GetTimings());
1469     WriterMutexLock rmu(Thread::Current(), *Locks::heap_bitmap_lock_);
1470     CHECK(!done_scanning_.load(std::memory_order_relaxed));
1471     if (kIsDebugBuild) {
1472       // Leave some time for mutators to race ahead to try and find races between the GC card
1473       // scanning and mutators reading references.
1474       usleep(10 * 1000);
1475     }
1476     for (space::ContinuousSpace* space : GetHeap()->GetContinuousSpaces()) {
1477       if (space->IsImageSpace() || space->IsZygoteSpace()) {
1478         // Image and zygote spaces are already handled since we gray the objects in the pause.
1479         continue;
1480       }
1481       // Scan all of the objects on dirty cards in unevac from space, and non moving space. These
1482       // are from previous GCs (or from marking phase of 2-phase full GC) and may reference things
1483       // in the from space.
1484       //
1485       // Note that we do not need to process the large-object space (the only discontinuous space)
1486       // as it contains only large string objects and large primitive array objects, that have no
1487       // reference to other objects, except their class. There is no need to scan these large
1488       // objects, as the String class and the primitive array classes are expected to never move
1489       // during a collection:
1490       // - In the case where we run with a boot image, these classes are part of the image space,
1491       //   which is an immune space.
1492       // - In the case where we run without a boot image, these classes are allocated in the
1493       //   non-moving space (see art::ClassLinker::InitWithoutImage).
1494       card_table->Scan<false>(
1495           space->GetMarkBitmap(),
1496           space->Begin(),
1497           space->End(),
1498           [this, space](mirror::Object* obj)
1499               REQUIRES(Locks::heap_bitmap_lock_)
1500               REQUIRES_SHARED(Locks::mutator_lock_) {
1501             // TODO: This code may be refactored to avoid scanning object while
1502             // done_scanning_ is false by setting rb_state to gray, and pushing the
1503             // object on mark stack. However, it will also require clearing the
1504             // corresponding mark-bit and, for region space objects,
1505             // decrementing the object's size from the corresponding region's
1506             // live_bytes.
1507             if (young_gen_) {
1508               // Don't push or gray unevac refs.
1509               if (kIsDebugBuild && space == region_space_) {
1510                 // We may get unevac large objects.
1511                 if (!region_space_->IsInUnevacFromSpace(obj)) {
1512                   CHECK(region_space_bitmap_->Test(obj));
1513                   region_space_->DumpRegionForObject(LOG_STREAM(FATAL_WITHOUT_ABORT), obj);
1514                   LOG(FATAL) << "Scanning " << obj << " not in unevac space";
1515                 }
1516               }
1517               ScanDirtyObject</*kNoUnEvac*/ true>(obj);
1518             } else if (space != region_space_) {
1519               DCHECK(space == heap_->non_moving_space_);
1520               // We need to process un-evac references as they may be unprocessed,
1521               // if they skipped the marking phase due to heap mutation.
1522               ScanDirtyObject</*kNoUnEvac*/ false>(obj);
1523               non_moving_space_inter_region_bitmap_.Clear(obj);
1524             } else if (region_space_->IsInUnevacFromSpace(obj)) {
1525               ScanDirtyObject</*kNoUnEvac*/ false>(obj);
1526               region_space_inter_region_bitmap_.Clear(obj);
1527             }
1528           },
1529           accounting::CardTable::kCardAged);
1530 
1531       if (!young_gen_) {
1532         auto visitor = [this](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1533                          // We don't need to process un-evac references as any unprocessed
1534                          // ones will be taken care of in the card-table scan above.
1535                          ScanDirtyObject</*kNoUnEvac*/ true>(obj);
1536                        };
1537         if (space == region_space_) {
1538           region_space_->ScanUnevacFromSpace(&region_space_inter_region_bitmap_, visitor);
1539         } else {
1540           DCHECK(space == heap_->non_moving_space_);
1541           non_moving_space_inter_region_bitmap_.VisitMarkedRange(
1542               reinterpret_cast<uintptr_t>(space->Begin()),
1543               reinterpret_cast<uintptr_t>(space->End()),
1544               visitor);
1545         }
1546       }
1547     }
1548     // Done scanning unevac space.
1549     done_scanning_.store(true, std::memory_order_release);
1550     // NOTE: inter-region-ref bitmaps can be cleared here to release memory, if needed.
1551     // Currently we do it in ReclaimPhase().
1552     if (kVerboseMode) {
1553       LOG(INFO) << "GC end of ScanCardsForSpace";
1554     }
1555   }
1556   {
1557     // For a sticky-bit collection, this phase needs to be after the card scanning since the
1558     // mutator may read an unevac space object out of an image object. If the image object is no
1559     // longer gray it will trigger a read barrier for the unevac space object.
1560     TimingLogger::ScopedTiming split2("ScanImmuneSpaces", GetTimings());
1561     for (auto& space : immune_spaces_.GetSpaces()) {
1562       DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
1563       accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
1564       accounting::ModUnionTable* table = heap_->FindModUnionTableFromSpace(space);
1565       ImmuneSpaceScanObjVisitor visitor(this);
1566       if (kUseBakerReadBarrier && kGrayDirtyImmuneObjects && table != nullptr) {
1567         table->VisitObjects(ImmuneSpaceScanObjVisitor::Callback, &visitor);
1568       } else {
1569         WriterMutexLock rmu(Thread::Current(), *Locks::heap_bitmap_lock_);
1570         card_table->Scan<false>(
1571             live_bitmap,
1572             space->Begin(),
1573             space->Limit(),
1574             visitor,
1575             accounting::CardTable::kCardDirty - 1);
1576       }
1577     }
1578   }
1579   if (kUseBakerReadBarrier) {
1580     // This release fence makes the field updates in the above loop visible before allowing mutator
1581     // getting access to immune objects without graying it first.
1582     updated_all_immune_objects_.store(true, std::memory_order_release);
1583     // Now "un-gray" (conceptually blacken) immune objects concurrently accessed and grayed by
1584     // mutators. We can't do this in the above loop because we would incorrectly disable the read
1585     // barrier by un-graying (conceptually blackening) an object which may point to an unscanned,
1586     // white object, breaking the to-space invariant (a mutator shall never observe a from-space
1587     // (white) object).
1588     //
1589     // Make sure no mutators are in the middle of marking an immune object before un-graying
1590     // (blackening) immune objects.
1591     IssueEmptyCheckpoint();
1592     MutexLock mu(Thread::Current(), immune_gray_stack_lock_);
1593     if (kVerboseMode) {
1594       LOG(INFO) << "immune gray stack size=" << immune_gray_stack_.size();
1595     }
1596     for (mirror::Object* obj : immune_gray_stack_) {
1597       DCHECK_EQ(obj->GetReadBarrierState(), ReadBarrier::GrayState());
1598       bool success = obj->AtomicSetReadBarrierState(ReadBarrier::GrayState(),
1599                                                     ReadBarrier::NonGrayState());
1600       DCHECK(success);
1601     }
1602     immune_gray_stack_.clear();
1603   }
1604 
1605   {
1606     TimingLogger::ScopedTiming split2("VisitConcurrentRoots", GetTimings());
1607     Runtime::Current()->VisitConcurrentRoots(this, kVisitRootFlagAllRoots);
1608   }
1609   {
1610     // TODO: don't visit the transaction roots if it's not active.
1611     TimingLogger::ScopedTiming split5("VisitNonThreadRoots", GetTimings());
1612     Runtime::Current()->VisitNonThreadRoots(this);
1613   }
1614 
1615   {
1616     TimingLogger::ScopedTiming split7("ProcessMarkStack", GetTimings());
1617     // We transition through three mark stack modes (thread-local, shared, GC-exclusive). The
1618     // primary reasons are the fact that we need to use a checkpoint to process thread-local mark
1619     // stacks, but after we disable weak refs accesses, we can't use a checkpoint due to a deadlock
1620     // issue because running threads potentially blocking at WaitHoldingLocks, and that once we
1621     // reach the point where we process weak references, we can avoid using a lock when accessing
1622     // the GC mark stack, which makes mark stack processing more efficient.
1623 
1624     // Process the mark stack once in the thread local stack mode. This marks most of the live
1625     // objects, aside from weak ref accesses with read barriers (Reference::GetReferent() and system
1626     // weaks) that may happen concurrently while we processing the mark stack and newly mark/gray
1627     // objects and push refs on the mark stack.
1628     ProcessMarkStack();
1629     // Switch to the shared mark stack mode. That is, revoke and process thread-local mark stacks
1630     // for the last time before transitioning to the shared mark stack mode, which would process new
1631     // refs that may have been concurrently pushed onto the mark stack during the ProcessMarkStack()
1632     // call above. At the same time, disable weak ref accesses using a per-thread flag. It's
1633     // important to do these together in a single checkpoint so that we can ensure that mutators
1634     // won't newly gray objects and push new refs onto the mark stack due to weak ref accesses and
1635     // mutators safely transition to the shared mark stack mode (without leaving unprocessed refs on
1636     // the thread-local mark stacks), without a race. This is why we use a thread-local weak ref
1637     // access flag Thread::tls32_.weak_ref_access_enabled_ instead of the global ones.
1638     SwitchToSharedMarkStackMode();
1639     CHECK(!self->GetWeakRefAccessEnabled());
1640     // Now that weak refs accesses are disabled, once we exhaust the shared mark stack again here
1641     // (which may be non-empty if there were refs found on thread-local mark stacks during the above
1642     // SwitchToSharedMarkStackMode() call), we won't have new refs to process, that is, mutators
1643     // (via read barriers) have no way to produce any more refs to process. Marking converges once
1644     // before we process weak refs below.
1645     ProcessMarkStack();
1646     CheckEmptyMarkStack();
1647     // Switch to the GC exclusive mark stack mode so that we can process the mark stack without a
1648     // lock from this point on.
1649     SwitchToGcExclusiveMarkStackMode();
1650     CheckEmptyMarkStack();
1651     if (kVerboseMode) {
1652       LOG(INFO) << "ProcessReferences";
1653     }
1654     // Process weak references. This may produce new refs to process and have them processed via
1655     // ProcessMarkStack (in the GC exclusive mark stack mode).
1656     ProcessReferences(self);
1657     CheckEmptyMarkStack();
1658     if (kVerboseMode) {
1659       LOG(INFO) << "SweepSystemWeaks";
1660     }
1661     SweepSystemWeaks(self);
1662     if (kVerboseMode) {
1663       LOG(INFO) << "SweepSystemWeaks done";
1664     }
1665     // Process the mark stack here one last time because the above SweepSystemWeaks() call may have
1666     // marked some objects (strings alive) as hash_set::Erase() can call the hash function for
1667     // arbitrary elements in the weak intern table in InternTable::Table::SweepWeaks().
1668     ProcessMarkStack();
1669     CheckEmptyMarkStack();
1670     // Re-enable weak ref accesses.
1671     ReenableWeakRefAccess(self);
1672     // Free data for class loaders that we unloaded.
1673     Runtime::Current()->GetClassLinker()->CleanupClassLoaders();
1674     // Marking is done. Disable marking.
1675     DisableMarking();
1676     CheckEmptyMarkStack();
1677   }
1678 
1679   if (kIsDebugBuild) {
1680     MutexLock mu(self, *Locks::thread_list_lock_);
1681     CHECK(weak_ref_access_enabled_);
1682   }
1683   if (kVerboseMode) {
1684     LOG(INFO) << "GC end of CopyingPhase";
1685   }
1686 }
1687 
ReenableWeakRefAccess(Thread * self)1688 void ConcurrentCopying::ReenableWeakRefAccess(Thread* self) {
1689   if (kVerboseMode) {
1690     LOG(INFO) << "ReenableWeakRefAccess";
1691   }
1692   // Iterate all threads (don't need to or can't use a checkpoint) and re-enable weak ref access.
1693   {
1694     MutexLock mu(self, *Locks::thread_list_lock_);
1695     weak_ref_access_enabled_ = true;  // This is for new threads.
1696     std::list<Thread*> thread_list = Runtime::Current()->GetThreadList()->GetList();
1697     for (Thread* thread : thread_list) {
1698       thread->SetWeakRefAccessEnabled(true);
1699     }
1700   }
1701   // Unblock blocking threads.
1702   GetHeap()->GetReferenceProcessor()->BroadcastForSlowPath(self);
1703   Runtime::Current()->BroadcastForNewSystemWeaks();
1704 }
1705 
1706 class ConcurrentCopying::DisableMarkingCheckpoint : public Closure {
1707  public:
DisableMarkingCheckpoint(ConcurrentCopying * concurrent_copying)1708   explicit DisableMarkingCheckpoint(ConcurrentCopying* concurrent_copying)
1709       : concurrent_copying_(concurrent_copying) {
1710   }
1711 
Run(Thread * thread)1712   void Run(Thread* thread) override NO_THREAD_SAFETY_ANALYSIS {
1713     // Note: self is not necessarily equal to thread since thread may be suspended.
1714     Thread* self = Thread::Current();
1715     DCHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
1716         << thread->GetState() << " thread " << thread << " self " << self;
1717     // Disable the thread-local is_gc_marking flag.
1718     // Note a thread that has just started right before this checkpoint may have already this flag
1719     // set to false, which is ok.
1720     thread->SetIsGcMarkingAndUpdateEntrypoints(false);
1721     // If thread is a running mutator, then act on behalf of the garbage collector.
1722     // See the code in ThreadList::RunCheckpoint.
1723     concurrent_copying_->GetBarrier().Pass(self);
1724   }
1725 
1726  private:
1727   ConcurrentCopying* const concurrent_copying_;
1728 };
1729 
1730 class ConcurrentCopying::DisableMarkingCallback : public Closure {
1731  public:
DisableMarkingCallback(ConcurrentCopying * concurrent_copying)1732   explicit DisableMarkingCallback(ConcurrentCopying* concurrent_copying)
1733       : concurrent_copying_(concurrent_copying) {
1734   }
1735 
Run(Thread * self ATTRIBUTE_UNUSED)1736   void Run(Thread* self ATTRIBUTE_UNUSED) override REQUIRES(Locks::thread_list_lock_) {
1737     // This needs to run under the thread_list_lock_ critical section in ThreadList::RunCheckpoint()
1738     // to avoid a race with ThreadList::Register().
1739     CHECK(concurrent_copying_->is_marking_);
1740     concurrent_copying_->is_marking_ = false;
1741     if (kUseBakerReadBarrier && kGrayDirtyImmuneObjects) {
1742       CHECK(concurrent_copying_->is_using_read_barrier_entrypoints_);
1743       concurrent_copying_->is_using_read_barrier_entrypoints_ = false;
1744     } else {
1745       CHECK(!concurrent_copying_->is_using_read_barrier_entrypoints_);
1746     }
1747   }
1748 
1749  private:
1750   ConcurrentCopying* const concurrent_copying_;
1751 };
1752 
IssueDisableMarkingCheckpoint()1753 void ConcurrentCopying::IssueDisableMarkingCheckpoint() {
1754   Thread* self = Thread::Current();
1755   DisableMarkingCheckpoint check_point(this);
1756   ThreadList* thread_list = Runtime::Current()->GetThreadList();
1757   gc_barrier_->Init(self, 0);
1758   DisableMarkingCallback dmc(this);
1759   size_t barrier_count = thread_list->RunCheckpoint(&check_point, &dmc);
1760   // If there are no threads to wait which implies that all the checkpoint functions are finished,
1761   // then no need to release the mutator lock.
1762   if (barrier_count == 0) {
1763     return;
1764   }
1765   // Release locks then wait for all mutator threads to pass the barrier.
1766   Locks::mutator_lock_->SharedUnlock(self);
1767   {
1768     ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
1769     gc_barrier_->Increment(self, barrier_count);
1770   }
1771   Locks::mutator_lock_->SharedLock(self);
1772 }
1773 
DisableMarking()1774 void ConcurrentCopying::DisableMarking() {
1775   // Use a checkpoint to turn off the global is_marking and the thread-local is_gc_marking flags and
1776   // to ensure no threads are still in the middle of a read barrier which may have a from-space ref
1777   // cached in a local variable.
1778   IssueDisableMarkingCheckpoint();
1779   if (kUseTableLookupReadBarrier) {
1780     heap_->rb_table_->ClearAll();
1781     DCHECK(heap_->rb_table_->IsAllCleared());
1782   }
1783   is_mark_stack_push_disallowed_.store(1, std::memory_order_seq_cst);
1784   mark_stack_mode_.store(kMarkStackModeOff, std::memory_order_seq_cst);
1785 }
1786 
IssueEmptyCheckpoint()1787 void ConcurrentCopying::IssueEmptyCheckpoint() {
1788   Thread* self = Thread::Current();
1789   ThreadList* thread_list = Runtime::Current()->GetThreadList();
1790   // Release locks then wait for all mutator threads to pass the barrier.
1791   Locks::mutator_lock_->SharedUnlock(self);
1792   thread_list->RunEmptyCheckpoint();
1793   Locks::mutator_lock_->SharedLock(self);
1794 }
1795 
ExpandGcMarkStack()1796 void ConcurrentCopying::ExpandGcMarkStack() {
1797   DCHECK(gc_mark_stack_->IsFull());
1798   const size_t new_size = gc_mark_stack_->Capacity() * 2;
1799   std::vector<StackReference<mirror::Object>> temp(gc_mark_stack_->Begin(),
1800                                                    gc_mark_stack_->End());
1801   gc_mark_stack_->Resize(new_size);
1802   for (auto& ref : temp) {
1803     gc_mark_stack_->PushBack(ref.AsMirrorPtr());
1804   }
1805   DCHECK(!gc_mark_stack_->IsFull());
1806 }
1807 
PushOntoMarkStack(Thread * const self,mirror::Object * to_ref)1808 void ConcurrentCopying::PushOntoMarkStack(Thread* const self, mirror::Object* to_ref) {
1809   CHECK_EQ(is_mark_stack_push_disallowed_.load(std::memory_order_relaxed), 0)
1810       << " " << to_ref << " " << mirror::Object::PrettyTypeOf(to_ref);
1811   CHECK(thread_running_gc_ != nullptr);
1812   MarkStackMode mark_stack_mode = mark_stack_mode_.load(std::memory_order_relaxed);
1813   if (LIKELY(mark_stack_mode == kMarkStackModeThreadLocal)) {
1814     if (LIKELY(self == thread_running_gc_)) {
1815       // If GC-running thread, use the GC mark stack instead of a thread-local mark stack.
1816       CHECK(self->GetThreadLocalMarkStack() == nullptr);
1817       if (UNLIKELY(gc_mark_stack_->IsFull())) {
1818         ExpandGcMarkStack();
1819       }
1820       gc_mark_stack_->PushBack(to_ref);
1821     } else {
1822       // Otherwise, use a thread-local mark stack.
1823       accounting::AtomicStack<mirror::Object>* tl_mark_stack = self->GetThreadLocalMarkStack();
1824       if (UNLIKELY(tl_mark_stack == nullptr || tl_mark_stack->IsFull())) {
1825         MutexLock mu(self, mark_stack_lock_);
1826         // Get a new thread local mark stack.
1827         accounting::AtomicStack<mirror::Object>* new_tl_mark_stack;
1828         if (!pooled_mark_stacks_.empty()) {
1829           // Use a pooled mark stack.
1830           new_tl_mark_stack = pooled_mark_stacks_.back();
1831           pooled_mark_stacks_.pop_back();
1832         } else {
1833           // None pooled. Create a new one.
1834           new_tl_mark_stack =
1835               accounting::AtomicStack<mirror::Object>::Create(
1836                   "thread local mark stack", 4 * KB, 4 * KB);
1837         }
1838         DCHECK(new_tl_mark_stack != nullptr);
1839         DCHECK(new_tl_mark_stack->IsEmpty());
1840         new_tl_mark_stack->PushBack(to_ref);
1841         self->SetThreadLocalMarkStack(new_tl_mark_stack);
1842         if (tl_mark_stack != nullptr) {
1843           // Store the old full stack into a vector.
1844           revoked_mark_stacks_.push_back(tl_mark_stack);
1845         }
1846       } else {
1847         tl_mark_stack->PushBack(to_ref);
1848       }
1849     }
1850   } else if (mark_stack_mode == kMarkStackModeShared) {
1851     // Access the shared GC mark stack with a lock.
1852     MutexLock mu(self, mark_stack_lock_);
1853     if (UNLIKELY(gc_mark_stack_->IsFull())) {
1854       ExpandGcMarkStack();
1855     }
1856     gc_mark_stack_->PushBack(to_ref);
1857   } else {
1858     CHECK_EQ(static_cast<uint32_t>(mark_stack_mode),
1859              static_cast<uint32_t>(kMarkStackModeGcExclusive))
1860         << "ref=" << to_ref
1861         << " self->gc_marking=" << self->GetIsGcMarking()
1862         << " cc->is_marking=" << is_marking_;
1863     CHECK(self == thread_running_gc_)
1864         << "Only GC-running thread should access the mark stack "
1865         << "in the GC exclusive mark stack mode";
1866     // Access the GC mark stack without a lock.
1867     if (UNLIKELY(gc_mark_stack_->IsFull())) {
1868       ExpandGcMarkStack();
1869     }
1870     gc_mark_stack_->PushBack(to_ref);
1871   }
1872 }
1873 
GetAllocationStack()1874 accounting::ObjectStack* ConcurrentCopying::GetAllocationStack() {
1875   return heap_->allocation_stack_.get();
1876 }
1877 
GetLiveStack()1878 accounting::ObjectStack* ConcurrentCopying::GetLiveStack() {
1879   return heap_->live_stack_.get();
1880 }
1881 
1882 // The following visitors are used to verify that there's no references to the from-space left after
1883 // marking.
1884 class ConcurrentCopying::VerifyNoFromSpaceRefsVisitor : public SingleRootVisitor {
1885  public:
VerifyNoFromSpaceRefsVisitor(ConcurrentCopying * collector)1886   explicit VerifyNoFromSpaceRefsVisitor(ConcurrentCopying* collector)
1887       : collector_(collector) {}
1888 
operator ()(mirror::Object * ref,MemberOffset offset=MemberOffset (0),mirror::Object * holder=nullptr) const1889   void operator()(mirror::Object* ref,
1890                   MemberOffset offset = MemberOffset(0),
1891                   mirror::Object* holder = nullptr) const
1892       REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
1893     if (ref == nullptr) {
1894       // OK.
1895       return;
1896     }
1897     collector_->AssertToSpaceInvariant(holder, offset, ref);
1898     if (kUseBakerReadBarrier) {
1899       CHECK_EQ(ref->GetReadBarrierState(), ReadBarrier::NonGrayState())
1900           << "Ref " << ref << " " << ref->PrettyTypeOf() << " has gray rb_state";
1901     }
1902   }
1903 
VisitRoot(mirror::Object * root,const RootInfo & info ATTRIBUTE_UNUSED)1904   void VisitRoot(mirror::Object* root, const RootInfo& info ATTRIBUTE_UNUSED)
1905       override REQUIRES_SHARED(Locks::mutator_lock_) {
1906     DCHECK(root != nullptr);
1907     operator()(root);
1908   }
1909 
1910  private:
1911   ConcurrentCopying* const collector_;
1912 };
1913 
1914 class ConcurrentCopying::VerifyNoFromSpaceRefsFieldVisitor {
1915  public:
VerifyNoFromSpaceRefsFieldVisitor(ConcurrentCopying * collector)1916   explicit VerifyNoFromSpaceRefsFieldVisitor(ConcurrentCopying* collector)
1917       : collector_(collector) {}
1918 
operator ()(ObjPtr<mirror::Object> obj,MemberOffset offset,bool is_static ATTRIBUTE_UNUSED) const1919   void operator()(ObjPtr<mirror::Object> obj,
1920                   MemberOffset offset,
1921                   bool is_static ATTRIBUTE_UNUSED) const
1922       REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
1923     mirror::Object* ref =
1924         obj->GetFieldObject<mirror::Object, kDefaultVerifyFlags, kWithoutReadBarrier>(offset);
1925     VerifyNoFromSpaceRefsVisitor visitor(collector_);
1926     visitor(ref, offset, obj.Ptr());
1927   }
operator ()(ObjPtr<mirror::Class> klass,ObjPtr<mirror::Reference> ref) const1928   void operator()(ObjPtr<mirror::Class> klass,
1929                   ObjPtr<mirror::Reference> ref) const
1930       REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
1931     CHECK(klass->IsTypeOfReferenceClass());
1932     this->operator()(ref, mirror::Reference::ReferentOffset(), false);
1933   }
1934 
VisitRootIfNonNull(mirror::CompressedReference<mirror::Object> * root) const1935   void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
1936       REQUIRES_SHARED(Locks::mutator_lock_) {
1937     if (!root->IsNull()) {
1938       VisitRoot(root);
1939     }
1940   }
1941 
VisitRoot(mirror::CompressedReference<mirror::Object> * root) const1942   void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
1943       REQUIRES_SHARED(Locks::mutator_lock_) {
1944     VerifyNoFromSpaceRefsVisitor visitor(collector_);
1945     visitor(root->AsMirrorPtr());
1946   }
1947 
1948  private:
1949   ConcurrentCopying* const collector_;
1950 };
1951 
1952 // Verify there's no from-space references left after the marking phase.
VerifyNoFromSpaceReferences()1953 void ConcurrentCopying::VerifyNoFromSpaceReferences() {
1954   Thread* self = Thread::Current();
1955   DCHECK(Locks::mutator_lock_->IsExclusiveHeld(self));
1956   // Verify all threads have is_gc_marking to be false
1957   {
1958     MutexLock mu(self, *Locks::thread_list_lock_);
1959     std::list<Thread*> thread_list = Runtime::Current()->GetThreadList()->GetList();
1960     for (Thread* thread : thread_list) {
1961       CHECK(!thread->GetIsGcMarking());
1962     }
1963   }
1964 
1965   auto verify_no_from_space_refs_visitor = [&](mirror::Object* obj)
1966       REQUIRES_SHARED(Locks::mutator_lock_) {
1967     CHECK(obj != nullptr);
1968     space::RegionSpace* region_space = RegionSpace();
1969     CHECK(!region_space->IsInFromSpace(obj)) << "Scanning object " << obj << " in from space";
1970     VerifyNoFromSpaceRefsFieldVisitor visitor(this);
1971     obj->VisitReferences</*kVisitNativeRoots=*/true, kDefaultVerifyFlags, kWithoutReadBarrier>(
1972         visitor,
1973         visitor);
1974     if (kUseBakerReadBarrier) {
1975       CHECK_EQ(obj->GetReadBarrierState(), ReadBarrier::NonGrayState())
1976           << "obj=" << obj << " has gray rb_state " << obj->GetReadBarrierState();
1977     }
1978   };
1979   // Roots.
1980   {
1981     ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1982     VerifyNoFromSpaceRefsVisitor ref_visitor(this);
1983     Runtime::Current()->VisitRoots(&ref_visitor);
1984   }
1985   // The to-space.
1986   region_space_->WalkToSpace(verify_no_from_space_refs_visitor);
1987   // Non-moving spaces.
1988   {
1989     WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1990     heap_->GetMarkBitmap()->Visit(verify_no_from_space_refs_visitor);
1991   }
1992   // The alloc stack.
1993   {
1994     VerifyNoFromSpaceRefsVisitor ref_visitor(this);
1995     for (auto* it = heap_->allocation_stack_->Begin(), *end = heap_->allocation_stack_->End();
1996         it < end; ++it) {
1997       mirror::Object* const obj = it->AsMirrorPtr();
1998       if (obj != nullptr && obj->GetClass() != nullptr) {
1999         // TODO: need to call this only if obj is alive?
2000         ref_visitor(obj);
2001         verify_no_from_space_refs_visitor(obj);
2002       }
2003     }
2004   }
2005   // TODO: LOS. But only refs in LOS are classes.
2006 }
2007 
2008 // The following visitors are used to assert the to-space invariant.
2009 class ConcurrentCopying::AssertToSpaceInvariantFieldVisitor {
2010  public:
AssertToSpaceInvariantFieldVisitor(ConcurrentCopying * collector)2011   explicit AssertToSpaceInvariantFieldVisitor(ConcurrentCopying* collector)
2012       : collector_(collector) {}
2013 
operator ()(ObjPtr<mirror::Object> obj,MemberOffset offset,bool is_static ATTRIBUTE_UNUSED) const2014   void operator()(ObjPtr<mirror::Object> obj,
2015                   MemberOffset offset,
2016                   bool is_static ATTRIBUTE_UNUSED) const
2017       REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
2018     mirror::Object* ref =
2019         obj->GetFieldObject<mirror::Object, kDefaultVerifyFlags, kWithoutReadBarrier>(offset);
2020     collector_->AssertToSpaceInvariant(obj.Ptr(), offset, ref);
2021   }
operator ()(ObjPtr<mirror::Class> klass,ObjPtr<mirror::Reference> ref ATTRIBUTE_UNUSED) const2022   void operator()(ObjPtr<mirror::Class> klass, ObjPtr<mirror::Reference> ref ATTRIBUTE_UNUSED) const
2023       REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
2024     CHECK(klass->IsTypeOfReferenceClass());
2025   }
2026 
VisitRootIfNonNull(mirror::CompressedReference<mirror::Object> * root) const2027   void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
2028       REQUIRES_SHARED(Locks::mutator_lock_) {
2029     if (!root->IsNull()) {
2030       VisitRoot(root);
2031     }
2032   }
2033 
VisitRoot(mirror::CompressedReference<mirror::Object> * root) const2034   void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
2035       REQUIRES_SHARED(Locks::mutator_lock_) {
2036     mirror::Object* ref = root->AsMirrorPtr();
2037     collector_->AssertToSpaceInvariant(/* obj */ nullptr, MemberOffset(0), ref);
2038   }
2039 
2040  private:
2041   ConcurrentCopying* const collector_;
2042 };
2043 
RevokeThreadLocalMarkStacks(bool disable_weak_ref_access,Closure * checkpoint_callback)2044 void ConcurrentCopying::RevokeThreadLocalMarkStacks(bool disable_weak_ref_access,
2045                                                     Closure* checkpoint_callback) {
2046   Thread* self = Thread::Current();
2047   RevokeThreadLocalMarkStackCheckpoint check_point(this, disable_weak_ref_access);
2048   ThreadList* thread_list = Runtime::Current()->GetThreadList();
2049   gc_barrier_->Init(self, 0);
2050   size_t barrier_count = thread_list->RunCheckpoint(&check_point, checkpoint_callback);
2051   // If there are no threads to wait which implys that all the checkpoint functions are finished,
2052   // then no need to release the mutator lock.
2053   if (barrier_count == 0) {
2054     return;
2055   }
2056   Locks::mutator_lock_->SharedUnlock(self);
2057   {
2058     ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
2059     gc_barrier_->Increment(self, barrier_count);
2060   }
2061   Locks::mutator_lock_->SharedLock(self);
2062 }
2063 
RevokeThreadLocalMarkStack(Thread * thread)2064 void ConcurrentCopying::RevokeThreadLocalMarkStack(Thread* thread) {
2065   Thread* self = Thread::Current();
2066   CHECK_EQ(self, thread);
2067   MutexLock mu(self, mark_stack_lock_);
2068   accounting::AtomicStack<mirror::Object>* tl_mark_stack = thread->GetThreadLocalMarkStack();
2069   if (tl_mark_stack != nullptr) {
2070     CHECK(is_marking_);
2071     revoked_mark_stacks_.push_back(tl_mark_stack);
2072     thread->SetThreadLocalMarkStack(nullptr);
2073   }
2074 }
2075 
ProcessMarkStack()2076 void ConcurrentCopying::ProcessMarkStack() {
2077   if (kVerboseMode) {
2078     LOG(INFO) << "ProcessMarkStack. ";
2079   }
2080   bool empty_prev = false;
2081   while (true) {
2082     bool empty = ProcessMarkStackOnce();
2083     if (empty_prev && empty) {
2084       // Saw empty mark stack for a second time, done.
2085       break;
2086     }
2087     empty_prev = empty;
2088   }
2089 }
2090 
ProcessMarkStackOnce()2091 bool ConcurrentCopying::ProcessMarkStackOnce() {
2092   DCHECK(thread_running_gc_ != nullptr);
2093   Thread* const self = Thread::Current();
2094   DCHECK(self == thread_running_gc_);
2095   DCHECK(thread_running_gc_->GetThreadLocalMarkStack() == nullptr);
2096   size_t count = 0;
2097   MarkStackMode mark_stack_mode = mark_stack_mode_.load(std::memory_order_relaxed);
2098   if (mark_stack_mode == kMarkStackModeThreadLocal) {
2099     // Process the thread-local mark stacks and the GC mark stack.
2100     count += ProcessThreadLocalMarkStacks(/* disable_weak_ref_access= */ false,
2101                                           /* checkpoint_callback= */ nullptr,
2102                                           [this] (mirror::Object* ref)
2103                                               REQUIRES_SHARED(Locks::mutator_lock_) {
2104                                             ProcessMarkStackRef(ref);
2105                                           });
2106     while (!gc_mark_stack_->IsEmpty()) {
2107       mirror::Object* to_ref = gc_mark_stack_->PopBack();
2108       ProcessMarkStackRef(to_ref);
2109       ++count;
2110     }
2111     gc_mark_stack_->Reset();
2112   } else if (mark_stack_mode == kMarkStackModeShared) {
2113     // Do an empty checkpoint to avoid a race with a mutator preempted in the middle of a read
2114     // barrier but before pushing onto the mark stack. b/32508093. Note the weak ref access is
2115     // disabled at this point.
2116     IssueEmptyCheckpoint();
2117     // Process the shared GC mark stack with a lock.
2118     {
2119       MutexLock mu(thread_running_gc_, mark_stack_lock_);
2120       CHECK(revoked_mark_stacks_.empty());
2121       CHECK_EQ(pooled_mark_stacks_.size(), kMarkStackPoolSize);
2122     }
2123     while (true) {
2124       std::vector<mirror::Object*> refs;
2125       {
2126         // Copy refs with lock. Note the number of refs should be small.
2127         MutexLock mu(thread_running_gc_, mark_stack_lock_);
2128         if (gc_mark_stack_->IsEmpty()) {
2129           break;
2130         }
2131         for (StackReference<mirror::Object>* p = gc_mark_stack_->Begin();
2132              p != gc_mark_stack_->End(); ++p) {
2133           refs.push_back(p->AsMirrorPtr());
2134         }
2135         gc_mark_stack_->Reset();
2136       }
2137       for (mirror::Object* ref : refs) {
2138         ProcessMarkStackRef(ref);
2139         ++count;
2140       }
2141     }
2142   } else {
2143     CHECK_EQ(static_cast<uint32_t>(mark_stack_mode),
2144              static_cast<uint32_t>(kMarkStackModeGcExclusive));
2145     {
2146       MutexLock mu(thread_running_gc_, mark_stack_lock_);
2147       CHECK(revoked_mark_stacks_.empty());
2148       CHECK_EQ(pooled_mark_stacks_.size(), kMarkStackPoolSize);
2149     }
2150     // Process the GC mark stack in the exclusive mode. No need to take the lock.
2151     while (!gc_mark_stack_->IsEmpty()) {
2152       mirror::Object* to_ref = gc_mark_stack_->PopBack();
2153       ProcessMarkStackRef(to_ref);
2154       ++count;
2155     }
2156     gc_mark_stack_->Reset();
2157   }
2158 
2159   // Return true if the stack was empty.
2160   return count == 0;
2161 }
2162 
2163 template <typename Processor>
ProcessThreadLocalMarkStacks(bool disable_weak_ref_access,Closure * checkpoint_callback,const Processor & processor)2164 size_t ConcurrentCopying::ProcessThreadLocalMarkStacks(bool disable_weak_ref_access,
2165                                                        Closure* checkpoint_callback,
2166                                                        const Processor& processor) {
2167   // Run a checkpoint to collect all thread local mark stacks and iterate over them all.
2168   RevokeThreadLocalMarkStacks(disable_weak_ref_access, checkpoint_callback);
2169   if (disable_weak_ref_access) {
2170     CHECK_EQ(static_cast<uint32_t>(mark_stack_mode_.load(std::memory_order_relaxed)),
2171              static_cast<uint32_t>(kMarkStackModeShared));
2172   }
2173   size_t count = 0;
2174   std::vector<accounting::AtomicStack<mirror::Object>*> mark_stacks;
2175   {
2176     MutexLock mu(thread_running_gc_, mark_stack_lock_);
2177     // Make a copy of the mark stack vector.
2178     mark_stacks = revoked_mark_stacks_;
2179     revoked_mark_stacks_.clear();
2180   }
2181   for (accounting::AtomicStack<mirror::Object>* mark_stack : mark_stacks) {
2182     for (StackReference<mirror::Object>* p = mark_stack->Begin(); p != mark_stack->End(); ++p) {
2183       mirror::Object* to_ref = p->AsMirrorPtr();
2184       processor(to_ref);
2185       ++count;
2186     }
2187     {
2188       MutexLock mu(thread_running_gc_, mark_stack_lock_);
2189       if (pooled_mark_stacks_.size() >= kMarkStackPoolSize) {
2190         // The pool has enough. Delete it.
2191         delete mark_stack;
2192       } else {
2193         // Otherwise, put it into the pool for later reuse.
2194         mark_stack->Reset();
2195         pooled_mark_stacks_.push_back(mark_stack);
2196       }
2197     }
2198   }
2199   if (disable_weak_ref_access) {
2200     MutexLock mu(thread_running_gc_, mark_stack_lock_);
2201     CHECK(revoked_mark_stacks_.empty());
2202     CHECK_EQ(pooled_mark_stacks_.size(), kMarkStackPoolSize);
2203   }
2204   return count;
2205 }
2206 
ProcessMarkStackRef(mirror::Object * to_ref)2207 inline void ConcurrentCopying::ProcessMarkStackRef(mirror::Object* to_ref) {
2208   DCHECK(!region_space_->IsInFromSpace(to_ref));
2209   size_t obj_size = 0;
2210   space::RegionSpace::RegionType rtype = region_space_->GetRegionType(to_ref);
2211   if (kUseBakerReadBarrier) {
2212     DCHECK(to_ref->GetReadBarrierState() == ReadBarrier::GrayState())
2213         << " to_ref=" << to_ref
2214         << " rb_state=" << to_ref->GetReadBarrierState()
2215         << " is_marked=" << IsMarked(to_ref)
2216         << " type=" << to_ref->PrettyTypeOf()
2217         << " young_gen=" << std::boolalpha << young_gen_ << std::noboolalpha
2218         << " space=" << heap_->DumpSpaceNameFromAddress(to_ref)
2219         << " region_type=" << rtype
2220         // TODO: Temporary; remove this when this is no longer needed (b/116087961).
2221         << " runtime->sentinel=" << Runtime::Current()->GetSentinel().Read<kWithoutReadBarrier>();
2222   }
2223   bool add_to_live_bytes = false;
2224   // Invariant: There should be no object from a newly-allocated
2225   // region (either large or non-large) on the mark stack.
2226   DCHECK(!region_space_->IsInNewlyAllocatedRegion(to_ref)) << to_ref;
2227   bool perform_scan = false;
2228   switch (rtype) {
2229     case space::RegionSpace::RegionType::kRegionTypeUnevacFromSpace:
2230       // Mark the bitmap only in the GC thread here so that we don't need a CAS.
2231       if (!kUseBakerReadBarrier || !region_space_bitmap_->Set(to_ref)) {
2232         // It may be already marked if we accidentally pushed the same object twice due to the racy
2233         // bitmap read in MarkUnevacFromSpaceRegion.
2234         if (use_generational_cc_ && young_gen_) {
2235           CHECK(region_space_->IsLargeObject(to_ref));
2236           region_space_->ZeroLiveBytesForLargeObject(to_ref);
2237         }
2238         perform_scan = true;
2239         // Only add to the live bytes if the object was not already marked and we are not the young
2240         // GC.
2241         // Why add live bytes even after 2-phase GC?
2242         // We need to ensure that if there is a unevac region with any live
2243         // objects, then its live_bytes must be non-zero. Otherwise,
2244         // ClearFromSpace() will clear the region. Considering, that we may skip
2245         // live objects during marking phase of 2-phase GC, we have to take care
2246         // of such objects here.
2247         add_to_live_bytes = true;
2248       }
2249       break;
2250     case space::RegionSpace::RegionType::kRegionTypeToSpace:
2251       if (use_generational_cc_) {
2252         // Copied to to-space, set the bit so that the next GC can scan objects.
2253         region_space_bitmap_->Set(to_ref);
2254       }
2255       perform_scan = true;
2256       break;
2257     default:
2258       DCHECK(!region_space_->HasAddress(to_ref)) << to_ref;
2259       DCHECK(!immune_spaces_.ContainsObject(to_ref));
2260       // Non-moving or large-object space.
2261       if (kUseBakerReadBarrier) {
2262         accounting::ContinuousSpaceBitmap* mark_bitmap =
2263             heap_->GetNonMovingSpace()->GetMarkBitmap();
2264         const bool is_los = !mark_bitmap->HasAddress(to_ref);
2265         if (is_los) {
2266           if (!IsAligned<kPageSize>(to_ref)) {
2267             // Ref is a large object that is not aligned, it must be heap
2268             // corruption. Remove memory protection and dump data before
2269             // AtomicSetReadBarrierState since it will fault if the address is not
2270             // valid.
2271             region_space_->Unprotect();
2272             heap_->GetVerification()->LogHeapCorruption(/* obj */ nullptr,
2273                                                         MemberOffset(0),
2274                                                         to_ref,
2275                                                         /* fatal */ true);
2276           }
2277           DCHECK(heap_->GetLargeObjectsSpace())
2278               << "ref=" << to_ref
2279               << " doesn't belong to non-moving space and large object space doesn't exist";
2280           accounting::LargeObjectBitmap* los_bitmap =
2281               heap_->GetLargeObjectsSpace()->GetMarkBitmap();
2282           DCHECK(los_bitmap->HasAddress(to_ref));
2283           // Only the GC thread could be setting the LOS bit map hence doesn't
2284           // need to be atomically done.
2285           perform_scan = !los_bitmap->Set(to_ref);
2286         } else {
2287           // Only the GC thread could be setting the non-moving space bit map
2288           // hence doesn't need to be atomically done.
2289           perform_scan = !mark_bitmap->Set(to_ref);
2290         }
2291       } else {
2292         perform_scan = true;
2293       }
2294   }
2295   if (perform_scan) {
2296     obj_size = to_ref->SizeOf<kDefaultVerifyFlags>();
2297     if (use_generational_cc_ && young_gen_) {
2298       Scan<true>(to_ref, obj_size);
2299     } else {
2300       Scan<false>(to_ref, obj_size);
2301     }
2302   }
2303   if (kUseBakerReadBarrier) {
2304     DCHECK(to_ref->GetReadBarrierState() == ReadBarrier::GrayState())
2305         << " to_ref=" << to_ref
2306         << " rb_state=" << to_ref->GetReadBarrierState()
2307         << " is_marked=" << IsMarked(to_ref)
2308         << " type=" << to_ref->PrettyTypeOf()
2309         << " young_gen=" << std::boolalpha << young_gen_ << std::noboolalpha
2310         << " space=" << heap_->DumpSpaceNameFromAddress(to_ref)
2311         << " region_type=" << rtype
2312         // TODO: Temporary; remove this when this is no longer needed (b/116087961).
2313         << " runtime->sentinel=" << Runtime::Current()->GetSentinel().Read<kWithoutReadBarrier>();
2314   }
2315 #ifdef USE_BAKER_OR_BROOKS_READ_BARRIER
2316   mirror::Object* referent = nullptr;
2317   if (UNLIKELY((to_ref->GetClass<kVerifyNone, kWithoutReadBarrier>()->IsTypeOfReferenceClass() &&
2318                 (referent = to_ref->AsReference()->GetReferent<kWithoutReadBarrier>()) != nullptr &&
2319                 !IsInToSpace(referent)))) {
2320     // Leave this reference gray in the queue so that GetReferent() will trigger a read barrier. We
2321     // will change it to non-gray later in ReferenceQueue::DisableReadBarrierForReference.
2322     DCHECK(to_ref->AsReference()->GetPendingNext() != nullptr)
2323         << "Left unenqueued ref gray " << to_ref;
2324   } else {
2325     // We may occasionally leave a reference non-gray in the queue if its referent happens to be
2326     // concurrently marked after the Scan() call above has enqueued the Reference, in which case the
2327     // above IsInToSpace() evaluates to true and we change the color from gray to non-gray here in
2328     // this else block.
2329     if (kUseBakerReadBarrier) {
2330       bool success = to_ref->AtomicSetReadBarrierState<std::memory_order_release>(
2331           ReadBarrier::GrayState(),
2332           ReadBarrier::NonGrayState());
2333       DCHECK(success) << "Must succeed as we won the race.";
2334     }
2335   }
2336 #else
2337   DCHECK(!kUseBakerReadBarrier);
2338 #endif
2339 
2340   if (add_to_live_bytes) {
2341     // Add to the live bytes per unevacuated from-space. Note this code is always run by the
2342     // GC-running thread (no synchronization required).
2343     DCHECK(region_space_bitmap_->Test(to_ref));
2344     if (obj_size == 0) {
2345       obj_size = to_ref->SizeOf<kDefaultVerifyFlags>();
2346     }
2347     region_space_->AddLiveBytes(to_ref, RoundUp(obj_size, space::RegionSpace::kAlignment));
2348   }
2349   if (ReadBarrier::kEnableToSpaceInvariantChecks) {
2350     CHECK(to_ref != nullptr);
2351     space::RegionSpace* region_space = RegionSpace();
2352     CHECK(!region_space->IsInFromSpace(to_ref)) << "Scanning object " << to_ref << " in from space";
2353     AssertToSpaceInvariant(nullptr, MemberOffset(0), to_ref);
2354     AssertToSpaceInvariantFieldVisitor visitor(this);
2355     to_ref->VisitReferences</*kVisitNativeRoots=*/true, kDefaultVerifyFlags, kWithoutReadBarrier>(
2356         visitor,
2357         visitor);
2358   }
2359 }
2360 
2361 class ConcurrentCopying::DisableWeakRefAccessCallback : public Closure {
2362  public:
DisableWeakRefAccessCallback(ConcurrentCopying * concurrent_copying)2363   explicit DisableWeakRefAccessCallback(ConcurrentCopying* concurrent_copying)
2364       : concurrent_copying_(concurrent_copying) {
2365   }
2366 
Run(Thread * self ATTRIBUTE_UNUSED)2367   void Run(Thread* self ATTRIBUTE_UNUSED) override REQUIRES(Locks::thread_list_lock_) {
2368     // This needs to run under the thread_list_lock_ critical section in ThreadList::RunCheckpoint()
2369     // to avoid a deadlock b/31500969.
2370     CHECK(concurrent_copying_->weak_ref_access_enabled_);
2371     concurrent_copying_->weak_ref_access_enabled_ = false;
2372   }
2373 
2374  private:
2375   ConcurrentCopying* const concurrent_copying_;
2376 };
2377 
SwitchToSharedMarkStackMode()2378 void ConcurrentCopying::SwitchToSharedMarkStackMode() {
2379   Thread* self = Thread::Current();
2380   DCHECK(thread_running_gc_ != nullptr);
2381   DCHECK(self == thread_running_gc_);
2382   DCHECK(thread_running_gc_->GetThreadLocalMarkStack() == nullptr);
2383   MarkStackMode before_mark_stack_mode = mark_stack_mode_.load(std::memory_order_relaxed);
2384   CHECK_EQ(static_cast<uint32_t>(before_mark_stack_mode),
2385            static_cast<uint32_t>(kMarkStackModeThreadLocal));
2386   mark_stack_mode_.store(kMarkStackModeShared, std::memory_order_relaxed);
2387   DisableWeakRefAccessCallback dwrac(this);
2388   // Process the thread local mark stacks one last time after switching to the shared mark stack
2389   // mode and disable weak ref accesses.
2390   ProcessThreadLocalMarkStacks(/* disable_weak_ref_access= */ true,
2391                                &dwrac,
2392                                [this] (mirror::Object* ref)
2393                                    REQUIRES_SHARED(Locks::mutator_lock_) {
2394                                  ProcessMarkStackRef(ref);
2395                                });
2396   if (kVerboseMode) {
2397     LOG(INFO) << "Switched to shared mark stack mode and disabled weak ref access";
2398   }
2399 }
2400 
SwitchToGcExclusiveMarkStackMode()2401 void ConcurrentCopying::SwitchToGcExclusiveMarkStackMode() {
2402   Thread* self = Thread::Current();
2403   DCHECK(thread_running_gc_ != nullptr);
2404   DCHECK(self == thread_running_gc_);
2405   DCHECK(thread_running_gc_->GetThreadLocalMarkStack() == nullptr);
2406   MarkStackMode before_mark_stack_mode = mark_stack_mode_.load(std::memory_order_relaxed);
2407   CHECK_EQ(static_cast<uint32_t>(before_mark_stack_mode),
2408            static_cast<uint32_t>(kMarkStackModeShared));
2409   mark_stack_mode_.store(kMarkStackModeGcExclusive, std::memory_order_relaxed);
2410   QuasiAtomic::ThreadFenceForConstructor();
2411   if (kVerboseMode) {
2412     LOG(INFO) << "Switched to GC exclusive mark stack mode";
2413   }
2414 }
2415 
CheckEmptyMarkStack()2416 void ConcurrentCopying::CheckEmptyMarkStack() {
2417   Thread* self = Thread::Current();
2418   DCHECK(thread_running_gc_ != nullptr);
2419   DCHECK(self == thread_running_gc_);
2420   DCHECK(thread_running_gc_->GetThreadLocalMarkStack() == nullptr);
2421   MarkStackMode mark_stack_mode = mark_stack_mode_.load(std::memory_order_relaxed);
2422   if (mark_stack_mode == kMarkStackModeThreadLocal) {
2423     // Thread-local mark stack mode.
2424     RevokeThreadLocalMarkStacks(false, nullptr);
2425     MutexLock mu(thread_running_gc_, mark_stack_lock_);
2426     if (!revoked_mark_stacks_.empty()) {
2427       for (accounting::AtomicStack<mirror::Object>* mark_stack : revoked_mark_stacks_) {
2428         while (!mark_stack->IsEmpty()) {
2429           mirror::Object* obj = mark_stack->PopBack();
2430           if (kUseBakerReadBarrier) {
2431             uint32_t rb_state = obj->GetReadBarrierState();
2432             LOG(INFO) << "On mark queue : " << obj << " " << obj->PrettyTypeOf() << " rb_state="
2433                       << rb_state << " is_marked=" << IsMarked(obj);
2434           } else {
2435             LOG(INFO) << "On mark queue : " << obj << " " << obj->PrettyTypeOf()
2436                       << " is_marked=" << IsMarked(obj);
2437           }
2438         }
2439       }
2440       LOG(FATAL) << "mark stack is not empty";
2441     }
2442   } else {
2443     // Shared, GC-exclusive, or off.
2444     MutexLock mu(thread_running_gc_, mark_stack_lock_);
2445     CHECK(gc_mark_stack_->IsEmpty());
2446     CHECK(revoked_mark_stacks_.empty());
2447     CHECK_EQ(pooled_mark_stacks_.size(), kMarkStackPoolSize);
2448   }
2449 }
2450 
SweepSystemWeaks(Thread * self)2451 void ConcurrentCopying::SweepSystemWeaks(Thread* self) {
2452   TimingLogger::ScopedTiming split("SweepSystemWeaks", GetTimings());
2453   ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
2454   Runtime::Current()->SweepSystemWeaks(this);
2455 }
2456 
Sweep(bool swap_bitmaps)2457 void ConcurrentCopying::Sweep(bool swap_bitmaps) {
2458   if (use_generational_cc_ && young_gen_) {
2459     // Only sweep objects on the live stack.
2460     SweepArray(heap_->GetLiveStack(), /* swap_bitmaps= */ false);
2461   } else {
2462     {
2463       TimingLogger::ScopedTiming t("MarkStackAsLive", GetTimings());
2464       accounting::ObjectStack* live_stack = heap_->GetLiveStack();
2465       if (kEnableFromSpaceAccountingCheck) {
2466         // Ensure that nobody inserted items in the live stack after we swapped the stacks.
2467         CHECK_GE(live_stack_freeze_size_, live_stack->Size());
2468       }
2469       heap_->MarkAllocStackAsLive(live_stack);
2470       live_stack->Reset();
2471     }
2472     CheckEmptyMarkStack();
2473     TimingLogger::ScopedTiming split("Sweep", GetTimings());
2474     for (const auto& space : GetHeap()->GetContinuousSpaces()) {
2475       if (space->IsContinuousMemMapAllocSpace() && space != region_space_
2476           && !immune_spaces_.ContainsSpace(space)) {
2477         space::ContinuousMemMapAllocSpace* alloc_space = space->AsContinuousMemMapAllocSpace();
2478         TimingLogger::ScopedTiming split2(
2479             alloc_space->IsZygoteSpace() ? "SweepZygoteSpace" : "SweepAllocSpace", GetTimings());
2480         RecordFree(alloc_space->Sweep(swap_bitmaps));
2481       }
2482     }
2483     SweepLargeObjects(swap_bitmaps);
2484   }
2485 }
2486 
2487 // Copied and adapted from MarkSweep::SweepArray.
SweepArray(accounting::ObjectStack * allocations,bool swap_bitmaps)2488 void ConcurrentCopying::SweepArray(accounting::ObjectStack* allocations, bool swap_bitmaps) {
2489   // This method is only used when Generational CC collection is enabled.
2490   DCHECK(use_generational_cc_);
2491   CheckEmptyMarkStack();
2492   TimingLogger::ScopedTiming t("SweepArray", GetTimings());
2493   Thread* self = Thread::Current();
2494   mirror::Object** chunk_free_buffer = reinterpret_cast<mirror::Object**>(
2495       sweep_array_free_buffer_mem_map_.BaseBegin());
2496   size_t chunk_free_pos = 0;
2497   ObjectBytePair freed;
2498   ObjectBytePair freed_los;
2499   // How many objects are left in the array, modified after each space is swept.
2500   StackReference<mirror::Object>* objects = allocations->Begin();
2501   size_t count = allocations->Size();
2502   // Start by sweeping the continuous spaces.
2503   for (space::ContinuousSpace* space : heap_->GetContinuousSpaces()) {
2504     if (!space->IsAllocSpace() ||
2505         space == region_space_ ||
2506         immune_spaces_.ContainsSpace(space) ||
2507         space->GetLiveBitmap() == nullptr) {
2508       continue;
2509     }
2510     space::AllocSpace* alloc_space = space->AsAllocSpace();
2511     accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
2512     accounting::ContinuousSpaceBitmap* mark_bitmap = space->GetMarkBitmap();
2513     if (swap_bitmaps) {
2514       std::swap(live_bitmap, mark_bitmap);
2515     }
2516     StackReference<mirror::Object>* out = objects;
2517     for (size_t i = 0; i < count; ++i) {
2518       mirror::Object* const obj = objects[i].AsMirrorPtr();
2519       if (kUseThreadLocalAllocationStack && obj == nullptr) {
2520         continue;
2521       }
2522       if (space->HasAddress(obj)) {
2523         // This object is in the space, remove it from the array and add it to the sweep buffer
2524         // if needed.
2525         if (!mark_bitmap->Test(obj)) {
2526           if (chunk_free_pos >= kSweepArrayChunkFreeSize) {
2527             TimingLogger::ScopedTiming t2("FreeList", GetTimings());
2528             freed.objects += chunk_free_pos;
2529             freed.bytes += alloc_space->FreeList(self, chunk_free_pos, chunk_free_buffer);
2530             chunk_free_pos = 0;
2531           }
2532           chunk_free_buffer[chunk_free_pos++] = obj;
2533         }
2534       } else {
2535         (out++)->Assign(obj);
2536       }
2537     }
2538     if (chunk_free_pos > 0) {
2539       TimingLogger::ScopedTiming t2("FreeList", GetTimings());
2540       freed.objects += chunk_free_pos;
2541       freed.bytes += alloc_space->FreeList(self, chunk_free_pos, chunk_free_buffer);
2542       chunk_free_pos = 0;
2543     }
2544     // All of the references which space contained are no longer in the allocation stack, update
2545     // the count.
2546     count = out - objects;
2547   }
2548   // Handle the large object space.
2549   space::LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
2550   if (large_object_space != nullptr) {
2551     accounting::LargeObjectBitmap* large_live_objects = large_object_space->GetLiveBitmap();
2552     accounting::LargeObjectBitmap* large_mark_objects = large_object_space->GetMarkBitmap();
2553     if (swap_bitmaps) {
2554       std::swap(large_live_objects, large_mark_objects);
2555     }
2556     for (size_t i = 0; i < count; ++i) {
2557       mirror::Object* const obj = objects[i].AsMirrorPtr();
2558       // Handle large objects.
2559       if (kUseThreadLocalAllocationStack && obj == nullptr) {
2560         continue;
2561       }
2562       if (!large_mark_objects->Test(obj)) {
2563         ++freed_los.objects;
2564         freed_los.bytes += large_object_space->Free(self, obj);
2565       }
2566     }
2567   }
2568   {
2569     TimingLogger::ScopedTiming t2("RecordFree", GetTimings());
2570     RecordFree(freed);
2571     RecordFreeLOS(freed_los);
2572     t2.NewTiming("ResetStack");
2573     allocations->Reset();
2574   }
2575   sweep_array_free_buffer_mem_map_.MadviseDontNeedAndZero();
2576 }
2577 
MarkZygoteLargeObjects()2578 void ConcurrentCopying::MarkZygoteLargeObjects() {
2579   TimingLogger::ScopedTiming split(__FUNCTION__, GetTimings());
2580   Thread* const self = Thread::Current();
2581   WriterMutexLock rmu(self, *Locks::heap_bitmap_lock_);
2582   space::LargeObjectSpace* const los = heap_->GetLargeObjectsSpace();
2583   if (los != nullptr) {
2584     // Pick the current live bitmap (mark bitmap if swapped).
2585     accounting::LargeObjectBitmap* const live_bitmap = los->GetLiveBitmap();
2586     accounting::LargeObjectBitmap* const mark_bitmap = los->GetMarkBitmap();
2587     // Walk through all of the objects and explicitly mark the zygote ones so they don't get swept.
2588     std::pair<uint8_t*, uint8_t*> range = los->GetBeginEndAtomic();
2589     live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(range.first),
2590                                   reinterpret_cast<uintptr_t>(range.second),
2591                                   [mark_bitmap, los, self](mirror::Object* obj)
2592         REQUIRES(Locks::heap_bitmap_lock_)
2593         REQUIRES_SHARED(Locks::mutator_lock_) {
2594       if (los->IsZygoteLargeObject(self, obj)) {
2595         mark_bitmap->Set(obj);
2596       }
2597     });
2598   }
2599 }
2600 
SweepLargeObjects(bool swap_bitmaps)2601 void ConcurrentCopying::SweepLargeObjects(bool swap_bitmaps) {
2602   TimingLogger::ScopedTiming split("SweepLargeObjects", GetTimings());
2603   if (heap_->GetLargeObjectsSpace() != nullptr) {
2604     RecordFreeLOS(heap_->GetLargeObjectsSpace()->Sweep(swap_bitmaps));
2605   }
2606 }
2607 
CaptureRssAtPeak()2608 void ConcurrentCopying::CaptureRssAtPeak() {
2609   using range_t = std::pair<void*, void*>;
2610   // This operation is expensive as several calls to mincore() are performed.
2611   // Also, this must be called before clearing regions in ReclaimPhase().
2612   // Therefore, we make it conditional on the flag that enables dumping GC
2613   // performance info on shutdown.
2614   if (Runtime::Current()->GetDumpGCPerformanceOnShutdown()) {
2615     std::list<range_t> gc_ranges;
2616     auto add_gc_range = [&gc_ranges](void* start, size_t size) {
2617       void* end = static_cast<char*>(start) + RoundUp(size, kPageSize);
2618       gc_ranges.emplace_back(range_t(start, end));
2619     };
2620 
2621     // region space
2622     DCHECK(IsAligned<kPageSize>(region_space_->Limit()));
2623     gc_ranges.emplace_back(range_t(region_space_->Begin(), region_space_->Limit()));
2624     // mark bitmap
2625     add_gc_range(region_space_bitmap_->Begin(), region_space_bitmap_->Size());
2626 
2627     // non-moving space
2628     {
2629       DCHECK(IsAligned<kPageSize>(heap_->non_moving_space_->Limit()));
2630       gc_ranges.emplace_back(range_t(heap_->non_moving_space_->Begin(),
2631                                      heap_->non_moving_space_->Limit()));
2632       // mark bitmap
2633       accounting::ContinuousSpaceBitmap *bitmap = heap_->non_moving_space_->GetMarkBitmap();
2634       add_gc_range(bitmap->Begin(), bitmap->Size());
2635       // live bitmap. Deal with bound bitmaps.
2636       ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
2637       if (heap_->non_moving_space_->HasBoundBitmaps()) {
2638         DCHECK_EQ(bitmap, heap_->non_moving_space_->GetLiveBitmap());
2639         bitmap = heap_->non_moving_space_->GetTempBitmap();
2640       } else {
2641         bitmap = heap_->non_moving_space_->GetLiveBitmap();
2642       }
2643       add_gc_range(bitmap->Begin(), bitmap->Size());
2644     }
2645     // large-object space
2646     if (heap_->GetLargeObjectsSpace()) {
2647       heap_->GetLargeObjectsSpace()->ForEachMemMap([&add_gc_range](const MemMap& map) {
2648         DCHECK(IsAligned<kPageSize>(map.BaseSize()));
2649         add_gc_range(map.BaseBegin(), map.BaseSize());
2650       });
2651       // mark bitmap
2652       accounting::LargeObjectBitmap* bitmap = heap_->GetLargeObjectsSpace()->GetMarkBitmap();
2653       add_gc_range(bitmap->Begin(), bitmap->Size());
2654       // live bitmap
2655       bitmap = heap_->GetLargeObjectsSpace()->GetLiveBitmap();
2656       add_gc_range(bitmap->Begin(), bitmap->Size());
2657     }
2658     // card table
2659     add_gc_range(heap_->GetCardTable()->MemMapBegin(), heap_->GetCardTable()->MemMapSize());
2660     // inter-region refs
2661     if (use_generational_cc_ && !young_gen_) {
2662       // region space
2663       add_gc_range(region_space_inter_region_bitmap_.Begin(),
2664                    region_space_inter_region_bitmap_.Size());
2665       // non-moving space
2666       add_gc_range(non_moving_space_inter_region_bitmap_.Begin(),
2667                    non_moving_space_inter_region_bitmap_.Size());
2668     }
2669     // Extract RSS using mincore(). Updates the cummulative RSS counter.
2670     ExtractRssFromMincore(&gc_ranges);
2671   }
2672 }
2673 
ReclaimPhase()2674 void ConcurrentCopying::ReclaimPhase() {
2675   TimingLogger::ScopedTiming split("ReclaimPhase", GetTimings());
2676   if (kVerboseMode) {
2677     LOG(INFO) << "GC ReclaimPhase";
2678   }
2679   Thread* self = Thread::Current();
2680 
2681   {
2682     // Double-check that the mark stack is empty.
2683     // Note: need to set this after VerifyNoFromSpaceRef().
2684     is_asserting_to_space_invariant_ = false;
2685     QuasiAtomic::ThreadFenceForConstructor();
2686     if (kVerboseMode) {
2687       LOG(INFO) << "Issue an empty check point. ";
2688     }
2689     IssueEmptyCheckpoint();
2690     // Disable the check.
2691     is_mark_stack_push_disallowed_.store(0, std::memory_order_seq_cst);
2692     if (kUseBakerReadBarrier) {
2693       updated_all_immune_objects_.store(false, std::memory_order_seq_cst);
2694     }
2695     CheckEmptyMarkStack();
2696   }
2697 
2698   // Capture RSS at the time when memory usage is at its peak. All GC related
2699   // memory ranges like java heap, card table, bitmap etc. are taken into
2700   // account.
2701   // TODO: We can fetch resident memory for region space directly by going
2702   // through list of allocated regions. This way we can avoid calling mincore on
2703   // the biggest memory range, thereby reducing the cost of this function.
2704   CaptureRssAtPeak();
2705 
2706   // Sweep the malloc spaces before clearing the from space since the memory tool mode might
2707   // access the object classes in the from space for dead objects.
2708   {
2709     WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
2710     Sweep(/* swap_bitmaps= */ false);
2711     SwapBitmaps();
2712     heap_->UnBindBitmaps();
2713 
2714     // The bitmap was cleared at the start of the GC, there is nothing we need to do here.
2715     DCHECK(region_space_bitmap_ != nullptr);
2716     region_space_bitmap_ = nullptr;
2717   }
2718 
2719 
2720   {
2721     // Record freed objects.
2722     TimingLogger::ScopedTiming split2("RecordFree", GetTimings());
2723     // Don't include thread-locals that are in the to-space.
2724     const uint64_t from_bytes = region_space_->GetBytesAllocatedInFromSpace();
2725     const uint64_t from_objects = region_space_->GetObjectsAllocatedInFromSpace();
2726     const uint64_t unevac_from_bytes = region_space_->GetBytesAllocatedInUnevacFromSpace();
2727     const uint64_t unevac_from_objects = region_space_->GetObjectsAllocatedInUnevacFromSpace();
2728     uint64_t to_bytes = bytes_moved_.load(std::memory_order_relaxed) + bytes_moved_gc_thread_;
2729     cumulative_bytes_moved_ += to_bytes;
2730     uint64_t to_objects = objects_moved_.load(std::memory_order_relaxed) + objects_moved_gc_thread_;
2731     cumulative_objects_moved_ += to_objects;
2732     if (kEnableFromSpaceAccountingCheck) {
2733       CHECK_EQ(from_space_num_objects_at_first_pause_, from_objects + unevac_from_objects);
2734       CHECK_EQ(from_space_num_bytes_at_first_pause_, from_bytes + unevac_from_bytes);
2735     }
2736     CHECK_LE(to_objects, from_objects);
2737     // to_bytes <= from_bytes is only approximately true, because objects expand a little when
2738     // copying to non-moving space in near-OOM situations.
2739     if (from_bytes > 0) {
2740       copied_live_bytes_ratio_sum_ += static_cast<float>(to_bytes) / from_bytes;
2741       gc_count_++;
2742     }
2743 
2744     // Cleared bytes and objects, populated by the call to RegionSpace::ClearFromSpace below.
2745     uint64_t cleared_bytes;
2746     uint64_t cleared_objects;
2747     {
2748       TimingLogger::ScopedTiming split4("ClearFromSpace", GetTimings());
2749       region_space_->ClearFromSpace(&cleared_bytes, &cleared_objects, /*clear_bitmap*/ !young_gen_);
2750       // `cleared_bytes` and `cleared_objects` may be greater than the from space equivalents since
2751       // RegionSpace::ClearFromSpace may clear empty unevac regions.
2752       CHECK_GE(cleared_bytes, from_bytes);
2753       CHECK_GE(cleared_objects, from_objects);
2754     }
2755     // freed_bytes could conceivably be negative if we fall back to nonmoving space and have to
2756     // pad to a larger size.
2757     int64_t freed_bytes = (int64_t)cleared_bytes - (int64_t)to_bytes;
2758     uint64_t freed_objects = cleared_objects - to_objects;
2759     if (kVerboseMode) {
2760       LOG(INFO) << "RecordFree:"
2761                 << " from_bytes=" << from_bytes << " from_objects=" << from_objects
2762                 << " unevac_from_bytes=" << unevac_from_bytes
2763                 << " unevac_from_objects=" << unevac_from_objects
2764                 << " to_bytes=" << to_bytes << " to_objects=" << to_objects
2765                 << " freed_bytes=" << freed_bytes << " freed_objects=" << freed_objects
2766                 << " from_space size=" << region_space_->FromSpaceSize()
2767                 << " unevac_from_space size=" << region_space_->UnevacFromSpaceSize()
2768                 << " to_space size=" << region_space_->ToSpaceSize();
2769       LOG(INFO) << "(before) num_bytes_allocated="
2770                 << heap_->num_bytes_allocated_.load();
2771     }
2772     RecordFree(ObjectBytePair(freed_objects, freed_bytes));
2773     GetCurrentIteration()->SetScannedBytes(bytes_scanned_);
2774     if (kVerboseMode) {
2775       LOG(INFO) << "(after) num_bytes_allocated="
2776                 << heap_->num_bytes_allocated_.load();
2777     }
2778 
2779     float reclaimed_bytes_ratio = static_cast<float>(freed_bytes) / num_bytes_allocated_before_gc_;
2780     reclaimed_bytes_ratio_sum_ += reclaimed_bytes_ratio;
2781   }
2782 
2783   CheckEmptyMarkStack();
2784 
2785   if (heap_->dump_region_info_after_gc_) {
2786     LOG(INFO) << "time=" << region_space_->Time();
2787     region_space_->DumpNonFreeRegions(LOG_STREAM(INFO));
2788   }
2789 
2790   if (kVerboseMode) {
2791     LOG(INFO) << "GC end of ReclaimPhase";
2792   }
2793 }
2794 
DumpReferenceInfo(mirror::Object * ref,const char * ref_name,const char * indent)2795 std::string ConcurrentCopying::DumpReferenceInfo(mirror::Object* ref,
2796                                                  const char* ref_name,
2797                                                  const char* indent) {
2798   std::ostringstream oss;
2799   oss << indent << heap_->GetVerification()->DumpObjectInfo(ref, ref_name) << '\n';
2800   if (ref != nullptr) {
2801     if (kUseBakerReadBarrier) {
2802       oss << indent << ref_name << "->GetMarkBit()=" << ref->GetMarkBit() << '\n';
2803       oss << indent << ref_name << "->GetReadBarrierState()=" << ref->GetReadBarrierState() << '\n';
2804     }
2805   }
2806   if (region_space_->HasAddress(ref)) {
2807     oss << indent << "Region containing " << ref_name << ":" << '\n';
2808     region_space_->DumpRegionForObject(oss, ref);
2809     if (region_space_bitmap_ != nullptr) {
2810       oss << indent << "region_space_bitmap_->Test(" << ref_name << ")="
2811           << std::boolalpha << region_space_bitmap_->Test(ref) << std::noboolalpha;
2812     }
2813   }
2814   return oss.str();
2815 }
2816 
DumpHeapReference(mirror::Object * obj,MemberOffset offset,mirror::Object * ref)2817 std::string ConcurrentCopying::DumpHeapReference(mirror::Object* obj,
2818                                                  MemberOffset offset,
2819                                                  mirror::Object* ref) {
2820   std::ostringstream oss;
2821   constexpr const char* kIndent = "  ";
2822   oss << kIndent << "Invalid reference: ref=" << ref
2823       << " referenced from: object=" << obj << " offset= " << offset << '\n';
2824   // Information about `obj`.
2825   oss << DumpReferenceInfo(obj, "obj", kIndent) << '\n';
2826   // Information about `ref`.
2827   oss << DumpReferenceInfo(ref, "ref", kIndent);
2828   return oss.str();
2829 }
2830 
AssertToSpaceInvariant(mirror::Object * obj,MemberOffset offset,mirror::Object * ref)2831 void ConcurrentCopying::AssertToSpaceInvariant(mirror::Object* obj,
2832                                                MemberOffset offset,
2833                                                mirror::Object* ref) {
2834   CHECK_EQ(heap_->collector_type_, kCollectorTypeCC) << static_cast<size_t>(heap_->collector_type_);
2835   if (is_asserting_to_space_invariant_) {
2836     if (ref == nullptr) {
2837       // OK.
2838       return;
2839     } else if (region_space_->HasAddress(ref)) {
2840       // Check to-space invariant in region space (moving space).
2841       using RegionType = space::RegionSpace::RegionType;
2842       space::RegionSpace::RegionType type = region_space_->GetRegionTypeUnsafe(ref);
2843       if (type == RegionType::kRegionTypeToSpace) {
2844         // OK.
2845         return;
2846       } else if (type == RegionType::kRegionTypeUnevacFromSpace) {
2847         if (!IsMarkedInUnevacFromSpace(ref)) {
2848           LOG(FATAL_WITHOUT_ABORT) << "Found unmarked reference in unevac from-space:";
2849           // Remove memory protection from the region space and log debugging information.
2850           region_space_->Unprotect();
2851           LOG(FATAL_WITHOUT_ABORT) << DumpHeapReference(obj, offset, ref);
2852           Thread::Current()->DumpJavaStack(LOG_STREAM(FATAL_WITHOUT_ABORT));
2853         }
2854         CHECK(IsMarkedInUnevacFromSpace(ref)) << ref;
2855      } else {
2856         // Not OK: either a from-space ref or a reference in an unused region.
2857         if (type == RegionType::kRegionTypeFromSpace) {
2858           LOG(FATAL_WITHOUT_ABORT) << "Found from-space reference:";
2859         } else {
2860           LOG(FATAL_WITHOUT_ABORT) << "Found reference in region with type " << type << ":";
2861         }
2862         // Remove memory protection from the region space and log debugging information.
2863         region_space_->Unprotect();
2864         LOG(FATAL_WITHOUT_ABORT) << DumpHeapReference(obj, offset, ref);
2865         if (obj != nullptr) {
2866           LogFromSpaceRefHolder(obj, offset);
2867           LOG(FATAL_WITHOUT_ABORT) << "UNEVAC " << region_space_->IsInUnevacFromSpace(obj) << " "
2868                                    << obj << " " << obj->GetMarkBit();
2869           if (region_space_->HasAddress(obj)) {
2870             region_space_->DumpRegionForObject(LOG_STREAM(FATAL_WITHOUT_ABORT), obj);
2871           }
2872           LOG(FATAL_WITHOUT_ABORT) << "CARD " << static_cast<size_t>(
2873               *Runtime::Current()->GetHeap()->GetCardTable()->CardFromAddr(
2874                   reinterpret_cast<uint8_t*>(obj)));
2875           if (region_space_->HasAddress(obj)) {
2876             LOG(FATAL_WITHOUT_ABORT) << "BITMAP " << region_space_bitmap_->Test(obj);
2877           } else {
2878             accounting::ContinuousSpaceBitmap* mark_bitmap =
2879                 heap_mark_bitmap_->GetContinuousSpaceBitmap(obj);
2880             if (mark_bitmap != nullptr) {
2881               LOG(FATAL_WITHOUT_ABORT) << "BITMAP " << mark_bitmap->Test(obj);
2882             } else {
2883               accounting::LargeObjectBitmap* los_bitmap =
2884                   heap_mark_bitmap_->GetLargeObjectBitmap(obj);
2885               LOG(FATAL_WITHOUT_ABORT) << "BITMAP " << los_bitmap->Test(obj);
2886             }
2887           }
2888         }
2889         ref->GetLockWord(false).Dump(LOG_STREAM(FATAL_WITHOUT_ABORT));
2890         LOG(FATAL_WITHOUT_ABORT) << "Non-free regions:";
2891         region_space_->DumpNonFreeRegions(LOG_STREAM(FATAL_WITHOUT_ABORT));
2892         PrintFileToLog("/proc/self/maps", LogSeverity::FATAL_WITHOUT_ABORT);
2893         MemMap::DumpMaps(LOG_STREAM(FATAL_WITHOUT_ABORT), /* terse= */ true);
2894         LOG(FATAL) << "Invalid reference " << ref
2895                    << " referenced from object " << obj << " at offset " << offset;
2896       }
2897     } else {
2898       // Check to-space invariant in non-moving space.
2899       AssertToSpaceInvariantInNonMovingSpace(obj, ref);
2900     }
2901   }
2902 }
2903 
2904 class RootPrinter {
2905  public:
RootPrinter()2906   RootPrinter() { }
2907 
2908   template <class MirrorType>
VisitRootIfNonNull(mirror::CompressedReference<MirrorType> * root)2909   ALWAYS_INLINE void VisitRootIfNonNull(mirror::CompressedReference<MirrorType>* root)
2910       REQUIRES_SHARED(Locks::mutator_lock_) {
2911     if (!root->IsNull()) {
2912       VisitRoot(root);
2913     }
2914   }
2915 
2916   template <class MirrorType>
VisitRoot(mirror::Object ** root)2917   void VisitRoot(mirror::Object** root)
2918       REQUIRES_SHARED(Locks::mutator_lock_) {
2919     LOG(FATAL_WITHOUT_ABORT) << "root=" << root << " ref=" << *root;
2920   }
2921 
2922   template <class MirrorType>
VisitRoot(mirror::CompressedReference<MirrorType> * root)2923   void VisitRoot(mirror::CompressedReference<MirrorType>* root)
2924       REQUIRES_SHARED(Locks::mutator_lock_) {
2925     LOG(FATAL_WITHOUT_ABORT) << "root=" << root << " ref=" << root->AsMirrorPtr();
2926   }
2927 };
2928 
DumpGcRoot(mirror::Object * ref)2929 std::string ConcurrentCopying::DumpGcRoot(mirror::Object* ref) {
2930   std::ostringstream oss;
2931   constexpr const char* kIndent = "  ";
2932   oss << kIndent << "Invalid GC root: ref=" << ref << '\n';
2933   // Information about `ref`.
2934   oss << DumpReferenceInfo(ref, "ref", kIndent);
2935   return oss.str();
2936 }
2937 
AssertToSpaceInvariant(GcRootSource * gc_root_source,mirror::Object * ref)2938 void ConcurrentCopying::AssertToSpaceInvariant(GcRootSource* gc_root_source,
2939                                                mirror::Object* ref) {
2940   CHECK_EQ(heap_->collector_type_, kCollectorTypeCC) << static_cast<size_t>(heap_->collector_type_);
2941   if (is_asserting_to_space_invariant_) {
2942     if (ref == nullptr) {
2943       // OK.
2944       return;
2945     } else if (region_space_->HasAddress(ref)) {
2946       // Check to-space invariant in region space (moving space).
2947       using RegionType = space::RegionSpace::RegionType;
2948       space::RegionSpace::RegionType type = region_space_->GetRegionTypeUnsafe(ref);
2949       if (type == RegionType::kRegionTypeToSpace) {
2950         // OK.
2951         return;
2952       } else if (type == RegionType::kRegionTypeUnevacFromSpace) {
2953         if (!IsMarkedInUnevacFromSpace(ref)) {
2954           LOG(FATAL_WITHOUT_ABORT) << "Found unmarked reference in unevac from-space:";
2955           // Remove memory protection from the region space and log debugging information.
2956           region_space_->Unprotect();
2957           LOG(FATAL_WITHOUT_ABORT) << DumpGcRoot(ref);
2958         }
2959         CHECK(IsMarkedInUnevacFromSpace(ref)) << ref;
2960       } else {
2961         // Not OK: either a from-space ref or a reference in an unused region.
2962         if (type == RegionType::kRegionTypeFromSpace) {
2963           LOG(FATAL_WITHOUT_ABORT) << "Found from-space reference:";
2964         } else {
2965           LOG(FATAL_WITHOUT_ABORT) << "Found reference in region with type " << type << ":";
2966         }
2967         // Remove memory protection from the region space and log debugging information.
2968         region_space_->Unprotect();
2969         LOG(FATAL_WITHOUT_ABORT) << DumpGcRoot(ref);
2970         if (gc_root_source == nullptr) {
2971           // No info.
2972         } else if (gc_root_source->HasArtField()) {
2973           ArtField* field = gc_root_source->GetArtField();
2974           LOG(FATAL_WITHOUT_ABORT) << "gc root in field " << field << " "
2975                                    << ArtField::PrettyField(field);
2976           RootPrinter root_printer;
2977           field->VisitRoots(root_printer);
2978         } else if (gc_root_source->HasArtMethod()) {
2979           ArtMethod* method = gc_root_source->GetArtMethod();
2980           LOG(FATAL_WITHOUT_ABORT) << "gc root in method " << method << " "
2981                                    << ArtMethod::PrettyMethod(method);
2982           RootPrinter root_printer;
2983           method->VisitRoots(root_printer, kRuntimePointerSize);
2984         }
2985         ref->GetLockWord(false).Dump(LOG_STREAM(FATAL_WITHOUT_ABORT));
2986         LOG(FATAL_WITHOUT_ABORT) << "Non-free regions:";
2987         region_space_->DumpNonFreeRegions(LOG_STREAM(FATAL_WITHOUT_ABORT));
2988         PrintFileToLog("/proc/self/maps", LogSeverity::FATAL_WITHOUT_ABORT);
2989         MemMap::DumpMaps(LOG_STREAM(FATAL_WITHOUT_ABORT), /* terse= */ true);
2990         LOG(FATAL) << "Invalid reference " << ref;
2991       }
2992     } else {
2993       // Check to-space invariant in non-moving space.
2994       AssertToSpaceInvariantInNonMovingSpace(/* obj= */ nullptr, ref);
2995     }
2996   }
2997 }
2998 
LogFromSpaceRefHolder(mirror::Object * obj,MemberOffset offset)2999 void ConcurrentCopying::LogFromSpaceRefHolder(mirror::Object* obj, MemberOffset offset) {
3000   if (kUseBakerReadBarrier) {
3001     LOG(INFO) << "holder=" << obj << " " << obj->PrettyTypeOf()
3002               << " holder rb_state=" << obj->GetReadBarrierState();
3003   } else {
3004     LOG(INFO) << "holder=" << obj << " " << obj->PrettyTypeOf();
3005   }
3006   if (region_space_->IsInFromSpace(obj)) {
3007     LOG(INFO) << "holder is in the from-space.";
3008   } else if (region_space_->IsInToSpace(obj)) {
3009     LOG(INFO) << "holder is in the to-space.";
3010   } else if (region_space_->IsInUnevacFromSpace(obj)) {
3011     LOG(INFO) << "holder is in the unevac from-space.";
3012     if (IsMarkedInUnevacFromSpace(obj)) {
3013       LOG(INFO) << "holder is marked in the region space bitmap.";
3014     } else {
3015       LOG(INFO) << "holder is not marked in the region space bitmap.";
3016     }
3017   } else {
3018     // In a non-moving space.
3019     if (immune_spaces_.ContainsObject(obj)) {
3020       LOG(INFO) << "holder is in an immune image or the zygote space.";
3021     } else {
3022       LOG(INFO) << "holder is in a non-immune, non-moving (or main) space.";
3023       accounting::ContinuousSpaceBitmap* mark_bitmap = heap_->GetNonMovingSpace()->GetMarkBitmap();
3024       accounting::LargeObjectBitmap* los_bitmap = nullptr;
3025       const bool is_los = !mark_bitmap->HasAddress(obj);
3026       if (is_los) {
3027         DCHECK(heap_->GetLargeObjectsSpace() && heap_->GetLargeObjectsSpace()->Contains(obj))
3028             << "obj=" << obj
3029             << " LOS bit map covers the entire lower 4GB address range";
3030         los_bitmap = heap_->GetLargeObjectsSpace()->GetMarkBitmap();
3031       }
3032       if (!is_los && mark_bitmap->Test(obj)) {
3033         LOG(INFO) << "holder is marked in the non-moving space mark bit map.";
3034       } else if (is_los && los_bitmap->Test(obj)) {
3035         LOG(INFO) << "holder is marked in the los bit map.";
3036       } else {
3037         // If ref is on the allocation stack, then it is considered
3038         // mark/alive (but not necessarily on the live stack.)
3039         if (IsOnAllocStack(obj)) {
3040           LOG(INFO) << "holder is on the alloc stack.";
3041         } else {
3042           LOG(INFO) << "holder is not marked or on the alloc stack.";
3043         }
3044       }
3045     }
3046   }
3047   LOG(INFO) << "offset=" << offset.SizeValue();
3048 }
3049 
IsMarkedInNonMovingSpace(mirror::Object * from_ref)3050 bool ConcurrentCopying::IsMarkedInNonMovingSpace(mirror::Object* from_ref) {
3051   DCHECK(!region_space_->HasAddress(from_ref)) << "ref=" << from_ref;
3052   DCHECK(!immune_spaces_.ContainsObject(from_ref)) << "ref=" << from_ref;
3053   if (kUseBakerReadBarrier && from_ref->GetReadBarrierStateAcquire() == ReadBarrier::GrayState()) {
3054     return true;
3055   } else if (!use_generational_cc_ || done_scanning_.load(std::memory_order_acquire)) {
3056     // Read the comment in IsMarkedInUnevacFromSpace()
3057     accounting::ContinuousSpaceBitmap* mark_bitmap = heap_->GetNonMovingSpace()->GetMarkBitmap();
3058     accounting::LargeObjectBitmap* los_bitmap = nullptr;
3059     const bool is_los = !mark_bitmap->HasAddress(from_ref);
3060     if (is_los) {
3061       DCHECK(heap_->GetLargeObjectsSpace() && heap_->GetLargeObjectsSpace()->Contains(from_ref))
3062           << "ref=" << from_ref
3063           << " doesn't belong to non-moving space and large object space doesn't exist";
3064       los_bitmap = heap_->GetLargeObjectsSpace()->GetMarkBitmap();
3065     }
3066     if (is_los ? los_bitmap->Test(from_ref) : mark_bitmap->Test(from_ref)) {
3067       return true;
3068     }
3069   }
3070   return IsOnAllocStack(from_ref);
3071 }
3072 
AssertToSpaceInvariantInNonMovingSpace(mirror::Object * obj,mirror::Object * ref)3073 void ConcurrentCopying::AssertToSpaceInvariantInNonMovingSpace(mirror::Object* obj,
3074                                                                mirror::Object* ref) {
3075   CHECK(ref != nullptr);
3076   CHECK(!region_space_->HasAddress(ref)) << "obj=" << obj << " ref=" << ref;
3077   // In a non-moving space. Check that the ref is marked.
3078   if (immune_spaces_.ContainsObject(ref)) {
3079     // Immune space case.
3080     if (kUseBakerReadBarrier) {
3081       // Immune object may not be gray if called from the GC.
3082       if (Thread::Current() == thread_running_gc_ && !gc_grays_immune_objects_) {
3083         return;
3084       }
3085       bool updated_all_immune_objects = updated_all_immune_objects_.load(std::memory_order_seq_cst);
3086       CHECK(updated_all_immune_objects || ref->GetReadBarrierState() == ReadBarrier::GrayState())
3087           << "Unmarked immune space ref. obj=" << obj << " rb_state="
3088           << (obj != nullptr ? obj->GetReadBarrierState() : 0U)
3089           << " ref=" << ref << " ref rb_state=" << ref->GetReadBarrierState()
3090           << " updated_all_immune_objects=" << updated_all_immune_objects;
3091     }
3092   } else {
3093     // Non-moving space and large-object space (LOS) cases.
3094     // If `ref` is on the allocation stack, then it may not be
3095     // marked live, but considered marked/alive (but not
3096     // necessarily on the live stack).
3097     CHECK(IsMarkedInNonMovingSpace(ref))
3098         << "Unmarked ref that's not on the allocation stack."
3099         << " obj=" << obj
3100         << " ref=" << ref
3101         << " rb_state=" << ref->GetReadBarrierState()
3102         << " is_marking=" << std::boolalpha << is_marking_ << std::noboolalpha
3103         << " young_gen=" << std::boolalpha << young_gen_ << std::noboolalpha
3104         << " done_scanning="
3105         << std::boolalpha << done_scanning_.load(std::memory_order_acquire) << std::noboolalpha
3106         << " self=" << Thread::Current();
3107   }
3108 }
3109 
3110 // Used to scan ref fields of an object.
3111 template <bool kNoUnEvac>
3112 class ConcurrentCopying::RefFieldsVisitor {
3113  public:
RefFieldsVisitor(ConcurrentCopying * collector,Thread * const thread)3114   explicit RefFieldsVisitor(ConcurrentCopying* collector, Thread* const thread)
3115       : collector_(collector), thread_(thread) {
3116     // Cannot have `kNoUnEvac` when Generational CC collection is disabled.
3117     DCHECK(!kNoUnEvac || collector_->use_generational_cc_);
3118   }
3119 
operator ()(mirror::Object * obj,MemberOffset offset,bool) const3120   void operator()(mirror::Object* obj, MemberOffset offset, bool /* is_static */)
3121       const ALWAYS_INLINE REQUIRES_SHARED(Locks::mutator_lock_)
3122       REQUIRES_SHARED(Locks::heap_bitmap_lock_) {
3123     collector_->Process<kNoUnEvac>(obj, offset);
3124   }
3125 
operator ()(ObjPtr<mirror::Class> klass,ObjPtr<mirror::Reference> ref) const3126   void operator()(ObjPtr<mirror::Class> klass, ObjPtr<mirror::Reference> ref) const
3127       REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
3128     CHECK(klass->IsTypeOfReferenceClass());
3129     collector_->DelayReferenceReferent(klass, ref);
3130   }
3131 
VisitRootIfNonNull(mirror::CompressedReference<mirror::Object> * root) const3132   void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
3133       ALWAYS_INLINE
3134       REQUIRES_SHARED(Locks::mutator_lock_) {
3135     if (!root->IsNull()) {
3136       VisitRoot(root);
3137     }
3138   }
3139 
VisitRoot(mirror::CompressedReference<mirror::Object> * root) const3140   void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
3141       ALWAYS_INLINE
3142       REQUIRES_SHARED(Locks::mutator_lock_) {
3143     collector_->MarkRoot</*kGrayImmuneObject=*/false>(thread_, root);
3144   }
3145 
3146  private:
3147   ConcurrentCopying* const collector_;
3148   Thread* const thread_;
3149 };
3150 
3151 template <bool kNoUnEvac>
Scan(mirror::Object * to_ref,size_t obj_size)3152 inline void ConcurrentCopying::Scan(mirror::Object* to_ref, size_t obj_size) {
3153   // Cannot have `kNoUnEvac` when Generational CC collection is disabled.
3154   DCHECK(!kNoUnEvac || use_generational_cc_);
3155   if (kDisallowReadBarrierDuringScan && !Runtime::Current()->IsActiveTransaction()) {
3156     // Avoid all read barriers during visit references to help performance.
3157     // Don't do this in transaction mode because we may read the old value of an field which may
3158     // trigger read barriers.
3159     Thread::Current()->ModifyDebugDisallowReadBarrier(1);
3160   }
3161   if (obj_size == 0) {
3162     obj_size = to_ref->SizeOf<kDefaultVerifyFlags>();
3163   }
3164   bytes_scanned_ += obj_size;
3165 
3166   DCHECK(!region_space_->IsInFromSpace(to_ref));
3167   DCHECK_EQ(Thread::Current(), thread_running_gc_);
3168   RefFieldsVisitor<kNoUnEvac> visitor(this, thread_running_gc_);
3169   // Disable the read barrier for a performance reason.
3170   to_ref->VisitReferences</*kVisitNativeRoots=*/true, kDefaultVerifyFlags, kWithoutReadBarrier>(
3171       visitor, visitor);
3172   if (kDisallowReadBarrierDuringScan && !Runtime::Current()->IsActiveTransaction()) {
3173     thread_running_gc_->ModifyDebugDisallowReadBarrier(-1);
3174   }
3175 }
3176 
3177 template <bool kNoUnEvac>
Process(mirror::Object * obj,MemberOffset offset)3178 inline void ConcurrentCopying::Process(mirror::Object* obj, MemberOffset offset) {
3179   // Cannot have `kNoUnEvac` when Generational CC collection is disabled.
3180   DCHECK(!kNoUnEvac || use_generational_cc_);
3181   DCHECK_EQ(Thread::Current(), thread_running_gc_);
3182   mirror::Object* ref = obj->GetFieldObject<
3183       mirror::Object, kVerifyNone, kWithoutReadBarrier, false>(offset);
3184   mirror::Object* to_ref = Mark</*kGrayImmuneObject=*/false, kNoUnEvac, /*kFromGCThread=*/true>(
3185       thread_running_gc_,
3186       ref,
3187       /*holder=*/ obj,
3188       offset);
3189   if (to_ref == ref) {
3190     return;
3191   }
3192   // This may fail if the mutator writes to the field at the same time. But it's ok.
3193   mirror::Object* expected_ref = ref;
3194   mirror::Object* new_ref = to_ref;
3195   do {
3196     if (expected_ref !=
3197         obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier, false>(offset)) {
3198       // It was updated by the mutator.
3199       break;
3200     }
3201     // Use release CAS to make sure threads reading the reference see contents of copied objects.
3202   } while (!obj->CasFieldObjectWithoutWriteBarrier<false, false, kVerifyNone>(
3203       offset,
3204       expected_ref,
3205       new_ref,
3206       CASMode::kWeak,
3207       std::memory_order_release));
3208 }
3209 
3210 // Process some roots.
VisitRoots(mirror::Object *** roots,size_t count,const RootInfo & info ATTRIBUTE_UNUSED)3211 inline void ConcurrentCopying::VisitRoots(
3212     mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED) {
3213   Thread* const self = Thread::Current();
3214   for (size_t i = 0; i < count; ++i) {
3215     mirror::Object** root = roots[i];
3216     mirror::Object* ref = *root;
3217     mirror::Object* to_ref = Mark(self, ref);
3218     if (to_ref == ref) {
3219       continue;
3220     }
3221     Atomic<mirror::Object*>* addr = reinterpret_cast<Atomic<mirror::Object*>*>(root);
3222     mirror::Object* expected_ref = ref;
3223     mirror::Object* new_ref = to_ref;
3224     do {
3225       if (expected_ref != addr->load(std::memory_order_relaxed)) {
3226         // It was updated by the mutator.
3227         break;
3228       }
3229     } while (!addr->CompareAndSetWeakRelaxed(expected_ref, new_ref));
3230   }
3231 }
3232 
3233 template<bool kGrayImmuneObject>
MarkRoot(Thread * const self,mirror::CompressedReference<mirror::Object> * root)3234 inline void ConcurrentCopying::MarkRoot(Thread* const self,
3235                                         mirror::CompressedReference<mirror::Object>* root) {
3236   DCHECK(!root->IsNull());
3237   mirror::Object* const ref = root->AsMirrorPtr();
3238   mirror::Object* to_ref = Mark<kGrayImmuneObject>(self, ref);
3239   if (to_ref != ref) {
3240     auto* addr = reinterpret_cast<Atomic<mirror::CompressedReference<mirror::Object>>*>(root);
3241     auto expected_ref = mirror::CompressedReference<mirror::Object>::FromMirrorPtr(ref);
3242     auto new_ref = mirror::CompressedReference<mirror::Object>::FromMirrorPtr(to_ref);
3243     // If the cas fails, then it was updated by the mutator.
3244     do {
3245       if (ref != addr->load(std::memory_order_relaxed).AsMirrorPtr()) {
3246         // It was updated by the mutator.
3247         break;
3248       }
3249     } while (!addr->CompareAndSetWeakRelaxed(expected_ref, new_ref));
3250   }
3251 }
3252 
VisitRoots(mirror::CompressedReference<mirror::Object> ** roots,size_t count,const RootInfo & info ATTRIBUTE_UNUSED)3253 inline void ConcurrentCopying::VisitRoots(
3254     mirror::CompressedReference<mirror::Object>** roots, size_t count,
3255     const RootInfo& info ATTRIBUTE_UNUSED) {
3256   Thread* const self = Thread::Current();
3257   for (size_t i = 0; i < count; ++i) {
3258     mirror::CompressedReference<mirror::Object>* const root = roots[i];
3259     if (!root->IsNull()) {
3260       // kGrayImmuneObject is true because this is used for the thread flip.
3261       MarkRoot</*kGrayImmuneObject=*/true>(self, root);
3262     }
3263   }
3264 }
3265 
3266 // Temporary set gc_grays_immune_objects_ to true in a scope if the current thread is GC.
3267 class ConcurrentCopying::ScopedGcGraysImmuneObjects {
3268  public:
ScopedGcGraysImmuneObjects(ConcurrentCopying * collector)3269   explicit ScopedGcGraysImmuneObjects(ConcurrentCopying* collector)
3270       : collector_(collector), enabled_(false) {
3271     if (kUseBakerReadBarrier &&
3272         collector_->thread_running_gc_ == Thread::Current() &&
3273         !collector_->gc_grays_immune_objects_) {
3274       collector_->gc_grays_immune_objects_ = true;
3275       enabled_ = true;
3276     }
3277   }
3278 
~ScopedGcGraysImmuneObjects()3279   ~ScopedGcGraysImmuneObjects() {
3280     if (kUseBakerReadBarrier &&
3281         collector_->thread_running_gc_ == Thread::Current() &&
3282         enabled_) {
3283       DCHECK(collector_->gc_grays_immune_objects_);
3284       collector_->gc_grays_immune_objects_ = false;
3285     }
3286   }
3287 
3288  private:
3289   ConcurrentCopying* const collector_;
3290   bool enabled_;
3291 };
3292 
3293 // Fill the given memory block with a fake object. Used to fill in a
3294 // copy of objects that was lost in race.
FillWithFakeObject(Thread * const self,mirror::Object * fake_obj,size_t byte_size)3295 void ConcurrentCopying::FillWithFakeObject(Thread* const self,
3296                                            mirror::Object* fake_obj,
3297                                            size_t byte_size) {
3298   // GC doesn't gray immune objects while scanning immune objects. But we need to trigger the read
3299   // barriers here because we need the updated reference to the int array class, etc. Temporary set
3300   // gc_grays_immune_objects_ to true so that we won't cause a DCHECK failure in MarkImmuneSpace().
3301   ScopedGcGraysImmuneObjects scoped_gc_gray_immune_objects(this);
3302   CHECK_ALIGNED(byte_size, kObjectAlignment);
3303   memset(fake_obj, 0, byte_size);
3304   // Avoid going through read barrier for since kDisallowReadBarrierDuringScan may be enabled.
3305   // Explicitly mark to make sure to get an object in the to-space.
3306   mirror::Class* int_array_class = down_cast<mirror::Class*>(
3307       Mark(self, GetClassRoot<mirror::IntArray, kWithoutReadBarrier>().Ptr()));
3308   CHECK(int_array_class != nullptr);
3309   if (ReadBarrier::kEnableToSpaceInvariantChecks) {
3310     AssertToSpaceInvariant(nullptr, MemberOffset(0), int_array_class);
3311   }
3312   size_t component_size = int_array_class->GetComponentSize();
3313   CHECK_EQ(component_size, sizeof(int32_t));
3314   size_t data_offset = mirror::Array::DataOffset(component_size).SizeValue();
3315   if (data_offset > byte_size) {
3316     // An int array is too big. Use java.lang.Object.
3317     CHECK(java_lang_Object_ != nullptr);
3318     if (ReadBarrier::kEnableToSpaceInvariantChecks) {
3319       AssertToSpaceInvariant(nullptr, MemberOffset(0), java_lang_Object_);
3320     }
3321     CHECK_EQ(byte_size, java_lang_Object_->GetObjectSize<kVerifyNone>());
3322     fake_obj->SetClass(java_lang_Object_);
3323     CHECK_EQ(byte_size, (fake_obj->SizeOf<kVerifyNone>()));
3324   } else {
3325     // Use an int array.
3326     fake_obj->SetClass(int_array_class);
3327     CHECK(fake_obj->IsArrayInstance<kVerifyNone>());
3328     int32_t length = (byte_size - data_offset) / component_size;
3329     ObjPtr<mirror::Array> fake_arr = fake_obj->AsArray<kVerifyNone>();
3330     fake_arr->SetLength(length);
3331     CHECK_EQ(fake_arr->GetLength(), length)
3332         << "byte_size=" << byte_size << " length=" << length
3333         << " component_size=" << component_size << " data_offset=" << data_offset;
3334     CHECK_EQ(byte_size, (fake_obj->SizeOf<kVerifyNone>()))
3335         << "byte_size=" << byte_size << " length=" << length
3336         << " component_size=" << component_size << " data_offset=" << data_offset;
3337   }
3338 }
3339 
3340 // Reuse the memory blocks that were copy of objects that were lost in race.
AllocateInSkippedBlock(Thread * const self,size_t alloc_size)3341 mirror::Object* ConcurrentCopying::AllocateInSkippedBlock(Thread* const self, size_t alloc_size) {
3342   // Try to reuse the blocks that were unused due to CAS failures.
3343   CHECK_ALIGNED(alloc_size, space::RegionSpace::kAlignment);
3344   size_t min_object_size = RoundUp(sizeof(mirror::Object), space::RegionSpace::kAlignment);
3345   size_t byte_size;
3346   uint8_t* addr;
3347   {
3348     MutexLock mu(self, skipped_blocks_lock_);
3349     auto it = skipped_blocks_map_.lower_bound(alloc_size);
3350     if (it == skipped_blocks_map_.end()) {
3351       // Not found.
3352       return nullptr;
3353     }
3354     byte_size = it->first;
3355     CHECK_GE(byte_size, alloc_size);
3356     if (byte_size > alloc_size && byte_size - alloc_size < min_object_size) {
3357       // If remainder would be too small for a fake object, retry with a larger request size.
3358       it = skipped_blocks_map_.lower_bound(alloc_size + min_object_size);
3359       if (it == skipped_blocks_map_.end()) {
3360         // Not found.
3361         return nullptr;
3362       }
3363       CHECK_ALIGNED(it->first - alloc_size, space::RegionSpace::kAlignment);
3364       CHECK_GE(it->first - alloc_size, min_object_size)
3365           << "byte_size=" << byte_size << " it->first=" << it->first << " alloc_size=" << alloc_size;
3366     }
3367     // Found a block.
3368     CHECK(it != skipped_blocks_map_.end());
3369     byte_size = it->first;
3370     addr = it->second;
3371     CHECK_GE(byte_size, alloc_size);
3372     CHECK(region_space_->IsInToSpace(reinterpret_cast<mirror::Object*>(addr)));
3373     CHECK_ALIGNED(byte_size, space::RegionSpace::kAlignment);
3374     if (kVerboseMode) {
3375       LOG(INFO) << "Reusing skipped bytes : " << reinterpret_cast<void*>(addr) << ", " << byte_size;
3376     }
3377     skipped_blocks_map_.erase(it);
3378   }
3379   memset(addr, 0, byte_size);
3380   if (byte_size > alloc_size) {
3381     // Return the remainder to the map.
3382     CHECK_ALIGNED(byte_size - alloc_size, space::RegionSpace::kAlignment);
3383     CHECK_GE(byte_size - alloc_size, min_object_size);
3384     // FillWithFakeObject may mark an object, avoid holding skipped_blocks_lock_ to prevent lock
3385     // violation and possible deadlock. The deadlock case is a recursive case:
3386     // FillWithFakeObject -> Mark(IntArray.class) -> Copy -> AllocateInSkippedBlock.
3387     FillWithFakeObject(self,
3388                        reinterpret_cast<mirror::Object*>(addr + alloc_size),
3389                        byte_size - alloc_size);
3390     CHECK(region_space_->IsInToSpace(reinterpret_cast<mirror::Object*>(addr + alloc_size)));
3391     {
3392       MutexLock mu(self, skipped_blocks_lock_);
3393       skipped_blocks_map_.insert(std::make_pair(byte_size - alloc_size, addr + alloc_size));
3394     }
3395   }
3396   return reinterpret_cast<mirror::Object*>(addr);
3397 }
3398 
Copy(Thread * const self,mirror::Object * from_ref,mirror::Object * holder,MemberOffset offset)3399 mirror::Object* ConcurrentCopying::Copy(Thread* const self,
3400                                         mirror::Object* from_ref,
3401                                         mirror::Object* holder,
3402                                         MemberOffset offset) {
3403   DCHECK(region_space_->IsInFromSpace(from_ref));
3404   // If the class pointer is null, the object is invalid. This could occur for a dangling pointer
3405   // from a previous GC that is either inside or outside the allocated region.
3406   mirror::Class* klass = from_ref->GetClass<kVerifyNone, kWithoutReadBarrier>();
3407   if (UNLIKELY(klass == nullptr)) {
3408     // Remove memory protection from the region space and log debugging information.
3409     region_space_->Unprotect();
3410     heap_->GetVerification()->LogHeapCorruption(holder, offset, from_ref, /* fatal= */ true);
3411   }
3412   // There must not be a read barrier to avoid nested RB that might violate the to-space invariant.
3413   // Note that from_ref is a from space ref so the SizeOf() call will access the from-space meta
3414   // objects, but it's ok and necessary.
3415   size_t obj_size = from_ref->SizeOf<kDefaultVerifyFlags>();
3416   size_t region_space_alloc_size = (obj_size <= space::RegionSpace::kRegionSize)
3417       ? RoundUp(obj_size, space::RegionSpace::kAlignment)
3418       : RoundUp(obj_size, space::RegionSpace::kRegionSize);
3419   size_t region_space_bytes_allocated = 0U;
3420   size_t non_moving_space_bytes_allocated = 0U;
3421   size_t bytes_allocated = 0U;
3422   size_t unused_size;
3423   bool fall_back_to_non_moving = false;
3424   mirror::Object* to_ref = region_space_->AllocNonvirtual</*kForEvac=*/ true>(
3425       region_space_alloc_size, &region_space_bytes_allocated, nullptr, &unused_size);
3426   bytes_allocated = region_space_bytes_allocated;
3427   if (LIKELY(to_ref != nullptr)) {
3428     DCHECK_EQ(region_space_alloc_size, region_space_bytes_allocated);
3429   } else {
3430     // Failed to allocate in the region space. Try the skipped blocks.
3431     to_ref = AllocateInSkippedBlock(self, region_space_alloc_size);
3432     if (to_ref != nullptr) {
3433       // Succeeded to allocate in a skipped block.
3434       if (heap_->use_tlab_) {
3435         // This is necessary for the tlab case as it's not accounted in the space.
3436         region_space_->RecordAlloc(to_ref);
3437       }
3438       bytes_allocated = region_space_alloc_size;
3439       heap_->num_bytes_allocated_.fetch_sub(bytes_allocated, std::memory_order_relaxed);
3440       to_space_bytes_skipped_.fetch_sub(bytes_allocated, std::memory_order_relaxed);
3441       to_space_objects_skipped_.fetch_sub(1, std::memory_order_relaxed);
3442     } else {
3443       // Fall back to the non-moving space.
3444       fall_back_to_non_moving = true;
3445       if (kVerboseMode) {
3446         LOG(INFO) << "Out of memory in the to-space. Fall back to non-moving. skipped_bytes="
3447                   << to_space_bytes_skipped_.load(std::memory_order_relaxed)
3448                   << " skipped_objects="
3449                   << to_space_objects_skipped_.load(std::memory_order_relaxed);
3450       }
3451       to_ref = heap_->non_moving_space_->Alloc(
3452           self, obj_size, &non_moving_space_bytes_allocated, nullptr, &unused_size);
3453       if (UNLIKELY(to_ref == nullptr)) {
3454         LOG(FATAL_WITHOUT_ABORT) << "Fall-back non-moving space allocation failed for a "
3455                                  << obj_size << " byte object in region type "
3456                                  << region_space_->GetRegionType(from_ref);
3457         LOG(FATAL) << "Object address=" << from_ref << " type=" << from_ref->PrettyTypeOf();
3458       }
3459       bytes_allocated = non_moving_space_bytes_allocated;
3460     }
3461   }
3462   DCHECK(to_ref != nullptr);
3463 
3464   // Copy the object excluding the lock word since that is handled in the loop.
3465   to_ref->SetClass(klass);
3466   const size_t kObjectHeaderSize = sizeof(mirror::Object);
3467   DCHECK_GE(obj_size, kObjectHeaderSize);
3468   static_assert(kObjectHeaderSize == sizeof(mirror::HeapReference<mirror::Class>) +
3469                     sizeof(LockWord),
3470                 "Object header size does not match");
3471   // Memcpy can tear for words since it may do byte copy. It is only safe to do this since the
3472   // object in the from space is immutable other than the lock word. b/31423258
3473   memcpy(reinterpret_cast<uint8_t*>(to_ref) + kObjectHeaderSize,
3474          reinterpret_cast<const uint8_t*>(from_ref) + kObjectHeaderSize,
3475          obj_size - kObjectHeaderSize);
3476 
3477   // Attempt to install the forward pointer. This is in a loop as the
3478   // lock word atomic write can fail.
3479   while (true) {
3480     LockWord old_lock_word = from_ref->GetLockWord(false);
3481 
3482     if (old_lock_word.GetState() == LockWord::kForwardingAddress) {
3483       // Lost the race. Another thread (either GC or mutator) stored
3484       // the forwarding pointer first. Make the lost copy (to_ref)
3485       // look like a valid but dead (fake) object and keep it for
3486       // future reuse.
3487       FillWithFakeObject(self, to_ref, bytes_allocated);
3488       if (!fall_back_to_non_moving) {
3489         DCHECK(region_space_->IsInToSpace(to_ref));
3490         if (bytes_allocated > space::RegionSpace::kRegionSize) {
3491           // Free the large alloc.
3492           region_space_->FreeLarge</*kForEvac=*/ true>(to_ref, bytes_allocated);
3493         } else {
3494           // Record the lost copy for later reuse.
3495           heap_->num_bytes_allocated_.fetch_add(bytes_allocated, std::memory_order_relaxed);
3496           to_space_bytes_skipped_.fetch_add(bytes_allocated, std::memory_order_relaxed);
3497           to_space_objects_skipped_.fetch_add(1, std::memory_order_relaxed);
3498           MutexLock mu(self, skipped_blocks_lock_);
3499           skipped_blocks_map_.insert(std::make_pair(bytes_allocated,
3500                                                     reinterpret_cast<uint8_t*>(to_ref)));
3501         }
3502       } else {
3503         DCHECK(heap_->non_moving_space_->HasAddress(to_ref));
3504         DCHECK_EQ(bytes_allocated, non_moving_space_bytes_allocated);
3505         // Free the non-moving-space chunk.
3506         heap_->non_moving_space_->Free(self, to_ref);
3507       }
3508 
3509       // Get the winner's forward ptr.
3510       mirror::Object* lost_fwd_ptr = to_ref;
3511       to_ref = reinterpret_cast<mirror::Object*>(old_lock_word.ForwardingAddress());
3512       CHECK(to_ref != nullptr);
3513       CHECK_NE(to_ref, lost_fwd_ptr);
3514       CHECK(region_space_->IsInToSpace(to_ref) || heap_->non_moving_space_->HasAddress(to_ref))
3515           << "to_ref=" << to_ref << " " << heap_->DumpSpaces();
3516       CHECK_NE(to_ref->GetLockWord(false).GetState(), LockWord::kForwardingAddress);
3517       return to_ref;
3518     }
3519 
3520     // Copy the old lock word over since we did not copy it yet.
3521     to_ref->SetLockWord(old_lock_word, false);
3522     // Set the gray ptr.
3523     if (kUseBakerReadBarrier) {
3524       to_ref->SetReadBarrierState(ReadBarrier::GrayState());
3525     }
3526 
3527     LockWord new_lock_word = LockWord::FromForwardingAddress(reinterpret_cast<size_t>(to_ref));
3528 
3529     // Try to atomically write the fwd ptr. Make sure that the copied object is visible to any
3530     // readers of the fwd pointer.
3531     bool success = from_ref->CasLockWord(old_lock_word,
3532                                          new_lock_word,
3533                                          CASMode::kWeak,
3534                                          std::memory_order_release);
3535     if (LIKELY(success)) {
3536       // The CAS succeeded.
3537       DCHECK(thread_running_gc_ != nullptr);
3538       if (LIKELY(self == thread_running_gc_)) {
3539         objects_moved_gc_thread_ += 1;
3540         bytes_moved_gc_thread_ += bytes_allocated;
3541       } else {
3542         objects_moved_.fetch_add(1, std::memory_order_relaxed);
3543         bytes_moved_.fetch_add(bytes_allocated, std::memory_order_relaxed);
3544       }
3545 
3546       if (LIKELY(!fall_back_to_non_moving)) {
3547         DCHECK(region_space_->IsInToSpace(to_ref));
3548       } else {
3549         DCHECK(heap_->non_moving_space_->HasAddress(to_ref));
3550         DCHECK_EQ(bytes_allocated, non_moving_space_bytes_allocated);
3551         if (!use_generational_cc_ || !young_gen_) {
3552           // Mark it in the live bitmap.
3553           CHECK(!heap_->non_moving_space_->GetLiveBitmap()->AtomicTestAndSet(to_ref));
3554         }
3555         if (!kUseBakerReadBarrier) {
3556           // Mark it in the mark bitmap.
3557           CHECK(!heap_->non_moving_space_->GetMarkBitmap()->AtomicTestAndSet(to_ref));
3558         }
3559       }
3560       if (kUseBakerReadBarrier) {
3561         DCHECK(to_ref->GetReadBarrierState() == ReadBarrier::GrayState());
3562       }
3563       DCHECK(GetFwdPtr(from_ref) == to_ref);
3564       CHECK_NE(to_ref->GetLockWord(false).GetState(), LockWord::kForwardingAddress);
3565       // Make sure that anyone who sees to_ref also sees both the object contents and the
3566       // fwd pointer.
3567       QuasiAtomic::ThreadFenceForConstructor();
3568       PushOntoMarkStack(self, to_ref);
3569       return to_ref;
3570     } else {
3571       // The CAS failed. It may have lost the race or may have failed
3572       // due to monitor/hashcode ops. Either way, retry.
3573     }
3574   }
3575 }
3576 
IsMarked(mirror::Object * from_ref)3577 mirror::Object* ConcurrentCopying::IsMarked(mirror::Object* from_ref) {
3578   DCHECK(from_ref != nullptr);
3579   space::RegionSpace::RegionType rtype = region_space_->GetRegionType(from_ref);
3580   if (rtype == space::RegionSpace::RegionType::kRegionTypeToSpace) {
3581     // It's already marked.
3582     return from_ref;
3583   }
3584   mirror::Object* to_ref;
3585   if (rtype == space::RegionSpace::RegionType::kRegionTypeFromSpace) {
3586     to_ref = GetFwdPtr(from_ref);
3587     DCHECK(to_ref == nullptr || region_space_->IsInToSpace(to_ref) ||
3588            heap_->non_moving_space_->HasAddress(to_ref))
3589         << "from_ref=" << from_ref << " to_ref=" << to_ref;
3590   } else if (rtype == space::RegionSpace::RegionType::kRegionTypeUnevacFromSpace) {
3591     if (IsMarkedInUnevacFromSpace(from_ref)) {
3592       to_ref = from_ref;
3593     } else {
3594       to_ref = nullptr;
3595     }
3596   } else {
3597     // At this point, `from_ref` should not be in the region space
3598     // (i.e. within an "unused" region).
3599     DCHECK(!region_space_->HasAddress(from_ref)) << from_ref;
3600     // from_ref is in a non-moving space.
3601     if (immune_spaces_.ContainsObject(from_ref)) {
3602       // An immune object is alive.
3603       to_ref = from_ref;
3604     } else {
3605       // Non-immune non-moving space. Use the mark bitmap.
3606       if (IsMarkedInNonMovingSpace(from_ref)) {
3607         // Already marked.
3608         to_ref = from_ref;
3609       } else {
3610         to_ref = nullptr;
3611       }
3612     }
3613   }
3614   return to_ref;
3615 }
3616 
IsOnAllocStack(mirror::Object * ref)3617 bool ConcurrentCopying::IsOnAllocStack(mirror::Object* ref) {
3618   // TODO: Explain why this is here. What release operation does it pair with?
3619   std::atomic_thread_fence(std::memory_order_acquire);
3620   accounting::ObjectStack* alloc_stack = GetAllocationStack();
3621   return alloc_stack->Contains(ref);
3622 }
3623 
MarkNonMoving(Thread * const self,mirror::Object * ref,mirror::Object * holder,MemberOffset offset)3624 mirror::Object* ConcurrentCopying::MarkNonMoving(Thread* const self,
3625                                                  mirror::Object* ref,
3626                                                  mirror::Object* holder,
3627                                                  MemberOffset offset) {
3628   // ref is in a non-moving space (from_ref == to_ref).
3629   DCHECK(!region_space_->HasAddress(ref)) << ref;
3630   DCHECK(!immune_spaces_.ContainsObject(ref));
3631   // Use the mark bitmap.
3632   accounting::ContinuousSpaceBitmap* mark_bitmap = heap_->GetNonMovingSpace()->GetMarkBitmap();
3633   accounting::LargeObjectBitmap* los_bitmap = nullptr;
3634   const bool is_los = !mark_bitmap->HasAddress(ref);
3635   if (is_los) {
3636     if (!IsAligned<kPageSize>(ref)) {
3637       // Ref is a large object that is not aligned, it must be heap
3638       // corruption. Remove memory protection and dump data before
3639       // AtomicSetReadBarrierState since it will fault if the address is not
3640       // valid.
3641       region_space_->Unprotect();
3642       heap_->GetVerification()->LogHeapCorruption(holder, offset, ref, /* fatal= */ true);
3643     }
3644     DCHECK(heap_->GetLargeObjectsSpace())
3645         << "ref=" << ref
3646         << " doesn't belong to non-moving space and large object space doesn't exist";
3647     los_bitmap = heap_->GetLargeObjectsSpace()->GetMarkBitmap();
3648     DCHECK(los_bitmap->HasAddress(ref));
3649   }
3650   if (use_generational_cc_) {
3651     // The sticky-bit CC collector is only compatible with Baker-style read barriers.
3652     DCHECK(kUseBakerReadBarrier);
3653     // Not done scanning, use AtomicSetReadBarrierPointer.
3654     if (!done_scanning_.load(std::memory_order_acquire)) {
3655       // Since the mark bitmap is still filled in from last GC, we can not use that or else the
3656       // mutator may see references to the from space. Instead, use the Baker pointer itself as
3657       // the mark bit.
3658       //
3659       // We need to avoid marking objects that are on allocation stack as that will lead to a
3660       // situation (after this GC cycle is finished) where some object(s) are on both allocation
3661       // stack and live bitmap. This leads to visiting the same object(s) twice during a heapdump
3662       // (b/117426281).
3663       if (!IsOnAllocStack(ref) &&
3664           ref->AtomicSetReadBarrierState(ReadBarrier::NonGrayState(), ReadBarrier::GrayState())) {
3665         // TODO: We don't actually need to scan this object later, we just need to clear the gray
3666         // bit.
3667         // We don't need to mark newly allocated objects (those in allocation stack) as they can
3668         // only point to to-space objects. Also, they are considered live till the next GC cycle.
3669         PushOntoMarkStack(self, ref);
3670       }
3671       return ref;
3672     }
3673   }
3674   if (!is_los && mark_bitmap->Test(ref)) {
3675     // Already marked.
3676   } else if (is_los && los_bitmap->Test(ref)) {
3677     // Already marked in LOS.
3678   } else if (IsOnAllocStack(ref)) {
3679     // If it's on the allocation stack, it's considered marked. Keep it white (non-gray).
3680     // Objects on the allocation stack need not be marked.
3681     if (!is_los) {
3682       DCHECK(!mark_bitmap->Test(ref));
3683     } else {
3684       DCHECK(!los_bitmap->Test(ref));
3685     }
3686     if (kUseBakerReadBarrier) {
3687       DCHECK_EQ(ref->GetReadBarrierState(), ReadBarrier::NonGrayState());
3688     }
3689   } else {
3690     // Not marked nor on the allocation stack. Try to mark it.
3691     // This may or may not succeed, which is ok.
3692     bool success = false;
3693     if (kUseBakerReadBarrier) {
3694       success = ref->AtomicSetReadBarrierState(ReadBarrier::NonGrayState(),
3695                                                ReadBarrier::GrayState());
3696     } else {
3697       success = is_los ?
3698           !los_bitmap->AtomicTestAndSet(ref) :
3699           !mark_bitmap->AtomicTestAndSet(ref);
3700     }
3701     if (success) {
3702       if (kUseBakerReadBarrier) {
3703         DCHECK_EQ(ref->GetReadBarrierState(), ReadBarrier::GrayState());
3704       }
3705       PushOntoMarkStack(self, ref);
3706     }
3707   }
3708   return ref;
3709 }
3710 
FinishPhase()3711 void ConcurrentCopying::FinishPhase() {
3712   Thread* const self = Thread::Current();
3713   {
3714     MutexLock mu(self, mark_stack_lock_);
3715     CHECK(revoked_mark_stacks_.empty());
3716     CHECK_EQ(pooled_mark_stacks_.size(), kMarkStackPoolSize);
3717   }
3718   // kVerifyNoMissingCardMarks relies on the region space cards not being cleared to avoid false
3719   // positives.
3720   if (!kVerifyNoMissingCardMarks && !use_generational_cc_) {
3721     TimingLogger::ScopedTiming split("ClearRegionSpaceCards", GetTimings());
3722     // We do not currently use the region space cards at all, madvise them away to save ram.
3723     heap_->GetCardTable()->ClearCardRange(region_space_->Begin(), region_space_->Limit());
3724   } else if (use_generational_cc_ && !young_gen_) {
3725     region_space_inter_region_bitmap_.Clear();
3726     non_moving_space_inter_region_bitmap_.Clear();
3727   }
3728   {
3729     MutexLock mu(self, skipped_blocks_lock_);
3730     skipped_blocks_map_.clear();
3731   }
3732   {
3733     ReaderMutexLock mu(self, *Locks::mutator_lock_);
3734     {
3735       WriterMutexLock mu2(self, *Locks::heap_bitmap_lock_);
3736       heap_->ClearMarkedObjects();
3737     }
3738     if (kUseBakerReadBarrier && kFilterModUnionCards) {
3739       TimingLogger::ScopedTiming split("FilterModUnionCards", GetTimings());
3740       ReaderMutexLock mu2(self, *Locks::heap_bitmap_lock_);
3741       for (space::ContinuousSpace* space : immune_spaces_.GetSpaces()) {
3742         DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
3743         accounting::ModUnionTable* table = heap_->FindModUnionTableFromSpace(space);
3744         // Filter out cards that don't need to be set.
3745         if (table != nullptr) {
3746           table->FilterCards();
3747         }
3748       }
3749     }
3750     if (kUseBakerReadBarrier) {
3751       TimingLogger::ScopedTiming split("EmptyRBMarkBitStack", GetTimings());
3752       DCHECK(rb_mark_bit_stack_ != nullptr);
3753       const auto* limit = rb_mark_bit_stack_->End();
3754       for (StackReference<mirror::Object>* it = rb_mark_bit_stack_->Begin(); it != limit; ++it) {
3755         CHECK(it->AsMirrorPtr()->AtomicSetMarkBit(1, 0))
3756             << "rb_mark_bit_stack_->Begin()" << rb_mark_bit_stack_->Begin() << '\n'
3757             << "rb_mark_bit_stack_->End()" << rb_mark_bit_stack_->End() << '\n'
3758             << "rb_mark_bit_stack_->IsFull()"
3759             << std::boolalpha << rb_mark_bit_stack_->IsFull() << std::noboolalpha << '\n'
3760             << DumpReferenceInfo(it->AsMirrorPtr(), "*it");
3761       }
3762       rb_mark_bit_stack_->Reset();
3763     }
3764   }
3765   if (measure_read_barrier_slow_path_) {
3766     MutexLock mu(self, rb_slow_path_histogram_lock_);
3767     rb_slow_path_time_histogram_.AdjustAndAddValue(
3768         rb_slow_path_ns_.load(std::memory_order_relaxed));
3769     rb_slow_path_count_total_ += rb_slow_path_count_.load(std::memory_order_relaxed);
3770     rb_slow_path_count_gc_total_ += rb_slow_path_count_gc_.load(std::memory_order_relaxed);
3771   }
3772 }
3773 
IsNullOrMarkedHeapReference(mirror::HeapReference<mirror::Object> * field,bool do_atomic_update)3774 bool ConcurrentCopying::IsNullOrMarkedHeapReference(mirror::HeapReference<mirror::Object>* field,
3775                                                     bool do_atomic_update) {
3776   mirror::Object* from_ref = field->AsMirrorPtr();
3777   if (from_ref == nullptr) {
3778     return true;
3779   }
3780   mirror::Object* to_ref = IsMarked(from_ref);
3781   if (to_ref == nullptr) {
3782     return false;
3783   }
3784   if (from_ref != to_ref) {
3785     if (do_atomic_update) {
3786       do {
3787         if (field->AsMirrorPtr() != from_ref) {
3788           // Concurrently overwritten by a mutator.
3789           break;
3790         }
3791       } while (!field->CasWeakRelaxed(from_ref, to_ref));
3792     } else {
3793       field->Assign(to_ref);
3794     }
3795   }
3796   return true;
3797 }
3798 
MarkObject(mirror::Object * from_ref)3799 mirror::Object* ConcurrentCopying::MarkObject(mirror::Object* from_ref) {
3800   return Mark(Thread::Current(), from_ref);
3801 }
3802 
DelayReferenceReferent(ObjPtr<mirror::Class> klass,ObjPtr<mirror::Reference> reference)3803 void ConcurrentCopying::DelayReferenceReferent(ObjPtr<mirror::Class> klass,
3804                                                ObjPtr<mirror::Reference> reference) {
3805   heap_->GetReferenceProcessor()->DelayReferenceReferent(klass, reference, this);
3806 }
3807 
ProcessReferences(Thread * self)3808 void ConcurrentCopying::ProcessReferences(Thread* self) {
3809   TimingLogger::ScopedTiming split("ProcessReferences", GetTimings());
3810   // We don't really need to lock the heap bitmap lock as we use CAS to mark in bitmaps.
3811   WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
3812   GetHeap()->GetReferenceProcessor()->ProcessReferences(
3813       /*concurrent=*/ true, GetTimings(), GetCurrentIteration()->GetClearSoftReferences(), this);
3814 }
3815 
RevokeAllThreadLocalBuffers()3816 void ConcurrentCopying::RevokeAllThreadLocalBuffers() {
3817   TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
3818   region_space_->RevokeAllThreadLocalBuffers();
3819 }
3820 
MarkFromReadBarrierWithMeasurements(Thread * const self,mirror::Object * from_ref)3821 mirror::Object* ConcurrentCopying::MarkFromReadBarrierWithMeasurements(Thread* const self,
3822                                                                        mirror::Object* from_ref) {
3823   if (self != thread_running_gc_) {
3824     rb_slow_path_count_.fetch_add(1u, std::memory_order_relaxed);
3825   } else {
3826     rb_slow_path_count_gc_.fetch_add(1u, std::memory_order_relaxed);
3827   }
3828   ScopedTrace tr(__FUNCTION__);
3829   const uint64_t start_time = measure_read_barrier_slow_path_ ? NanoTime() : 0u;
3830   mirror::Object* ret =
3831       Mark</*kGrayImmuneObject=*/true, /*kNoUnEvac=*/false, /*kFromGCThread=*/false>(self,
3832                                                                                      from_ref);
3833   if (measure_read_barrier_slow_path_) {
3834     rb_slow_path_ns_.fetch_add(NanoTime() - start_time, std::memory_order_relaxed);
3835   }
3836   return ret;
3837 }
3838 
DumpPerformanceInfo(std::ostream & os)3839 void ConcurrentCopying::DumpPerformanceInfo(std::ostream& os) {
3840   GarbageCollector::DumpPerformanceInfo(os);
3841   size_t num_gc_cycles = GetCumulativeTimings().GetIterations();
3842   MutexLock mu(Thread::Current(), rb_slow_path_histogram_lock_);
3843   if (rb_slow_path_time_histogram_.SampleSize() > 0) {
3844     Histogram<uint64_t>::CumulativeData cumulative_data;
3845     rb_slow_path_time_histogram_.CreateHistogram(&cumulative_data);
3846     rb_slow_path_time_histogram_.PrintConfidenceIntervals(os, 0.99, cumulative_data);
3847   }
3848   if (rb_slow_path_count_total_ > 0) {
3849     os << "Slow path count " << rb_slow_path_count_total_ << "\n";
3850   }
3851   if (rb_slow_path_count_gc_total_ > 0) {
3852     os << "GC slow path count " << rb_slow_path_count_gc_total_ << "\n";
3853   }
3854 
3855   os << "Average " << (young_gen_ ? "minor" : "major") << " GC reclaim bytes ratio "
3856      << (reclaimed_bytes_ratio_sum_ / num_gc_cycles) << " over " << num_gc_cycles
3857      << " GC cycles\n";
3858 
3859   os << "Average " << (young_gen_ ? "minor" : "major") << " GC copied live bytes ratio "
3860      << (copied_live_bytes_ratio_sum_ / gc_count_) << " over " << gc_count_
3861      << " " << (young_gen_ ? "minor" : "major") << " GCs\n";
3862 
3863   os << "Cumulative bytes moved " << cumulative_bytes_moved_ << "\n";
3864   os << "Cumulative objects moved " << cumulative_objects_moved_ << "\n";
3865 
3866   os << "Peak regions allocated "
3867      << region_space_->GetMaxPeakNumNonFreeRegions() << " ("
3868      << PrettySize(region_space_->GetMaxPeakNumNonFreeRegions() * space::RegionSpace::kRegionSize)
3869      << ") / " << region_space_->GetNumRegions() / 2 << " ("
3870      << PrettySize(region_space_->GetNumRegions() * space::RegionSpace::kRegionSize / 2)
3871      << ")\n";
3872   if (!young_gen_) {
3873     os << "Total madvise time " << PrettyDuration(region_space_->GetMadviseTime()) << "\n";
3874   }
3875 }
3876 
3877 }  // namespace collector
3878 }  // namespace gc
3879 }  // namespace art
3880