blob: e95b135565894887c9757f00a4274cf7ef60c5e0 [file] [log] [blame]
Hiroshi Yamauchid5307ec2014-03-27 21:07:51 -07001/*
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
Mathieu Chartierc7853442015-03-27 14:35:38 -070019#include "art_field-inl.h"
Andreas Gampe542451c2016-07-26 09:02:02 -070020#include "base/enums.h"
David Sehr891a50e2017-10-27 17:01:07 -070021#include "base/file_utils.h"
Mathieu Chartier56fe2582016-07-14 13:30:03 -070022#include "base/histogram-inl.h"
David Sehrc431b9d2018-03-02 12:01:51 -080023#include "base/quasi_atomic.h"
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070024#include "base/stl_util.h"
Mathieu Chartier56fe2582016-07-14 13:30:03 -070025#include "base/systrace.h"
Vladimir Markob4eb1b12018-05-24 11:09:38 +010026#include "class_root.h"
Mathieu Chartiera6b1ead2015-10-06 10:32:38 -070027#include "debugger.h"
Andreas Gampe291ce172017-04-24 13:22:18 -070028#include "gc/accounting/atomic_stack.h"
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080029#include "gc/accounting/heap_bitmap-inl.h"
Mathieu Chartier21328a12016-07-22 10:47:45 -070030#include "gc/accounting/mod_union_table-inl.h"
Andreas Gampe291ce172017-04-24 13:22:18 -070031#include "gc/accounting/read_barrier_table.h"
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080032#include "gc/accounting/space_bitmap-inl.h"
Andreas Gampe4934eb12017-01-30 13:15:26 -080033#include "gc/gc_pause_listener.h"
Mathieu Chartier3cf22532015-07-09 15:15:09 -070034#include "gc/reference_processor.h"
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080035#include "gc/space/image_space.h"
Mathieu Chartier073b16c2015-11-10 14:13:23 -080036#include "gc/space/space-inl.h"
Mathieu Chartier1ca68902017-04-18 11:26:22 -070037#include "gc/verification.h"
Mathieu Chartier4a26f172016-01-26 14:26:18 -080038#include "image-inl.h"
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080039#include "intern_table.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070040#include "mirror/class-inl.h"
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080041#include "mirror/object-inl.h"
Andreas Gampec6ea7d02017-02-01 16:46:28 -080042#include "mirror/object-refvisitor-inl.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070043#include "scoped_thread_state_change-inl.h"
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080044#include "thread-inl.h"
45#include "thread_list.h"
46#include "well_known_classes.h"
47
Hiroshi Yamauchid5307ec2014-03-27 21:07:51 -070048namespace art {
49namespace gc {
50namespace collector {
51
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -070052static constexpr size_t kDefaultGcMarkStackSize = 2 * MB;
Mathieu Chartier21328a12016-07-22 10:47:45 -070053// If kFilterModUnionCards then we attempt to filter cards that don't need to be dirty in the mod
54// union table. Disabled since it does not seem to help the pause much.
55static constexpr bool kFilterModUnionCards = kIsDebugBuild;
Roland Levillain72b7bf82018-08-07 18:39:27 +010056// If kDisallowReadBarrierDuringScan is true then the GC aborts if there are any read barrier that
57// occur during ConcurrentCopying::Scan in GC thread. May be used to diagnose possibly unnecessary
58// read barriers. Only enabled for kIsDebugBuild to avoid performance hit.
Mathieu Chartierd6636d32016-07-28 11:02:38 -070059static constexpr bool kDisallowReadBarrierDuringScan = kIsDebugBuild;
Mathieu Chartier36a270a2016-07-28 18:08:51 -070060// Slow path mark stack size, increase this if the stack is getting full and it is causing
61// performance problems.
62static constexpr size_t kReadBarrierMarkStackSize = 512 * KB;
Roland Levillainb1e1dc32018-07-10 19:19:31 +010063// Size (in the number of objects) of the sweep array free buffer.
64static constexpr size_t kSweepArrayChunkFreeSize = 1024;
Mathieu Chartiera1467d02017-02-22 09:22:50 -080065// Verify that there are no missing card marks.
66static constexpr bool kVerifyNoMissingCardMarks = kIsDebugBuild;
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -070067
Mathieu Chartier56fe2582016-07-14 13:30:03 -070068ConcurrentCopying::ConcurrentCopying(Heap* heap,
Mathieu Chartier8d1a9962016-08-17 16:39:45 -070069 bool young_gen,
Mathieu Chartier56fe2582016-07-14 13:30:03 -070070 const std::string& name_prefix,
71 bool measure_read_barrier_slow_path)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080072 : GarbageCollector(heap,
73 name_prefix + (name_prefix.empty() ? "" : " ") +
Hiroshi Yamauchi88e08162017-01-06 15:03:26 -080074 "concurrent copying"),
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070075 region_space_(nullptr), gc_barrier_(new Barrier(0)),
76 gc_mark_stack_(accounting::ObjectStack::Create("concurrent copying gc mark stack",
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -070077 kDefaultGcMarkStackSize,
78 kDefaultGcMarkStackSize)),
Mathieu Chartier36a270a2016-07-28 18:08:51 -070079 rb_mark_bit_stack_(accounting::ObjectStack::Create("rb copying gc mark stack",
80 kReadBarrierMarkStackSize,
81 kReadBarrierMarkStackSize)),
82 rb_mark_bit_stack_full_(false),
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070083 mark_stack_lock_("concurrent copying mark stack lock", kMarkSweepMarkStackLock),
84 thread_running_gc_(nullptr),
Andreas Gamped9911ee2017-03-27 13:27:24 -070085 is_marking_(false),
Mathieu Chartier3768ade2017-05-02 14:04:39 -070086 is_using_read_barrier_entrypoints_(false),
Andreas Gamped9911ee2017-03-27 13:27:24 -070087 is_active_(false),
88 is_asserting_to_space_invariant_(false),
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -070089 region_space_bitmap_(nullptr),
Andreas Gamped9911ee2017-03-27 13:27:24 -070090 heap_mark_bitmap_(nullptr),
91 live_stack_freeze_size_(0),
92 from_space_num_objects_at_first_pause_(0),
93 from_space_num_bytes_at_first_pause_(0),
94 mark_stack_mode_(kMarkStackModeOff),
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070095 weak_ref_access_enabled_(true),
Albert Mingkun Yange260e542018-11-05 13:45:59 +000096 copied_live_bytes_ratio_sum_(0.f),
97 gc_count_(0),
Lokesh Gidra1c34b712018-12-18 13:41:58 -080098 region_space_inter_region_bitmap_(nullptr),
99 non_moving_space_inter_region_bitmap_(nullptr),
Albert Mingkun Yangaf9cce12018-11-07 09:58:35 +0000100 reclaimed_bytes_ratio_sum_(0.f),
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700101 young_gen_(young_gen),
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800102 skipped_blocks_lock_("concurrent copying bytes blocks lock", kMarkSweepMarkStackLock),
Mathieu Chartier56fe2582016-07-14 13:30:03 -0700103 measure_read_barrier_slow_path_(measure_read_barrier_slow_path),
Andreas Gamped9911ee2017-03-27 13:27:24 -0700104 mark_from_read_barrier_measurements_(false),
Mathieu Chartier56fe2582016-07-14 13:30:03 -0700105 rb_slow_path_ns_(0),
106 rb_slow_path_count_(0),
107 rb_slow_path_count_gc_(0),
108 rb_slow_path_histogram_lock_("Read barrier histogram lock"),
109 rb_slow_path_time_histogram_("Mutator time in read barrier slow path", 500, 32),
110 rb_slow_path_count_total_(0),
111 rb_slow_path_count_gc_total_(0),
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800112 rb_table_(heap_->GetReadBarrierTable()),
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700113 force_evacuate_all_(false),
Andreas Gamped9911ee2017-03-27 13:27:24 -0700114 gc_grays_immune_objects_(false),
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700115 immune_gray_stack_lock_("concurrent copying immune gray stack lock",
Albert Mingkun Yangaf9cce12018-11-07 09:58:35 +0000116 kMarkSweepMarkStackLock),
117 num_bytes_allocated_before_gc_(0) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800118 static_assert(space::RegionSpace::kRegionSize == accounting::ReadBarrierTable::kRegionSize,
119 "The region space size and the read barrier table region size must match");
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700120 CHECK(kEnableGenerationalConcurrentCopyingCollection || !young_gen_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700121 Thread* self = Thread::Current();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800122 {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800123 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
124 // Cache this so that we won't have to lock heap_bitmap_lock_ in
125 // Mark() which could cause a nested lock on heap_bitmap_lock_
126 // when GC causes a RB while doing GC or a lock order violation
127 // (class_linker_lock_ and heap_bitmap_lock_).
128 heap_mark_bitmap_ = heap->GetMarkBitmap();
129 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700130 {
131 MutexLock mu(self, mark_stack_lock_);
132 for (size_t i = 0; i < kMarkStackPoolSize; ++i) {
133 accounting::AtomicStack<mirror::Object>* mark_stack =
134 accounting::AtomicStack<mirror::Object>::Create(
135 "thread local mark stack", kMarkStackSize, kMarkStackSize);
136 pooled_mark_stacks_.push_back(mark_stack);
137 }
138 }
Roland Levillainb1e1dc32018-07-10 19:19:31 +0100139 if (kEnableGenerationalConcurrentCopyingCollection) {
140 // Allocate sweep array free buffer.
141 std::string error_msg;
142 sweep_array_free_buffer_mem_map_ = MemMap::MapAnonymous(
143 "concurrent copying sweep array free buffer",
Roland Levillainb1e1dc32018-07-10 19:19:31 +0100144 RoundUp(kSweepArrayChunkFreeSize * sizeof(mirror::Object*), kPageSize),
145 PROT_READ | PROT_WRITE,
Vladimir Marko11306592018-10-26 14:22:59 +0100146 /*low_4gb=*/ false,
Roland Levillainb1e1dc32018-07-10 19:19:31 +0100147 &error_msg);
148 CHECK(sweep_array_free_buffer_mem_map_.IsValid())
149 << "Couldn't allocate sweep array free buffer: " << error_msg;
150 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800151}
152
Hiroshi Yamauchi057d9772017-02-17 15:33:23 -0800153void ConcurrentCopying::MarkHeapReference(mirror::HeapReference<mirror::Object>* field,
154 bool do_atomic_update) {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -0800155 Thread* const self = Thread::Current();
Hiroshi Yamauchi057d9772017-02-17 15:33:23 -0800156 if (UNLIKELY(do_atomic_update)) {
157 // Used to mark the referent in DelayReferenceReferent in transaction mode.
158 mirror::Object* from_ref = field->AsMirrorPtr();
159 if (from_ref == nullptr) {
160 return;
161 }
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -0800162 mirror::Object* to_ref = Mark(self, from_ref);
Hiroshi Yamauchi057d9772017-02-17 15:33:23 -0800163 if (from_ref != to_ref) {
164 do {
165 if (field->AsMirrorPtr() != from_ref) {
166 // Concurrently overwritten by a mutator.
167 break;
168 }
169 } while (!field->CasWeakRelaxed(from_ref, to_ref));
170 }
171 } else {
172 // Used for preserving soft references, should be OK to not have a CAS here since there should be
173 // no other threads which can trigger read barriers on the same referent during reference
174 // processing.
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -0800175 field->Assign(Mark(self, field->AsMirrorPtr()));
Hiroshi Yamauchi057d9772017-02-17 15:33:23 -0800176 }
Mathieu Chartier97509952015-07-13 14:35:43 -0700177}
178
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800179ConcurrentCopying::~ConcurrentCopying() {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700180 STLDeleteElements(&pooled_mark_stacks_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800181}
182
183void ConcurrentCopying::RunPhases() {
184 CHECK(kUseBakerReadBarrier || kUseTableLookupReadBarrier);
185 CHECK(!is_active_);
186 is_active_ = true;
187 Thread* self = Thread::Current();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700188 thread_running_gc_ = self;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800189 Locks::mutator_lock_->AssertNotHeld(self);
190 {
191 ReaderMutexLock mu(self, *Locks::mutator_lock_);
192 InitializePhase();
Lokesh Gidra2a9824c2018-11-07 15:57:17 -0800193 // In case of forced evacuation, all regions are evacuated and hence no
194 // need to compute live_bytes.
195 if (kEnableGenerationalConcurrentCopyingCollection && !young_gen_ && !force_evacuate_all_) {
196 MarkingPhase();
197 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800198 }
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700199 if (kUseBakerReadBarrier && kGrayDirtyImmuneObjects) {
200 // Switch to read barrier mark entrypoints before we gray the objects. This is required in case
Roland Levillain97c46462017-05-11 14:04:03 +0100201 // a mutator sees a gray bit and dispatches on the entrypoint. (b/37876887).
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700202 ActivateReadBarrierEntrypoints();
203 // Gray dirty immune objects concurrently to reduce GC pause times. We re-process gray cards in
204 // the pause.
205 ReaderMutexLock mu(self, *Locks::mutator_lock_);
206 GrayAllDirtyImmuneObjects();
207 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800208 FlipThreadRoots();
209 {
210 ReaderMutexLock mu(self, *Locks::mutator_lock_);
Lokesh Gidra2a9824c2018-11-07 15:57:17 -0800211 CopyingPhase();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800212 }
213 // Verify no from space refs. This causes a pause.
Andreas Gampee3ce7872017-02-22 13:36:21 -0800214 if (kEnableNoFromSpaceRefsVerification) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800215 TimingLogger::ScopedTiming split("(Paused)VerifyNoFromSpaceReferences", GetTimings());
Andreas Gampe4934eb12017-01-30 13:15:26 -0800216 ScopedPause pause(this, false);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700217 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800218 if (kVerboseMode) {
219 LOG(INFO) << "Verifying no from-space refs";
220 }
221 VerifyNoFromSpaceReferences();
Mathieu Chartier720e71a2015-04-06 17:10:58 -0700222 if (kVerboseMode) {
223 LOG(INFO) << "Done verifying no from-space refs";
224 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700225 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800226 }
227 {
228 ReaderMutexLock mu(self, *Locks::mutator_lock_);
229 ReclaimPhase();
230 }
231 FinishPhase();
232 CHECK(is_active_);
233 is_active_ = false;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700234 thread_running_gc_ = nullptr;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800235}
236
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700237class ConcurrentCopying::ActivateReadBarrierEntrypointsCheckpoint : public Closure {
238 public:
239 explicit ActivateReadBarrierEntrypointsCheckpoint(ConcurrentCopying* concurrent_copying)
240 : concurrent_copying_(concurrent_copying) {}
241
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100242 void Run(Thread* thread) override NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700243 // Note: self is not necessarily equal to thread since thread may be suspended.
244 Thread* self = Thread::Current();
245 DCHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
246 << thread->GetState() << " thread " << thread << " self " << self;
247 // Switch to the read barrier entrypoints.
248 thread->SetReadBarrierEntrypoints();
249 // If thread is a running mutator, then act on behalf of the garbage collector.
250 // See the code in ThreadList::RunCheckpoint.
251 concurrent_copying_->GetBarrier().Pass(self);
252 }
253
254 private:
255 ConcurrentCopying* const concurrent_copying_;
256};
257
258class ConcurrentCopying::ActivateReadBarrierEntrypointsCallback : public Closure {
259 public:
260 explicit ActivateReadBarrierEntrypointsCallback(ConcurrentCopying* concurrent_copying)
261 : concurrent_copying_(concurrent_copying) {}
262
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100263 void Run(Thread* self ATTRIBUTE_UNUSED) override REQUIRES(Locks::thread_list_lock_) {
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700264 // This needs to run under the thread_list_lock_ critical section in ThreadList::RunCheckpoint()
265 // to avoid a race with ThreadList::Register().
266 CHECK(!concurrent_copying_->is_using_read_barrier_entrypoints_);
267 concurrent_copying_->is_using_read_barrier_entrypoints_ = true;
268 }
269
270 private:
271 ConcurrentCopying* const concurrent_copying_;
272};
273
274void ConcurrentCopying::ActivateReadBarrierEntrypoints() {
275 Thread* const self = Thread::Current();
276 ActivateReadBarrierEntrypointsCheckpoint checkpoint(this);
277 ThreadList* thread_list = Runtime::Current()->GetThreadList();
278 gc_barrier_->Init(self, 0);
279 ActivateReadBarrierEntrypointsCallback callback(this);
280 const size_t barrier_count = thread_list->RunCheckpoint(&checkpoint, &callback);
281 // If there are no threads to wait which implies that all the checkpoint functions are finished,
282 // then no need to release the mutator lock.
283 if (barrier_count == 0) {
284 return;
285 }
286 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
287 gc_barrier_->Increment(self, barrier_count);
288}
289
Lokesh Gidra1c34b712018-12-18 13:41:58 -0800290void ConcurrentCopying::CreateInterRegionRefBitmaps() {
291 DCHECK(kEnableGenerationalConcurrentCopyingCollection);
292 DCHECK(region_space_inter_region_bitmap_ == nullptr);
293 DCHECK(non_moving_space_inter_region_bitmap_ == nullptr);
294 DCHECK(region_space_ != nullptr);
295 DCHECK(heap_->non_moving_space_ != nullptr);
296 // Region-space
297 region_space_inter_region_bitmap_ = accounting::ContinuousSpaceBitmap::Create(
298 "region-space inter region ref bitmap",
299 reinterpret_cast<uint8_t*>(region_space_->Begin()),
300 region_space_->Limit() - region_space_->Begin());
301 CHECK(region_space_inter_region_bitmap_ != nullptr)
302 << "Couldn't allocate region-space inter region ref bitmap";
303
304 // non-moving-space
305 non_moving_space_inter_region_bitmap_ = accounting::ContinuousSpaceBitmap::Create(
306 "non-moving-space inter region ref bitmap",
307 reinterpret_cast<uint8_t*>(heap_->non_moving_space_->Begin()),
308 heap_->non_moving_space_->Limit() - heap_->non_moving_space_->Begin());
309 CHECK(non_moving_space_inter_region_bitmap_ != nullptr)
310 << "Couldn't allocate non-moving-space inter region ref bitmap";
311}
312
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800313void ConcurrentCopying::BindBitmaps() {
314 Thread* self = Thread::Current();
315 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
316 // Mark all of the spaces we never collect as immune.
317 for (const auto& space : heap_->GetContinuousSpaces()) {
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800318 if (space->GetGcRetentionPolicy() == space::kGcRetentionPolicyNeverCollect ||
319 space->GetGcRetentionPolicy() == space::kGcRetentionPolicyFullCollect) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800320 CHECK(space->IsZygoteSpace() || space->IsImageSpace());
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800321 immune_spaces_.AddSpace(space);
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700322 } else {
323 CHECK(!space->IsZygoteSpace());
324 CHECK(!space->IsImageSpace());
Lokesh Gidra1c34b712018-12-18 13:41:58 -0800325 CHECK(space == region_space_ || space == heap_->non_moving_space_);
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700326 if (kEnableGenerationalConcurrentCopyingCollection) {
327 if (space == region_space_) {
328 region_space_bitmap_ = region_space_->GetMarkBitmap();
329 } else if (young_gen_ && space->IsContinuousMemMapAllocSpace()) {
330 DCHECK_EQ(space->GetGcRetentionPolicy(), space::kGcRetentionPolicyAlwaysCollect);
331 space->AsContinuousMemMapAllocSpace()->BindLiveToMarkBitmap();
332 }
Lokesh Gidra2a9824c2018-11-07 15:57:17 -0800333 if (young_gen_) {
334 // Age all of the cards for the region space so that we know which evac regions to scan.
335 heap_->GetCardTable()->ModifyCardsAtomic(space->Begin(),
336 space->End(),
337 AgeCardVisitor(),
338 VoidFunctor());
339 } else {
340 // In a full-heap GC cycle, the card-table corresponding to region-space and
341 // non-moving space can be cleared, because this cycle only needs to
342 // capture writes during the marking phase of this cycle to catch
343 // objects that skipped marking due to heap mutation. Furthermore,
344 // if the next GC is a young-gen cycle, then it only needs writes to
345 // be captured after the thread-flip of this GC cycle, as that is when
346 // the young-gen for the next GC cycle starts getting populated.
347 heap_->GetCardTable()->ClearCardRange(space->Begin(), space->Limit());
348 }
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700349 } else {
350 if (space == region_space_) {
351 // It is OK to clear the bitmap with mutators running since the only place it is read is
352 // VisitObjects which has exclusion with CC.
353 region_space_bitmap_ = region_space_->GetMarkBitmap();
354 region_space_bitmap_->Clear();
355 }
356 }
357 }
358 }
Lokesh Gidra1c34b712018-12-18 13:41:58 -0800359 if (kEnableGenerationalConcurrentCopyingCollection && young_gen_) {
360 for (const auto& space : GetHeap()->GetDiscontinuousSpaces()) {
361 CHECK(space->IsLargeObjectSpace());
362 space->AsLargeObjectSpace()->CopyLiveToMarked();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800363 }
364 }
365}
366
367void ConcurrentCopying::InitializePhase() {
368 TimingLogger::ScopedTiming split("InitializePhase", GetTimings());
Albert Mingkun Yangaf9cce12018-11-07 09:58:35 +0000369 num_bytes_allocated_before_gc_ = static_cast<int64_t>(heap_->GetBytesAllocated());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800370 if (kVerboseMode) {
371 LOG(INFO) << "GC InitializePhase";
372 LOG(INFO) << "Region-space : " << reinterpret_cast<void*>(region_space_->Begin()) << "-"
373 << reinterpret_cast<void*>(region_space_->Limit());
374 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700375 CheckEmptyMarkStack();
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700376 rb_mark_bit_stack_full_ = false;
Mathieu Chartier56fe2582016-07-14 13:30:03 -0700377 mark_from_read_barrier_measurements_ = measure_read_barrier_slow_path_;
378 if (measure_read_barrier_slow_path_) {
Orion Hodson88591fe2018-03-06 13:35:43 +0000379 rb_slow_path_ns_.store(0, std::memory_order_relaxed);
380 rb_slow_path_count_.store(0, std::memory_order_relaxed);
381 rb_slow_path_count_gc_.store(0, std::memory_order_relaxed);
Mathieu Chartier56fe2582016-07-14 13:30:03 -0700382 }
383
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800384 immune_spaces_.Reset();
Orion Hodson88591fe2018-03-06 13:35:43 +0000385 bytes_moved_.store(0, std::memory_order_relaxed);
386 objects_moved_.store(0, std::memory_order_relaxed);
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -0800387 bytes_moved_gc_thread_ = 0;
388 objects_moved_gc_thread_ = 0;
Hiroshi Yamauchi60985b72016-08-24 13:53:12 -0700389 GcCause gc_cause = GetCurrentIteration()->GetGcCause();
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700390
391 force_evacuate_all_ = false;
392 if (!kEnableGenerationalConcurrentCopyingCollection || !young_gen_) {
393 if (gc_cause == kGcCauseExplicit ||
394 gc_cause == kGcCauseCollectorTransition ||
395 GetCurrentIteration()->GetClearSoftReferences()) {
396 force_evacuate_all_ = true;
397 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800398 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700399 if (kUseBakerReadBarrier) {
Orion Hodson88591fe2018-03-06 13:35:43 +0000400 updated_all_immune_objects_.store(false, std::memory_order_relaxed);
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700401 // GC may gray immune objects in the thread flip.
402 gc_grays_immune_objects_ = true;
403 if (kIsDebugBuild) {
404 MutexLock mu(Thread::Current(), immune_gray_stack_lock_);
405 DCHECK(immune_gray_stack_.empty());
406 }
407 }
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700408 if (kEnableGenerationalConcurrentCopyingCollection) {
Roland Levillain2d94e292018-08-15 16:46:30 +0100409 done_scanning_.store(false, std::memory_order_release);
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700410 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800411 BindBitmaps();
412 if (kVerboseMode) {
Roland Levillain57ce0542018-08-07 16:20:31 +0100413 LOG(INFO) << "young_gen=" << std::boolalpha << young_gen_ << std::noboolalpha;
414 LOG(INFO) << "force_evacuate_all=" << std::boolalpha << force_evacuate_all_ << std::noboolalpha;
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800415 LOG(INFO) << "Largest immune region: " << immune_spaces_.GetLargestImmuneRegion().Begin()
416 << "-" << immune_spaces_.GetLargestImmuneRegion().End();
417 for (space::ContinuousSpace* space : immune_spaces_.GetSpaces()) {
418 LOG(INFO) << "Immune space: " << *space;
419 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800420 LOG(INFO) << "GC end of InitializePhase";
421 }
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700422 if (kEnableGenerationalConcurrentCopyingCollection && !young_gen_) {
423 region_space_bitmap_->Clear();
424 }
Lokesh Gidra2a9824c2018-11-07 15:57:17 -0800425 mark_stack_mode_.store(ConcurrentCopying::kMarkStackModeThreadLocal, std::memory_order_relaxed);
Mathieu Chartier962cd7a2016-08-16 12:15:59 -0700426 // Mark all of the zygote large objects without graying them.
427 MarkZygoteLargeObjects();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800428}
429
430// Used to switch the thread roots of a thread from from-space refs to to-space refs.
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700431class ConcurrentCopying::ThreadFlipVisitor : public Closure, public RootVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800432 public:
Roland Levillain3887c462015-08-12 18:15:42 +0100433 ThreadFlipVisitor(ConcurrentCopying* concurrent_copying, bool use_tlab)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800434 : concurrent_copying_(concurrent_copying), use_tlab_(use_tlab) {
435 }
436
Roland Levillainf73caca2018-08-24 17:19:07 +0100437 void Run(Thread* thread) override REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800438 // Note: self is not necessarily equal to thread since thread may be suspended.
439 Thread* self = Thread::Current();
440 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
441 << thread->GetState() << " thread " << thread << " self " << self;
Mathieu Chartierfe814e82016-11-09 14:32:49 -0800442 thread->SetIsGcMarkingAndUpdateEntrypoints(true);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800443 if (use_tlab_ && thread->HasTlab()) {
444 if (ConcurrentCopying::kEnableFromSpaceAccountingCheck) {
445 // This must come before the revoke.
446 size_t thread_local_objects = thread->GetThreadLocalObjectsAllocated();
447 concurrent_copying_->region_space_->RevokeThreadLocalBuffers(thread);
Roland Levillain2ae376f2018-01-30 11:35:11 +0000448 reinterpret_cast<Atomic<size_t>*>(
449 &concurrent_copying_->from_space_num_objects_at_first_pause_)->
Hans Boehmfb8b4e22018-09-05 16:45:42 -0700450 fetch_add(thread_local_objects, std::memory_order_relaxed);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800451 } else {
452 concurrent_copying_->region_space_->RevokeThreadLocalBuffers(thread);
453 }
454 }
455 if (kUseThreadLocalAllocationStack) {
456 thread->RevokeThreadLocalAllocationStack();
457 }
458 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700459 // We can use the non-CAS VisitRoots functions below because we update thread-local GC roots
460 // only.
Andreas Gampe513061a2017-06-01 09:17:34 -0700461 thread->VisitRoots(this, kVisitRootFlagAllRoots);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800462 concurrent_copying_->GetBarrier().Pass(self);
463 }
464
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700465 void VisitRoots(mirror::Object*** roots,
466 size_t count,
Andreas Gampefa6a1b02018-09-07 08:11:55 -0700467 const RootInfo& info ATTRIBUTE_UNUSED) override
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700468 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -0800469 Thread* self = Thread::Current();
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700470 for (size_t i = 0; i < count; ++i) {
471 mirror::Object** root = roots[i];
472 mirror::Object* ref = *root;
473 if (ref != nullptr) {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -0800474 mirror::Object* to_ref = concurrent_copying_->Mark(self, ref);
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700475 if (to_ref != ref) {
476 *root = to_ref;
477 }
478 }
479 }
480 }
481
482 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots,
483 size_t count,
Andreas Gampefa6a1b02018-09-07 08:11:55 -0700484 const RootInfo& info ATTRIBUTE_UNUSED) override
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700485 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -0800486 Thread* self = Thread::Current();
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700487 for (size_t i = 0; i < count; ++i) {
488 mirror::CompressedReference<mirror::Object>* const root = roots[i];
489 if (!root->IsNull()) {
490 mirror::Object* ref = root->AsMirrorPtr();
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -0800491 mirror::Object* to_ref = concurrent_copying_->Mark(self, ref);
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700492 if (to_ref != ref) {
493 root->Assign(to_ref);
494 }
495 }
496 }
497 }
498
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800499 private:
500 ConcurrentCopying* const concurrent_copying_;
501 const bool use_tlab_;
502};
503
504// Called back from Runtime::FlipThreadRoots() during a pause.
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700505class ConcurrentCopying::FlipCallback : public Closure {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800506 public:
507 explicit FlipCallback(ConcurrentCopying* concurrent_copying)
508 : concurrent_copying_(concurrent_copying) {
509 }
510
Roland Levillainf73caca2018-08-24 17:19:07 +0100511 void Run(Thread* thread) override REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800512 ConcurrentCopying* cc = concurrent_copying_;
513 TimingLogger::ScopedTiming split("(Paused)FlipCallback", cc->GetTimings());
514 // Note: self is not necessarily equal to thread since thread may be suspended.
515 Thread* self = Thread::Current();
Lokesh Gidra2a9824c2018-11-07 15:57:17 -0800516 if (kVerifyNoMissingCardMarks && cc->young_gen_) {
Mathieu Chartiera1467d02017-02-22 09:22:50 -0800517 cc->VerifyNoMissingCardMarks();
518 }
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700519 CHECK_EQ(thread, self);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800520 Locks::mutator_lock_->AssertExclusiveHeld(self);
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700521 space::RegionSpace::EvacMode evac_mode = space::RegionSpace::kEvacModeLivePercentNewlyAllocated;
522 if (cc->young_gen_) {
523 CHECK(!cc->force_evacuate_all_);
524 evac_mode = space::RegionSpace::kEvacModeNewlyAllocated;
525 } else if (cc->force_evacuate_all_) {
526 evac_mode = space::RegionSpace::kEvacModeForceAll;
527 }
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700528 {
529 TimingLogger::ScopedTiming split2("(Paused)SetFromSpace", cc->GetTimings());
Lokesh Gidra2a9824c2018-11-07 15:57:17 -0800530 // Only change live bytes for 1-phase full heap CC.
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700531 cc->region_space_->SetFromSpace(
Lokesh Gidra2a9824c2018-11-07 15:57:17 -0800532 cc->rb_table_,
533 evac_mode,
534 /*clear_live_bytes=*/ !kEnableGenerationalConcurrentCopyingCollection);
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700535 }
Mathieu Chartiera4f6af92015-08-11 17:35:25 -0700536 cc->SwapStacks();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800537 if (ConcurrentCopying::kEnableFromSpaceAccountingCheck) {
538 cc->RecordLiveStackFreezeSize(self);
539 cc->from_space_num_objects_at_first_pause_ = cc->region_space_->GetObjectsAllocated();
540 cc->from_space_num_bytes_at_first_pause_ = cc->region_space_->GetBytesAllocated();
541 }
542 cc->is_marking_ = true;
Lokesh Gidra2a9824c2018-11-07 15:57:17 -0800543 if (kIsDebugBuild && !kEnableGenerationalConcurrentCopyingCollection) {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800544 cc->region_space_->AssertAllRegionLiveBytesZeroOrCleared();
545 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800546 if (UNLIKELY(Runtime::Current()->IsActiveTransaction())) {
Mathieu Chartier184c9dc2015-03-05 13:20:54 -0800547 CHECK(Runtime::Current()->IsAotCompiler());
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700548 TimingLogger::ScopedTiming split3("(Paused)VisitTransactionRoots", cc->GetTimings());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700549 Runtime::Current()->VisitTransactionRoots(cc);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800550 }
Mathieu Chartier21328a12016-07-22 10:47:45 -0700551 if (kUseBakerReadBarrier && kGrayDirtyImmuneObjects) {
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700552 cc->GrayAllNewlyDirtyImmuneObjects();
Mathieu Chartier21328a12016-07-22 10:47:45 -0700553 if (kIsDebugBuild) {
Roland Levillain001eff92018-01-24 14:24:33 +0000554 // Check that all non-gray immune objects only reference immune objects.
Mathieu Chartier21328a12016-07-22 10:47:45 -0700555 cc->VerifyGrayImmuneObjects();
556 }
557 }
Mathieu Chartier9aef9922017-04-23 13:53:50 -0700558 // May be null during runtime creation, in this case leave java_lang_Object null.
559 // This is safe since single threaded behavior should mean FillDummyObject does not
560 // happen when java_lang_Object_ is null.
561 if (WellKnownClasses::java_lang_Object != nullptr) {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -0800562 cc->java_lang_Object_ = down_cast<mirror::Class*>(cc->Mark(thread,
Mathieu Chartier9aef9922017-04-23 13:53:50 -0700563 WellKnownClasses::ToClass(WellKnownClasses::java_lang_Object).Ptr()));
564 } else {
565 cc->java_lang_Object_ = nullptr;
566 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800567 }
568
569 private:
570 ConcurrentCopying* const concurrent_copying_;
571};
572
Mathieu Chartier21328a12016-07-22 10:47:45 -0700573class ConcurrentCopying::VerifyGrayImmuneObjectsVisitor {
574 public:
575 explicit VerifyGrayImmuneObjectsVisitor(ConcurrentCopying* collector)
576 : collector_(collector) {}
577
Mathieu Chartier31e88222016-10-14 18:43:19 -0700578 void operator()(ObjPtr<mirror::Object> obj, MemberOffset offset, bool /* is_static */)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700579 const ALWAYS_INLINE REQUIRES_SHARED(Locks::mutator_lock_)
580 REQUIRES_SHARED(Locks::heap_bitmap_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700581 CheckReference(obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(offset),
582 obj, offset);
583 }
584
Mathieu Chartier31e88222016-10-14 18:43:19 -0700585 void operator()(ObjPtr<mirror::Class> klass, ObjPtr<mirror::Reference> ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700586 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700587 CHECK(klass->IsTypeOfReferenceClass());
588 CheckReference(ref->GetReferent<kWithoutReadBarrier>(),
589 ref,
590 mirror::Reference::ReferentOffset());
591 }
592
593 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
594 ALWAYS_INLINE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700595 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700596 if (!root->IsNull()) {
597 VisitRoot(root);
598 }
599 }
600
601 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
602 ALWAYS_INLINE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700603 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700604 CheckReference(root->AsMirrorPtr(), nullptr, MemberOffset(0));
605 }
606
607 private:
608 ConcurrentCopying* const collector_;
609
Mathieu Chartier31e88222016-10-14 18:43:19 -0700610 void CheckReference(ObjPtr<mirror::Object> ref,
611 ObjPtr<mirror::Object> holder,
612 MemberOffset offset) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700613 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700614 if (ref != nullptr) {
Mathieu Chartier31e88222016-10-14 18:43:19 -0700615 if (!collector_->immune_spaces_.ContainsObject(ref.Ptr())) {
Mathieu Chartier962cd7a2016-08-16 12:15:59 -0700616 // Not immune, must be a zygote large object.
Lokesh Gidra02c230c2018-10-10 23:48:43 -0700617 space::LargeObjectSpace* large_object_space =
618 Runtime::Current()->GetHeap()->GetLargeObjectsSpace();
619 CHECK(large_object_space->Contains(ref.Ptr()) &&
620 large_object_space->IsZygoteLargeObject(Thread::Current(), ref.Ptr()))
Mathieu Chartier962cd7a2016-08-16 12:15:59 -0700621 << "Non gray object references non immune, non zygote large object "<< ref << " "
David Sehr709b0702016-10-13 09:12:37 -0700622 << mirror::Object::PrettyTypeOf(ref) << " in holder " << holder << " "
623 << mirror::Object::PrettyTypeOf(holder) << " offset=" << offset.Uint32Value();
Mathieu Chartier962cd7a2016-08-16 12:15:59 -0700624 } else {
625 // Make sure the large object class is immune since we will never scan the large object.
626 CHECK(collector_->immune_spaces_.ContainsObject(
627 ref->GetClass<kVerifyNone, kWithoutReadBarrier>()));
628 }
Mathieu Chartier21328a12016-07-22 10:47:45 -0700629 }
630 }
631};
632
633void ConcurrentCopying::VerifyGrayImmuneObjects() {
634 TimingLogger::ScopedTiming split(__FUNCTION__, GetTimings());
635 for (auto& space : immune_spaces_.GetSpaces()) {
636 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
637 accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
638 VerifyGrayImmuneObjectsVisitor visitor(this);
639 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()),
640 reinterpret_cast<uintptr_t>(space->Limit()),
641 [&visitor](mirror::Object* obj)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700642 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700643 // If an object is not gray, it should only have references to things in the immune spaces.
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700644 if (obj->GetReadBarrierState() != ReadBarrier::GrayState()) {
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700645 obj->VisitReferences</*kVisitNativeRoots=*/true,
Mathieu Chartier21328a12016-07-22 10:47:45 -0700646 kDefaultVerifyFlags,
647 kWithoutReadBarrier>(visitor, visitor);
648 }
649 });
650 }
651}
652
Mathieu Chartiera1467d02017-02-22 09:22:50 -0800653class ConcurrentCopying::VerifyNoMissingCardMarkVisitor {
654 public:
655 VerifyNoMissingCardMarkVisitor(ConcurrentCopying* cc, ObjPtr<mirror::Object> holder)
656 : cc_(cc),
657 holder_(holder) {}
658
659 void operator()(ObjPtr<mirror::Object> obj,
660 MemberOffset offset,
661 bool is_static ATTRIBUTE_UNUSED) const
662 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
663 if (offset.Uint32Value() != mirror::Object::ClassOffset().Uint32Value()) {
664 CheckReference(obj->GetFieldObject<mirror::Object, kDefaultVerifyFlags, kWithoutReadBarrier>(
665 offset), offset.Uint32Value());
666 }
667 }
668 void operator()(ObjPtr<mirror::Class> klass,
669 ObjPtr<mirror::Reference> ref) const
670 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
671 CHECK(klass->IsTypeOfReferenceClass());
672 this->operator()(ref, mirror::Reference::ReferentOffset(), false);
673 }
674
675 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
676 REQUIRES_SHARED(Locks::mutator_lock_) {
677 if (!root->IsNull()) {
678 VisitRoot(root);
679 }
680 }
681
682 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
683 REQUIRES_SHARED(Locks::mutator_lock_) {
684 CheckReference(root->AsMirrorPtr());
685 }
686
687 void CheckReference(mirror::Object* ref, int32_t offset = -1) const
688 REQUIRES_SHARED(Locks::mutator_lock_) {
Roland Levillainb9c68342018-09-04 18:56:31 +0100689 if (ref != nullptr && cc_->region_space_->IsInNewlyAllocatedRegion(ref)) {
690 LOG(FATAL_WITHOUT_ABORT)
Mathieu Chartiera1467d02017-02-22 09:22:50 -0800691 << holder_->PrettyTypeOf() << "(" << holder_.Ptr() << ") references object "
692 << ref->PrettyTypeOf() << "(" << ref << ") in newly allocated region at offset=" << offset;
Roland Levillainb9c68342018-09-04 18:56:31 +0100693 LOG(FATAL_WITHOUT_ABORT) << "time=" << cc_->region_space_->Time();
694 constexpr const char* kIndent = " ";
695 LOG(FATAL_WITHOUT_ABORT) << cc_->DumpReferenceInfo(holder_.Ptr(), "holder_", kIndent);
696 LOG(FATAL_WITHOUT_ABORT) << cc_->DumpReferenceInfo(ref, "ref", kIndent);
697 LOG(FATAL) << "Unexpected reference to newly allocated region.";
698 }
Mathieu Chartiera1467d02017-02-22 09:22:50 -0800699 }
700
701 private:
702 ConcurrentCopying* const cc_;
703 ObjPtr<mirror::Object> const holder_;
704};
705
Mathieu Chartiera1467d02017-02-22 09:22:50 -0800706void ConcurrentCopying::VerifyNoMissingCardMarks() {
Andreas Gampe0c183382017-07-13 22:26:24 -0700707 auto visitor = [&](mirror::Object* obj)
708 REQUIRES(Locks::mutator_lock_)
709 REQUIRES(!mark_stack_lock_) {
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700710 // Objects on clean cards should never have references to newly allocated regions. Note
711 // that aged cards are also not clean.
Andreas Gampe0c183382017-07-13 22:26:24 -0700712 if (heap_->GetCardTable()->GetCard(obj) == gc::accounting::CardTable::kCardClean) {
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700713 VerifyNoMissingCardMarkVisitor internal_visitor(this, /*holder=*/ obj);
714 obj->VisitReferences</*kVisitNativeRoots=*/true, kVerifyNone, kWithoutReadBarrier>(
Andreas Gampe0c183382017-07-13 22:26:24 -0700715 internal_visitor, internal_visitor);
716 }
717 };
Mathieu Chartiera1467d02017-02-22 09:22:50 -0800718 TimingLogger::ScopedTiming split(__FUNCTION__, GetTimings());
Andreas Gampe0c183382017-07-13 22:26:24 -0700719 region_space_->Walk(visitor);
Mathieu Chartiera1467d02017-02-22 09:22:50 -0800720 {
721 ReaderMutexLock rmu(Thread::Current(), *Locks::heap_bitmap_lock_);
Andreas Gampe0c183382017-07-13 22:26:24 -0700722 heap_->GetLiveBitmap()->Visit(visitor);
Mathieu Chartiera1467d02017-02-22 09:22:50 -0800723 }
724}
725
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800726// Switch threads that from from-space to to-space refs. Forward/mark the thread roots.
727void ConcurrentCopying::FlipThreadRoots() {
728 TimingLogger::ScopedTiming split("FlipThreadRoots", GetTimings());
Albert Mingkun Yangde94ea72018-11-16 10:15:49 +0000729 if (kVerboseMode || heap_->dump_region_info_before_gc_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800730 LOG(INFO) << "time=" << region_space_->Time();
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700731 region_space_->DumpNonFreeRegions(LOG_STREAM(INFO));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800732 }
733 Thread* self = Thread::Current();
734 Locks::mutator_lock_->AssertNotHeld(self);
735 gc_barrier_->Init(self, 0);
736 ThreadFlipVisitor thread_flip_visitor(this, heap_->use_tlab_);
737 FlipCallback flip_callback(this);
Andreas Gampe4934eb12017-01-30 13:15:26 -0800738
Andreas Gampe6e644452017-05-09 16:30:27 -0700739 size_t barrier_count = Runtime::Current()->GetThreadList()->FlipThreadRoots(
740 &thread_flip_visitor, &flip_callback, this, GetHeap()->GetGcPauseListener());
Andreas Gampe4934eb12017-01-30 13:15:26 -0800741
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800742 {
743 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
744 gc_barrier_->Increment(self, barrier_count);
745 }
746 is_asserting_to_space_invariant_ = true;
747 QuasiAtomic::ThreadFenceForConstructor();
748 if (kVerboseMode) {
749 LOG(INFO) << "time=" << region_space_->Time();
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700750 region_space_->DumpNonFreeRegions(LOG_STREAM(INFO));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800751 LOG(INFO) << "GC end of FlipThreadRoots";
752 }
753}
754
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700755template <bool kConcurrent>
Mathieu Chartier21328a12016-07-22 10:47:45 -0700756class ConcurrentCopying::GrayImmuneObjectVisitor {
757 public:
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700758 explicit GrayImmuneObjectVisitor(Thread* self) : self_(self) {}
Mathieu Chartier21328a12016-07-22 10:47:45 -0700759
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700760 ALWAYS_INLINE void operator()(mirror::Object* obj) const REQUIRES_SHARED(Locks::mutator_lock_) {
Roland Levillain14e5a292018-06-28 12:00:56 +0100761 if (kUseBakerReadBarrier && obj->GetReadBarrierState() == ReadBarrier::NonGrayState()) {
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700762 if (kConcurrent) {
763 Locks::mutator_lock_->AssertSharedHeld(self_);
Roland Levillain14e5a292018-06-28 12:00:56 +0100764 obj->AtomicSetReadBarrierState(ReadBarrier::NonGrayState(), ReadBarrier::GrayState());
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700765 // Mod union table VisitObjects may visit the same object multiple times so we can't check
766 // the result of the atomic set.
767 } else {
768 Locks::mutator_lock_->AssertExclusiveHeld(self_);
769 obj->SetReadBarrierState(ReadBarrier::GrayState());
Mathieu Chartier21328a12016-07-22 10:47:45 -0700770 }
Mathieu Chartier21328a12016-07-22 10:47:45 -0700771 }
772 }
773
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700774 static void Callback(mirror::Object* obj, void* arg) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700775 reinterpret_cast<GrayImmuneObjectVisitor<kConcurrent>*>(arg)->operator()(obj);
Mathieu Chartier21328a12016-07-22 10:47:45 -0700776 }
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700777
778 private:
779 Thread* const self_;
Mathieu Chartier21328a12016-07-22 10:47:45 -0700780};
781
782void ConcurrentCopying::GrayAllDirtyImmuneObjects() {
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700783 TimingLogger::ScopedTiming split("GrayAllDirtyImmuneObjects", GetTimings());
784 accounting::CardTable* const card_table = heap_->GetCardTable();
785 Thread* const self = Thread::Current();
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700786 using VisitorType = GrayImmuneObjectVisitor</* kIsConcurrent= */ true>;
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700787 VisitorType visitor(self);
788 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier21328a12016-07-22 10:47:45 -0700789 for (space::ContinuousSpace* space : immune_spaces_.GetSpaces()) {
790 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700791 accounting::ModUnionTable* table = heap_->FindModUnionTableFromSpace(space);
Mathieu Chartier21328a12016-07-22 10:47:45 -0700792 // Mark all the objects on dirty cards since these may point to objects in other space.
793 // Once these are marked, the GC will eventually clear them later.
794 // Table is non null for boot image and zygote spaces. It is only null for application image
795 // spaces.
796 if (table != nullptr) {
Mathieu Chartier6e6078a2016-10-24 15:45:41 -0700797 table->ProcessCards();
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700798 table->VisitObjects(&VisitorType::Callback, &visitor);
799 // Don't clear cards here since we need to rescan in the pause. If we cleared the cards here,
800 // there would be races with the mutator marking new cards.
801 } else {
802 // Keep cards aged if we don't have a mod-union table since we may need to scan them in future
803 // GCs. This case is for app images.
804 card_table->ModifyCardsAtomic(
805 space->Begin(),
806 space->End(),
807 [](uint8_t card) {
808 return (card != gc::accounting::CardTable::kCardClean)
809 ? gc::accounting::CardTable::kCardAged
810 : card;
811 },
812 /* card modified visitor */ VoidFunctor());
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700813 card_table->Scan</*kClearCard=*/ false>(space->GetMarkBitmap(),
814 space->Begin(),
815 space->End(),
816 visitor,
817 gc::accounting::CardTable::kCardAged);
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700818 }
819 }
820}
821
822void ConcurrentCopying::GrayAllNewlyDirtyImmuneObjects() {
823 TimingLogger::ScopedTiming split("(Paused)GrayAllNewlyDirtyImmuneObjects", GetTimings());
824 accounting::CardTable* const card_table = heap_->GetCardTable();
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700825 using VisitorType = GrayImmuneObjectVisitor</* kIsConcurrent= */ false>;
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700826 Thread* const self = Thread::Current();
827 VisitorType visitor(self);
828 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
829 for (space::ContinuousSpace* space : immune_spaces_.GetSpaces()) {
830 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
831 accounting::ModUnionTable* table = heap_->FindModUnionTableFromSpace(space);
832
833 // Don't need to scan aged cards since we did these before the pause. Note that scanning cards
834 // also handles the mod-union table cards.
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700835 card_table->Scan</*kClearCard=*/ false>(space->GetMarkBitmap(),
836 space->Begin(),
837 space->End(),
838 visitor,
839 gc::accounting::CardTable::kCardDirty);
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700840 if (table != nullptr) {
841 // Add the cards to the mod-union table so that we can clear cards to save RAM.
842 table->ProcessCards();
Mathieu Chartier6e6078a2016-10-24 15:45:41 -0700843 TimingLogger::ScopedTiming split2("(Paused)ClearCards", GetTimings());
844 card_table->ClearCardRange(space->Begin(),
845 AlignDown(space->End(), accounting::CardTable::kCardSize));
Mathieu Chartier21328a12016-07-22 10:47:45 -0700846 }
847 }
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700848 // Since all of the objects that may point to other spaces are gray, we can avoid all the read
Mathieu Chartier21328a12016-07-22 10:47:45 -0700849 // barriers in the immune spaces.
Orion Hodson88591fe2018-03-06 13:35:43 +0000850 updated_all_immune_objects_.store(true, std::memory_order_relaxed);
Mathieu Chartier21328a12016-07-22 10:47:45 -0700851}
852
Mathieu Chartiera4f6af92015-08-11 17:35:25 -0700853void ConcurrentCopying::SwapStacks() {
854 heap_->SwapStacks();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800855}
856
857void ConcurrentCopying::RecordLiveStackFreezeSize(Thread* self) {
858 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
859 live_stack_freeze_size_ = heap_->GetLiveStack()->Size();
860}
861
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700862// Used to visit objects in the immune spaces.
863inline void ConcurrentCopying::ScanImmuneObject(mirror::Object* obj) {
864 DCHECK(obj != nullptr);
865 DCHECK(immune_spaces_.ContainsObject(obj));
866 // Update the fields without graying it or pushing it onto the mark stack.
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700867 if (kEnableGenerationalConcurrentCopyingCollection && young_gen_) {
868 // Young GC does not care about references to unevac space. It is safe to not gray these as
869 // long as scan immune objects happens after scanning the dirty cards.
870 Scan<true>(obj);
871 } else {
872 Scan<false>(obj);
873 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700874}
875
876class ConcurrentCopying::ImmuneSpaceScanObjVisitor {
877 public:
878 explicit ImmuneSpaceScanObjVisitor(ConcurrentCopying* cc)
879 : collector_(cc) {}
880
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700881 ALWAYS_INLINE void operator()(mirror::Object* obj) const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700882 if (kUseBakerReadBarrier && kGrayDirtyImmuneObjects) {
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700883 // Only need to scan gray objects.
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700884 if (obj->GetReadBarrierState() == ReadBarrier::GrayState()) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700885 collector_->ScanImmuneObject(obj);
Roland Levillain14e5a292018-06-28 12:00:56 +0100886 // Done scanning the object, go back to black (non-gray).
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700887 bool success = obj->AtomicSetReadBarrierState(ReadBarrier::GrayState(),
Roland Levillain14e5a292018-06-28 12:00:56 +0100888 ReadBarrier::NonGrayState());
Mathieu Chartier2af7a3e2017-12-14 18:36:05 -0800889 CHECK(success)
890 << Runtime::Current()->GetHeap()->GetVerification()->DumpObjectInfo(obj, "failed CAS");
Mathieu Chartier21328a12016-07-22 10:47:45 -0700891 }
892 } else {
893 collector_->ScanImmuneObject(obj);
894 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700895 }
896
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700897 static void Callback(mirror::Object* obj, void* arg) REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi5408f232016-07-29 15:07:05 -0700898 reinterpret_cast<ImmuneSpaceScanObjVisitor*>(arg)->operator()(obj);
899 }
900
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700901 private:
902 ConcurrentCopying* const collector_;
903};
904
Lokesh Gidra2a9824c2018-11-07 15:57:17 -0800905template <bool kAtomicTestAndSet>
906class ConcurrentCopying::CaptureRootsForMarkingVisitor : public RootVisitor {
907 public:
908 explicit CaptureRootsForMarkingVisitor(ConcurrentCopying* cc, Thread* self)
909 : collector_(cc), self_(self) {}
910
911 void VisitRoots(mirror::Object*** roots,
912 size_t count,
913 const RootInfo& info ATTRIBUTE_UNUSED) override
914 REQUIRES_SHARED(Locks::mutator_lock_) {
915 for (size_t i = 0; i < count; ++i) {
916 mirror::Object** root = roots[i];
917 mirror::Object* ref = *root;
918 if (ref != nullptr && !collector_->TestAndSetMarkBitForRef<kAtomicTestAndSet>(ref)) {
919 collector_->PushOntoMarkStack(self_, ref);
920 }
921 }
922 }
923
924 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots,
925 size_t count,
926 const RootInfo& info ATTRIBUTE_UNUSED) override
927 REQUIRES_SHARED(Locks::mutator_lock_) {
928 for (size_t i = 0; i < count; ++i) {
929 mirror::CompressedReference<mirror::Object>* const root = roots[i];
930 if (!root->IsNull()) {
931 mirror::Object* ref = root->AsMirrorPtr();
932 if (!collector_->TestAndSetMarkBitForRef<kAtomicTestAndSet>(ref)) {
933 collector_->PushOntoMarkStack(self_, ref);
934 }
935 }
936 }
937 }
938
939 private:
940 ConcurrentCopying* const collector_;
941 Thread* const self_;
942};
943
944class ConcurrentCopying::RevokeThreadLocalMarkStackCheckpoint : public Closure {
945 public:
946 RevokeThreadLocalMarkStackCheckpoint(ConcurrentCopying* concurrent_copying,
947 bool disable_weak_ref_access)
948 : concurrent_copying_(concurrent_copying),
949 disable_weak_ref_access_(disable_weak_ref_access) {
950 }
951
952 void Run(Thread* thread) override NO_THREAD_SAFETY_ANALYSIS {
953 // Note: self is not necessarily equal to thread since thread may be suspended.
954 Thread* const self = Thread::Current();
955 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
956 << thread->GetState() << " thread " << thread << " self " << self;
957 // Revoke thread local mark stacks.
958 accounting::AtomicStack<mirror::Object>* tl_mark_stack = thread->GetThreadLocalMarkStack();
959 if (tl_mark_stack != nullptr) {
960 MutexLock mu(self, concurrent_copying_->mark_stack_lock_);
961 concurrent_copying_->revoked_mark_stacks_.push_back(tl_mark_stack);
962 thread->SetThreadLocalMarkStack(nullptr);
963 }
964 // Disable weak ref access.
965 if (disable_weak_ref_access_) {
966 thread->SetWeakRefAccessEnabled(false);
967 }
968 // If thread is a running mutator, then act on behalf of the garbage collector.
969 // See the code in ThreadList::RunCheckpoint.
970 concurrent_copying_->GetBarrier().Pass(self);
971 }
972
973 protected:
974 ConcurrentCopying* const concurrent_copying_;
975
976 private:
977 const bool disable_weak_ref_access_;
978};
979
980class ConcurrentCopying::CaptureThreadRootsForMarkingAndCheckpoint :
981 public RevokeThreadLocalMarkStackCheckpoint {
982 public:
983 explicit CaptureThreadRootsForMarkingAndCheckpoint(ConcurrentCopying* cc) :
984 RevokeThreadLocalMarkStackCheckpoint(cc, /* disable_weak_ref_access */ false) {}
985
986 void Run(Thread* thread) override
987 REQUIRES_SHARED(Locks::mutator_lock_) {
988 Thread* const self = Thread::Current();
989 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
990 // We can use the non-CAS VisitRoots functions below because we update thread-local GC roots
991 // only.
992 CaptureRootsForMarkingVisitor</*kAtomicTestAndSet*/ true> visitor(concurrent_copying_, self);
993 thread->VisitRoots(&visitor, kVisitRootFlagAllRoots);
994 // Barrier handling is done in the base class' Run() below.
995 RevokeThreadLocalMarkStackCheckpoint::Run(thread);
996 }
997};
998
999void ConcurrentCopying::CaptureThreadRootsForMarking() {
1000 TimingLogger::ScopedTiming split("CaptureThreadRootsForMarking", GetTimings());
1001 if (kVerboseMode) {
1002 LOG(INFO) << "time=" << region_space_->Time();
1003 region_space_->DumpNonFreeRegions(LOG_STREAM(INFO));
1004 }
1005 Thread* const self = Thread::Current();
1006 CaptureThreadRootsForMarkingAndCheckpoint check_point(this);
1007 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1008 gc_barrier_->Init(self, 0);
1009 size_t barrier_count = thread_list->RunCheckpoint(&check_point, /* callback */ nullptr);
1010 // If there are no threads to wait which implys that all the checkpoint functions are finished,
1011 // then no need to release the mutator lock.
1012 if (barrier_count == 0) {
1013 return;
1014 }
1015 Locks::mutator_lock_->SharedUnlock(self);
1016 {
1017 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
1018 gc_barrier_->Increment(self, barrier_count);
1019 }
1020 Locks::mutator_lock_->SharedLock(self);
1021 if (kVerboseMode) {
1022 LOG(INFO) << "time=" << region_space_->Time();
1023 region_space_->DumpNonFreeRegions(LOG_STREAM(INFO));
1024 LOG(INFO) << "GC end of CaptureThreadRootsForMarking";
1025 }
1026}
1027
1028// Used to scan ref fields of an object.
1029template <bool kHandleInterRegionRefs>
1030class ConcurrentCopying::ComputeLiveBytesAndMarkRefFieldsVisitor {
1031 public:
1032 explicit ComputeLiveBytesAndMarkRefFieldsVisitor(ConcurrentCopying* collector,
1033 size_t obj_region_idx)
1034 : collector_(collector),
1035 obj_region_idx_(obj_region_idx),
1036 contains_inter_region_idx_(false) {}
1037
1038 void operator()(mirror::Object* obj, MemberOffset offset, bool /* is_static */) const
1039 ALWAYS_INLINE
1040 REQUIRES_SHARED(Locks::mutator_lock_)
1041 REQUIRES_SHARED(Locks::heap_bitmap_lock_) {
1042 DCHECK_EQ(collector_->RegionSpace()->RegionIdxForRef(obj), obj_region_idx_);
1043 DCHECK(kHandleInterRegionRefs || collector_->immune_spaces_.ContainsObject(obj));
1044 CheckReference(obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(offset));
1045 }
1046
1047 void operator()(ObjPtr<mirror::Class> klass, ObjPtr<mirror::Reference> ref) const
1048 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
1049 DCHECK(klass->IsTypeOfReferenceClass());
1050 // If the referent is not null, then we must re-visit the object during
1051 // copying phase to enqueue it for delayed processing and setting
1052 // read-barrier state to gray to ensure that call to GetReferent() triggers
1053 // the read-barrier. We use same data structure that is used to remember
1054 // objects with inter-region refs for this purpose too.
1055 if (kHandleInterRegionRefs
1056 && !contains_inter_region_idx_
1057 && ref->AsReference()->GetReferent<kWithoutReadBarrier>() != nullptr) {
1058 contains_inter_region_idx_ = true;
1059 }
1060 }
1061
1062 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
1063 ALWAYS_INLINE
1064 REQUIRES_SHARED(Locks::mutator_lock_) {
1065 if (!root->IsNull()) {
1066 VisitRoot(root);
1067 }
1068 }
1069
1070 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
1071 ALWAYS_INLINE
1072 REQUIRES_SHARED(Locks::mutator_lock_) {
1073 CheckReference(root->AsMirrorPtr());
1074 }
1075
1076 bool ContainsInterRegionRefs() const ALWAYS_INLINE REQUIRES_SHARED(Locks::mutator_lock_) {
1077 return contains_inter_region_idx_;
1078 }
1079
1080 private:
1081 void CheckReference(mirror::Object* ref) const
1082 REQUIRES_SHARED(Locks::mutator_lock_) {
1083 if (ref == nullptr) {
1084 // Nothing to do.
1085 return;
1086 }
1087 if (!collector_->TestAndSetMarkBitForRef(ref)) {
1088 collector_->PushOntoLocalMarkStack(ref);
1089 }
1090 if (kHandleInterRegionRefs && !contains_inter_region_idx_) {
1091 size_t ref_region_idx = collector_->RegionSpace()->RegionIdxForRef(ref);
1092 // If a region-space object refers to an outside object, we will have a
1093 // mismatch of region idx, but the object need not be re-visited in
1094 // copying phase.
1095 if (ref_region_idx != static_cast<size_t>(-1) && obj_region_idx_ != ref_region_idx) {
1096 contains_inter_region_idx_ = true;
1097 }
1098 }
1099 }
1100
1101 ConcurrentCopying* const collector_;
1102 const size_t obj_region_idx_;
1103 mutable bool contains_inter_region_idx_;
1104};
1105
1106void ConcurrentCopying::AddLiveBytesAndScanRef(mirror::Object* ref) {
1107 DCHECK(ref != nullptr);
1108 DCHECK(!immune_spaces_.ContainsObject(ref));
1109 DCHECK(TestMarkBitmapForRef(ref));
1110 size_t obj_region_idx = static_cast<size_t>(-1);
1111 if (LIKELY(region_space_->HasAddress(ref))) {
1112 obj_region_idx = region_space_->RegionIdxForRefUnchecked(ref);
1113 // Add live bytes to the corresponding region
1114 if (!region_space_->IsRegionNewlyAllocated(obj_region_idx)) {
1115 // Newly Allocated regions are always chosen for evacuation. So no need
1116 // to update live_bytes_.
1117 size_t obj_size = ref->SizeOf<kDefaultVerifyFlags>();
1118 size_t alloc_size = RoundUp(obj_size, space::RegionSpace::kAlignment);
1119 region_space_->AddLiveBytes(ref, alloc_size);
1120 }
1121 }
1122 ComputeLiveBytesAndMarkRefFieldsVisitor</*kHandleInterRegionRefs*/ true>
1123 visitor(this, obj_region_idx);
Lokesh Gidra1c34b712018-12-18 13:41:58 -08001124 ref->VisitReferences</*kVisitNativeRoots=*/ true, kDefaultVerifyFlags, kWithoutReadBarrier>(
Lokesh Gidra2a9824c2018-11-07 15:57:17 -08001125 visitor, visitor);
1126 // Mark the corresponding card dirty if the object contains any
1127 // inter-region reference.
1128 if (visitor.ContainsInterRegionRefs()) {
Lokesh Gidra1c34b712018-12-18 13:41:58 -08001129 if (obj_region_idx == static_cast<size_t>(-1)) {
1130 // If an inter-region ref has been found in a non-region-space, then it
1131 // must be non-moving-space. This is because this function cannot be
1132 // called on a immune-space object, and a large-object-space object has
1133 // only class object reference, which is either in some immune-space, or
1134 // in non-moving-space.
1135 DCHECK(heap_->non_moving_space_->HasAddress(ref));
1136 non_moving_space_inter_region_bitmap_->Set(ref);
1137 } else {
1138 region_space_inter_region_bitmap_->Set(ref);
1139 }
Lokesh Gidra2a9824c2018-11-07 15:57:17 -08001140 }
1141}
1142
1143template <bool kAtomic>
1144bool ConcurrentCopying::TestAndSetMarkBitForRef(mirror::Object* ref) {
1145 accounting::ContinuousSpaceBitmap* bitmap = nullptr;
1146 accounting::LargeObjectBitmap* los_bitmap = nullptr;
1147 if (LIKELY(region_space_->HasAddress(ref))) {
1148 bitmap = region_space_bitmap_;
1149 } else if (heap_->GetNonMovingSpace()->HasAddress(ref)) {
1150 bitmap = heap_->GetNonMovingSpace()->GetMarkBitmap();
1151 } else if (immune_spaces_.ContainsObject(ref)) {
1152 // References to immune space objects are always live.
1153 DCHECK(heap_mark_bitmap_->GetContinuousSpaceBitmap(ref)->Test(ref));
1154 return true;
1155 } else {
1156 // Should be a large object. Must be page aligned and the LOS must exist.
1157 if (kIsDebugBuild
1158 && (!IsAligned<kPageSize>(ref) || heap_->GetLargeObjectsSpace() == nullptr)) {
1159 // It must be heap corruption. Remove memory protection and dump data.
1160 region_space_->Unprotect();
1161 heap_->GetVerification()->LogHeapCorruption(/* obj */ nullptr,
1162 MemberOffset(0),
1163 ref,
1164 /* fatal */ true);
1165 }
1166 los_bitmap = heap_->GetLargeObjectsSpace()->GetMarkBitmap();
1167 }
1168 if (kAtomic) {
1169 return (bitmap != nullptr) ? bitmap->AtomicTestAndSet(ref) : los_bitmap->AtomicTestAndSet(ref);
1170 } else {
1171 return (bitmap != nullptr) ? bitmap->Set(ref) : los_bitmap->Set(ref);
1172 }
1173}
1174
1175bool ConcurrentCopying::TestMarkBitmapForRef(mirror::Object* ref) {
1176 if (LIKELY(region_space_->HasAddress(ref))) {
1177 return region_space_bitmap_->Test(ref);
1178 } else if (heap_->GetNonMovingSpace()->HasAddress(ref)) {
1179 return heap_->GetNonMovingSpace()->GetMarkBitmap()->Test(ref);
1180 } else if (immune_spaces_.ContainsObject(ref)) {
1181 // References to immune space objects are always live.
1182 DCHECK(heap_mark_bitmap_->GetContinuousSpaceBitmap(ref)->Test(ref));
1183 return true;
1184 } else {
1185 // Should be a large object. Must be page aligned and the LOS must exist.
1186 if (kIsDebugBuild
1187 && (!IsAligned<kPageSize>(ref) || heap_->GetLargeObjectsSpace() == nullptr)) {
1188 // It must be heap corruption. Remove memory protection and dump data.
1189 region_space_->Unprotect();
1190 heap_->GetVerification()->LogHeapCorruption(/* obj */ nullptr,
1191 MemberOffset(0),
1192 ref,
1193 /* fatal */ true);
1194 }
1195 return heap_->GetLargeObjectsSpace()->GetMarkBitmap()->Test(ref);
1196 }
1197}
1198
1199void ConcurrentCopying::PushOntoLocalMarkStack(mirror::Object* ref) {
1200 if (kIsDebugBuild) {
1201 Thread *self = Thread::Current();
1202 DCHECK_EQ(thread_running_gc_, self);
1203 DCHECK(self->GetThreadLocalMarkStack() == nullptr);
1204 }
1205 DCHECK_EQ(mark_stack_mode_.load(std::memory_order_relaxed), kMarkStackModeThreadLocal);
1206 gc_mark_stack_->PushBack(ref);
1207}
1208
1209void ConcurrentCopying::ProcessMarkStackForMarkingAndComputeLiveBytes() {
1210 // Process thread-local mark stack containing thread roots
1211 ProcessThreadLocalMarkStacks(/* disable_weak_ref_access */ false,
1212 /* checkpoint_callback */ nullptr,
1213 [this] (mirror::Object* ref)
1214 REQUIRES_SHARED(Locks::mutator_lock_) {
1215 AddLiveBytesAndScanRef(ref);
1216 });
1217
1218 while (!gc_mark_stack_->IsEmpty()) {
1219 mirror::Object* ref = gc_mark_stack_->PopBack();
1220 AddLiveBytesAndScanRef(ref);
1221 }
1222}
1223
1224class ConcurrentCopying::ImmuneSpaceCaptureRefsVisitor {
1225 public:
1226 explicit ImmuneSpaceCaptureRefsVisitor(ConcurrentCopying* cc) : collector_(cc) {}
1227
1228 ALWAYS_INLINE void operator()(mirror::Object* obj) const REQUIRES_SHARED(Locks::mutator_lock_) {
1229 ComputeLiveBytesAndMarkRefFieldsVisitor</*kHandleInterRegionRefs*/ false>
1230 visitor(collector_, /*obj_region_idx*/ static_cast<size_t>(-1));
1231 obj->VisitReferences</*kVisitNativeRoots=*/true, kDefaultVerifyFlags, kWithoutReadBarrier>(
1232 visitor, visitor);
1233 }
1234
1235 static void Callback(mirror::Object* obj, void* arg) REQUIRES_SHARED(Locks::mutator_lock_) {
1236 reinterpret_cast<ImmuneSpaceScanObjVisitor*>(arg)->operator()(obj);
1237 }
1238
1239 private:
1240 ConcurrentCopying* const collector_;
1241};
1242
1243/* Invariants for two-phase CC
1244 * ===========================
1245 * A) Definitions
1246 * ---------------
1247 * 1) Black: marked in bitmap, rb_state is non-gray, and not in mark stack
1248 * 2) Black-clean: marked in bitmap, and corresponding card is clean/aged
1249 * 3) Black-dirty: marked in bitmap, and corresponding card is dirty
1250 * 4) Gray: marked in bitmap, and exists in mark stack
1251 * 5) Gray-dirty: marked in bitmap, rb_state is gray, corresponding card is
1252 * dirty, and exists in mark stack
1253 * 6) White: unmarked in bitmap, rb_state is non-gray, and not in mark stack
1254 *
1255 * B) Before marking phase
1256 * -----------------------
1257 * 1) All objects are white
1258 * 2) Cards are either clean or aged (cannot be asserted without a STW pause)
1259 * 3) Mark bitmap is cleared
1260 * 4) Mark stack is empty
1261 *
1262 * C) During marking phase
1263 * ------------------------
1264 * 1) If a black object holds an inter-region or white reference, then its
1265 * corresponding card is dirty. In other words, it changes from being
1266 * black-clean to black-dirty
1267 * 2) No black-clean object points to a white object
1268 *
1269 * D) After marking phase
1270 * -----------------------
1271 * 1) There are no gray objects
1272 * 2) All newly allocated objects are in from space
1273 * 3) No white object can be reachable, directly or otherwise, from a
1274 * black-clean object
1275 *
1276 * E) During copying phase
1277 * ------------------------
1278 * 1) Mutators cannot observe white and black-dirty objects
1279 * 2) New allocations are in to-space (newly allocated regions are part of to-space)
1280 * 3) An object in mark stack must have its rb_state = Gray
1281 *
1282 * F) During card table scan
1283 * --------------------------
1284 * 1) Referents corresponding to root references are gray or in to-space
1285 * 2) Every path from an object that is read or written by a mutator during
1286 * this period to a dirty black object goes through some gray object.
1287 * Mutators preserve this by graying black objects as needed during this
1288 * period. Ensures that a mutator never encounters a black dirty object.
1289 *
1290 * G) After card table scan
1291 * ------------------------
1292 * 1) There are no black-dirty objects
1293 * 2) Referents corresponding to root references are gray, black-clean or in
1294 * to-space
1295 *
1296 * H) After copying phase
1297 * -----------------------
1298 * 1) Mark stack is empty
1299 * 2) No references into evacuated from-space
1300 * 3) No reference to an object which is unmarked and is also not in newly
1301 * allocated region. In other words, no reference to white objects.
1302*/
1303
1304void ConcurrentCopying::MarkingPhase() {
1305 TimingLogger::ScopedTiming split("MarkingPhase", GetTimings());
1306 if (kVerboseMode) {
1307 LOG(INFO) << "GC MarkingPhase";
1308 }
1309 accounting::CardTable* const card_table = heap_->GetCardTable();
1310 Thread* const self = Thread::Current();
1311 // Clear live_bytes_ of every non-free region, except the ones that are newly
1312 // allocated.
1313 region_space_->SetAllRegionLiveBytesZero();
1314 if (kIsDebugBuild) {
1315 region_space_->AssertAllRegionLiveBytesZeroOrCleared();
1316 }
1317 // Scan immune spaces
1318 {
1319 TimingLogger::ScopedTiming split2("ScanImmuneSpaces", GetTimings());
1320 for (auto& space : immune_spaces_.GetSpaces()) {
1321 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
1322 accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
1323 accounting::ModUnionTable* table = heap_->FindModUnionTableFromSpace(space);
1324 ImmuneSpaceCaptureRefsVisitor visitor(this);
1325 if (table != nullptr) {
1326 table->VisitObjects(ImmuneSpaceCaptureRefsVisitor::Callback, &visitor);
1327 } else {
1328 WriterMutexLock rmu(Thread::Current(), *Locks::heap_bitmap_lock_);
1329 card_table->Scan<false>(
1330 live_bitmap,
1331 space->Begin(),
1332 space->Limit(),
1333 visitor,
1334 accounting::CardTable::kCardDirty - 1);
1335 }
1336 }
1337 }
1338 // Scan runtime roots
1339 {
1340 TimingLogger::ScopedTiming split2("VisitConcurrentRoots", GetTimings());
1341 CaptureRootsForMarkingVisitor visitor(this, self);
1342 Runtime::Current()->VisitConcurrentRoots(&visitor, kVisitRootFlagAllRoots);
1343 }
1344 {
1345 // TODO: don't visit the transaction roots if it's not active.
1346 TimingLogger::ScopedTiming split2("VisitNonThreadRoots", GetTimings());
1347 CaptureRootsForMarkingVisitor visitor(this, self);
1348 Runtime::Current()->VisitNonThreadRoots(&visitor);
1349 }
1350 // Capture thread roots
1351 CaptureThreadRootsForMarking();
1352 // Process mark stack
1353 ProcessMarkStackForMarkingAndComputeLiveBytes();
1354
Lokesh Gidra2a9824c2018-11-07 15:57:17 -08001355 if (kVerboseMode) {
1356 LOG(INFO) << "GC end of MarkingPhase";
1357 }
1358}
1359
Lokesh Gidra8f5aaad2018-12-11 15:05:56 -08001360template <bool kNoUnEvac>
1361void ConcurrentCopying::ScanDirtyObject(mirror::Object* obj) {
1362 Scan<kNoUnEvac>(obj);
1363 // Set the read-barrier state of a reference-type object to gray if its
1364 // referent is not marked yet. This is to ensure that if GetReferent() is
1365 // called, it triggers the read-barrier to process the referent before use.
1366 if (UNLIKELY((obj->GetClass<kVerifyNone, kWithoutReadBarrier>()->IsTypeOfReferenceClass()))) {
1367 mirror::Object* referent =
1368 obj->AsReference<kVerifyNone, kWithoutReadBarrier>()->GetReferent<kWithoutReadBarrier>();
1369 if (referent != nullptr && !IsInToSpace(referent)) {
1370 obj->AtomicSetReadBarrierState(ReadBarrier::NonGrayState(), ReadBarrier::GrayState());
1371 }
1372 }
1373}
1374
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001375// Concurrently mark roots that are guarded by read barriers and process the mark stack.
Lokesh Gidra2a9824c2018-11-07 15:57:17 -08001376void ConcurrentCopying::CopyingPhase() {
1377 TimingLogger::ScopedTiming split("CopyingPhase", GetTimings());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001378 if (kVerboseMode) {
Lokesh Gidra2a9824c2018-11-07 15:57:17 -08001379 LOG(INFO) << "GC CopyingPhase";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001380 }
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001381 Thread* self = Thread::Current();
Lokesh Gidra2a9824c2018-11-07 15:57:17 -08001382 accounting::CardTable* const card_table = heap_->GetCardTable();
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001383 if (kIsDebugBuild) {
1384 MutexLock mu(self, *Locks::thread_list_lock_);
1385 CHECK(weak_ref_access_enabled_);
1386 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001387
1388 // Scan immune spaces.
1389 // Update all the fields in the immune spaces first without graying the objects so that we
1390 // minimize dirty pages in the immune spaces. Note mutators can concurrently access and gray some
1391 // of the objects.
1392 if (kUseBakerReadBarrier) {
1393 gc_grays_immune_objects_ = false;
Hiroshi Yamauchi16292fc2016-06-20 20:23:34 -07001394 }
Lokesh Gidra2a9824c2018-11-07 15:57:17 -08001395 if (kEnableGenerationalConcurrentCopyingCollection) {
Roland Levillain57ce0542018-08-07 16:20:31 +01001396 if (kVerboseMode) {
1397 LOG(INFO) << "GC ScanCardsForSpace";
1398 }
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07001399 TimingLogger::ScopedTiming split2("ScanCardsForSpace", GetTimings());
1400 WriterMutexLock rmu(Thread::Current(), *Locks::heap_bitmap_lock_);
Roland Levillain2d94e292018-08-15 16:46:30 +01001401 CHECK(!done_scanning_.load(std::memory_order_relaxed));
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07001402 if (kIsDebugBuild) {
1403 // Leave some time for mutators to race ahead to try and find races between the GC card
1404 // scanning and mutators reading references.
1405 usleep(10 * 1000);
1406 }
1407 for (space::ContinuousSpace* space : GetHeap()->GetContinuousSpaces()) {
1408 if (space->IsImageSpace() || space->IsZygoteSpace()) {
1409 // Image and zygote spaces are already handled since we gray the objects in the pause.
1410 continue;
1411 }
1412 // Scan all of the objects on dirty cards in unevac from space, and non moving space. These
Lokesh Gidra2a9824c2018-11-07 15:57:17 -08001413 // are from previous GCs (or from marking phase of 2-phase full GC) and may reference things
1414 // in the from space.
Roland Levillain4ba92462018-08-15 19:16:24 +01001415 //
1416 // Note that we do not need to process the large-object space (the only discontinuous space)
1417 // as it contains only large string objects and large primitive array objects, that have no
1418 // reference to other objects, except their class. There is no need to scan these large
1419 // objects, as the String class and the primitive array classes are expected to never move
Lokesh Gidra2a9824c2018-11-07 15:57:17 -08001420 // during a collection:
Roland Levillain4ba92462018-08-15 19:16:24 +01001421 // - In the case where we run with a boot image, these classes are part of the image space,
1422 // which is an immune space.
Roland Levillain0e840272018-08-23 19:55:30 +01001423 // - In the case where we run without a boot image, these classes are allocated in the
1424 // non-moving space (see art::ClassLinker::InitWithoutImage).
Lokesh Gidra2a9824c2018-11-07 15:57:17 -08001425 card_table->Scan<false>(
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07001426 space->GetMarkBitmap(),
1427 space->Begin(),
1428 space->End(),
1429 [this, space](mirror::Object* obj)
1430 REQUIRES(Locks::heap_bitmap_lock_)
1431 REQUIRES_SHARED(Locks::mutator_lock_) {
Lokesh Gidra2a9824c2018-11-07 15:57:17 -08001432 // TODO: This code may be refactored to avoid scanning object while
1433 // done_scanning_ is false by setting rb_state to gray, and pushing the
1434 // object on mark stack. However, it will also require clearing the
1435 // corresponding mark-bit and, for region space objects,
1436 // decrementing the object's size from the corresponding region's
1437 // live_bytes.
1438 if (young_gen_) {
1439 // Don't push or gray unevac refs.
1440 if (kIsDebugBuild && space == region_space_) {
1441 // We may get unevac large objects.
1442 if (!region_space_->IsInUnevacFromSpace(obj)) {
1443 CHECK(region_space_bitmap_->Test(obj));
1444 region_space_->DumpRegionForObject(LOG_STREAM(FATAL_WITHOUT_ABORT), obj);
1445 LOG(FATAL) << "Scanning " << obj << " not in unevac space";
1446 }
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07001447 }
Lokesh Gidra2a9824c2018-11-07 15:57:17 -08001448 ScanDirtyObject</*kNoUnEvac*/ true>(obj);
Lokesh Gidra1c34b712018-12-18 13:41:58 -08001449 } else if (space != region_space_) {
1450 DCHECK(space == heap_->non_moving_space_);
Lokesh Gidrad0c5b252018-12-05 01:10:40 -08001451 // We need to process un-evac references as they may be unprocessed,
1452 // if they skipped the marking phase due to heap mutation.
Lokesh Gidra2a9824c2018-11-07 15:57:17 -08001453 ScanDirtyObject</*kNoUnEvac*/ false>(obj);
Lokesh Gidra1c34b712018-12-18 13:41:58 -08001454 non_moving_space_inter_region_bitmap_->Clear(obj);
1455 } else if (region_space_->IsInUnevacFromSpace(obj)) {
1456 ScanDirtyObject</*kNoUnEvac*/ false>(obj);
1457 region_space_inter_region_bitmap_->Clear(obj);
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07001458 }
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07001459 },
Lokesh Gidrad0c5b252018-12-05 01:10:40 -08001460 accounting::CardTable::kCardAged);
1461
1462 if (!young_gen_) {
1463 auto visitor = [this](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1464 // We don't need to process un-evac references as any unprocessed
1465 // ones will be taken care of in the card-table scan above.
1466 ScanDirtyObject</*kNoUnEvac*/ true>(obj);
1467 };
1468 if (space == region_space_) {
Lokesh Gidra1c34b712018-12-18 13:41:58 -08001469 region_space_->ScanUnevacFromSpace(region_space_inter_region_bitmap_, visitor);
Lokesh Gidrad0c5b252018-12-05 01:10:40 -08001470 } else {
Lokesh Gidra1c34b712018-12-18 13:41:58 -08001471 DCHECK(space == heap_->non_moving_space_);
1472 non_moving_space_inter_region_bitmap_->VisitMarkedRange(
1473 reinterpret_cast<uintptr_t>(space->Begin()),
1474 reinterpret_cast<uintptr_t>(space->End()),
1475 visitor);
Lokesh Gidrad0c5b252018-12-05 01:10:40 -08001476 }
1477 }
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07001478 }
1479 // Done scanning unevac space.
Roland Levillain2d94e292018-08-15 16:46:30 +01001480 done_scanning_.store(true, std::memory_order_release);
Lokesh Gidra1c34b712018-12-18 13:41:58 -08001481 // NOTE: inter-region-ref bitmaps can be cleared here to release memory, if needed.
1482 // Currently we do it in ReclaimPhase().
Roland Levillain57ce0542018-08-07 16:20:31 +01001483 if (kVerboseMode) {
1484 LOG(INFO) << "GC end of ScanCardsForSpace";
1485 }
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07001486 }
Mathieu Chartier21328a12016-07-22 10:47:45 -07001487 {
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07001488 // For a sticky-bit collection, this phase needs to be after the card scanning since the
1489 // mutator may read an unevac space object out of an image object. If the image object is no
1490 // longer gray it will trigger a read barrier for the unevac space object.
Mathieu Chartier21328a12016-07-22 10:47:45 -07001491 TimingLogger::ScopedTiming split2("ScanImmuneSpaces", GetTimings());
1492 for (auto& space : immune_spaces_.GetSpaces()) {
1493 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
1494 accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
Hiroshi Yamauchi5408f232016-07-29 15:07:05 -07001495 accounting::ModUnionTable* table = heap_->FindModUnionTableFromSpace(space);
Mathieu Chartier21328a12016-07-22 10:47:45 -07001496 ImmuneSpaceScanObjVisitor visitor(this);
Hiroshi Yamauchi5408f232016-07-29 15:07:05 -07001497 if (kUseBakerReadBarrier && kGrayDirtyImmuneObjects && table != nullptr) {
1498 table->VisitObjects(ImmuneSpaceScanObjVisitor::Callback, &visitor);
1499 } else {
Lokesh Gidra2a9824c2018-11-07 15:57:17 -08001500 WriterMutexLock rmu(Thread::Current(), *Locks::heap_bitmap_lock_);
1501 card_table->Scan<false>(
1502 live_bitmap,
1503 space->Begin(),
1504 space->Limit(),
1505 visitor,
1506 accounting::CardTable::kCardDirty - 1);
Hiroshi Yamauchi5408f232016-07-29 15:07:05 -07001507 }
Mathieu Chartier21328a12016-07-22 10:47:45 -07001508 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001509 }
1510 if (kUseBakerReadBarrier) {
1511 // This release fence makes the field updates in the above loop visible before allowing mutator
1512 // getting access to immune objects without graying it first.
Orion Hodson88591fe2018-03-06 13:35:43 +00001513 updated_all_immune_objects_.store(true, std::memory_order_release);
Roland Levillain14e5a292018-06-28 12:00:56 +01001514 // Now "un-gray" (conceptually blacken) immune objects concurrently accessed and grayed by
1515 // mutators. We can't do this in the above loop because we would incorrectly disable the read
1516 // barrier by un-graying (conceptually blackening) an object which may point to an unscanned,
1517 // white object, breaking the to-space invariant (a mutator shall never observe a from-space
1518 // (white) object).
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001519 //
Roland Levillain14e5a292018-06-28 12:00:56 +01001520 // Make sure no mutators are in the middle of marking an immune object before un-graying
1521 // (blackening) immune objects.
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001522 IssueEmptyCheckpoint();
1523 MutexLock mu(Thread::Current(), immune_gray_stack_lock_);
1524 if (kVerboseMode) {
1525 LOG(INFO) << "immune gray stack size=" << immune_gray_stack_.size();
1526 }
1527 for (mirror::Object* obj : immune_gray_stack_) {
Roland Levillain14e5a292018-06-28 12:00:56 +01001528 DCHECK_EQ(obj->GetReadBarrierState(), ReadBarrier::GrayState());
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001529 bool success = obj->AtomicSetReadBarrierState(ReadBarrier::GrayState(),
Roland Levillain14e5a292018-06-28 12:00:56 +01001530 ReadBarrier::NonGrayState());
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001531 DCHECK(success);
1532 }
1533 immune_gray_stack_.clear();
1534 }
1535
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001536 {
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001537 TimingLogger::ScopedTiming split2("VisitConcurrentRoots", GetTimings());
1538 Runtime::Current()->VisitConcurrentRoots(this, kVisitRootFlagAllRoots);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001539 }
1540 {
1541 // TODO: don't visit the transaction roots if it's not active.
1542 TimingLogger::ScopedTiming split5("VisitNonThreadRoots", GetTimings());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001543 Runtime::Current()->VisitNonThreadRoots(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001544 }
1545
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001546 {
Mathieu Chartiera6b1ead2015-10-06 10:32:38 -07001547 TimingLogger::ScopedTiming split7("ProcessMarkStack", GetTimings());
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001548 // We transition through three mark stack modes (thread-local, shared, GC-exclusive). The
1549 // primary reasons are the fact that we need to use a checkpoint to process thread-local mark
1550 // stacks, but after we disable weak refs accesses, we can't use a checkpoint due to a deadlock
1551 // issue because running threads potentially blocking at WaitHoldingLocks, and that once we
1552 // reach the point where we process weak references, we can avoid using a lock when accessing
1553 // the GC mark stack, which makes mark stack processing more efficient.
1554
1555 // Process the mark stack once in the thread local stack mode. This marks most of the live
1556 // objects, aside from weak ref accesses with read barriers (Reference::GetReferent() and system
1557 // weaks) that may happen concurrently while we processing the mark stack and newly mark/gray
1558 // objects and push refs on the mark stack.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001559 ProcessMarkStack();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001560 // Switch to the shared mark stack mode. That is, revoke and process thread-local mark stacks
1561 // for the last time before transitioning to the shared mark stack mode, which would process new
1562 // refs that may have been concurrently pushed onto the mark stack during the ProcessMarkStack()
1563 // call above. At the same time, disable weak ref accesses using a per-thread flag. It's
1564 // important to do these together in a single checkpoint so that we can ensure that mutators
1565 // won't newly gray objects and push new refs onto the mark stack due to weak ref accesses and
1566 // mutators safely transition to the shared mark stack mode (without leaving unprocessed refs on
1567 // the thread-local mark stacks), without a race. This is why we use a thread-local weak ref
1568 // access flag Thread::tls32_.weak_ref_access_enabled_ instead of the global ones.
1569 SwitchToSharedMarkStackMode();
1570 CHECK(!self->GetWeakRefAccessEnabled());
1571 // Now that weak refs accesses are disabled, once we exhaust the shared mark stack again here
1572 // (which may be non-empty if there were refs found on thread-local mark stacks during the above
1573 // SwitchToSharedMarkStackMode() call), we won't have new refs to process, that is, mutators
1574 // (via read barriers) have no way to produce any more refs to process. Marking converges once
1575 // before we process weak refs below.
1576 ProcessMarkStack();
1577 CheckEmptyMarkStack();
1578 // Switch to the GC exclusive mark stack mode so that we can process the mark stack without a
1579 // lock from this point on.
1580 SwitchToGcExclusiveMarkStackMode();
1581 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001582 if (kVerboseMode) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001583 LOG(INFO) << "ProcessReferences";
1584 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001585 // Process weak references. This may produce new refs to process and have them processed via
Mathieu Chartier97509952015-07-13 14:35:43 -07001586 // ProcessMarkStack (in the GC exclusive mark stack mode).
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001587 ProcessReferences(self);
1588 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001589 if (kVerboseMode) {
1590 LOG(INFO) << "SweepSystemWeaks";
1591 }
1592 SweepSystemWeaks(self);
1593 if (kVerboseMode) {
1594 LOG(INFO) << "SweepSystemWeaks done";
1595 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001596 // Process the mark stack here one last time because the above SweepSystemWeaks() call may have
1597 // marked some objects (strings alive) as hash_set::Erase() can call the hash function for
1598 // arbitrary elements in the weak intern table in InternTable::Table::SweepWeaks().
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001599 ProcessMarkStack();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001600 CheckEmptyMarkStack();
1601 // Re-enable weak ref accesses.
1602 ReenableWeakRefAccess(self);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07001603 // Free data for class loaders that we unloaded.
1604 Runtime::Current()->GetClassLinker()->CleanupClassLoaders();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001605 // Marking is done. Disable marking.
Hiroshi Yamauchi00370822015-08-18 14:47:25 -07001606 DisableMarking();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001607 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001608 }
1609
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001610 if (kIsDebugBuild) {
1611 MutexLock mu(self, *Locks::thread_list_lock_);
1612 CHECK(weak_ref_access_enabled_);
1613 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001614 if (kVerboseMode) {
Lokesh Gidra2a9824c2018-11-07 15:57:17 -08001615 LOG(INFO) << "GC end of CopyingPhase";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001616 }
1617}
1618
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001619void ConcurrentCopying::ReenableWeakRefAccess(Thread* self) {
1620 if (kVerboseMode) {
1621 LOG(INFO) << "ReenableWeakRefAccess";
1622 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001623 // Iterate all threads (don't need to or can't use a checkpoint) and re-enable weak ref access.
1624 {
1625 MutexLock mu(self, *Locks::thread_list_lock_);
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001626 weak_ref_access_enabled_ = true; // This is for new threads.
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001627 std::list<Thread*> thread_list = Runtime::Current()->GetThreadList()->GetList();
1628 for (Thread* thread : thread_list) {
1629 thread->SetWeakRefAccessEnabled(true);
1630 }
1631 }
1632 // Unblock blocking threads.
1633 GetHeap()->GetReferenceProcessor()->BroadcastForSlowPath(self);
1634 Runtime::Current()->BroadcastForNewSystemWeaks();
1635}
1636
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001637class ConcurrentCopying::DisableMarkingCheckpoint : public Closure {
Hiroshi Yamauchi00370822015-08-18 14:47:25 -07001638 public:
1639 explicit DisableMarkingCheckpoint(ConcurrentCopying* concurrent_copying)
1640 : concurrent_copying_(concurrent_copying) {
1641 }
1642
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001643 void Run(Thread* thread) override NO_THREAD_SAFETY_ANALYSIS {
Hiroshi Yamauchi00370822015-08-18 14:47:25 -07001644 // Note: self is not necessarily equal to thread since thread may be suspended.
1645 Thread* self = Thread::Current();
1646 DCHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
1647 << thread->GetState() << " thread " << thread << " self " << self;
1648 // Disable the thread-local is_gc_marking flag.
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -07001649 // Note a thread that has just started right before this checkpoint may have already this flag
1650 // set to false, which is ok.
Mathieu Chartierfe814e82016-11-09 14:32:49 -08001651 thread->SetIsGcMarkingAndUpdateEntrypoints(false);
Hiroshi Yamauchi00370822015-08-18 14:47:25 -07001652 // If thread is a running mutator, then act on behalf of the garbage collector.
1653 // See the code in ThreadList::RunCheckpoint.
Mathieu Chartier10d25082015-10-28 18:36:09 -07001654 concurrent_copying_->GetBarrier().Pass(self);
Hiroshi Yamauchi00370822015-08-18 14:47:25 -07001655 }
1656
1657 private:
1658 ConcurrentCopying* const concurrent_copying_;
1659};
1660
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001661class ConcurrentCopying::DisableMarkingCallback : public Closure {
1662 public:
1663 explicit DisableMarkingCallback(ConcurrentCopying* concurrent_copying)
1664 : concurrent_copying_(concurrent_copying) {
1665 }
1666
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001667 void Run(Thread* self ATTRIBUTE_UNUSED) override REQUIRES(Locks::thread_list_lock_) {
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001668 // This needs to run under the thread_list_lock_ critical section in ThreadList::RunCheckpoint()
1669 // to avoid a race with ThreadList::Register().
1670 CHECK(concurrent_copying_->is_marking_);
1671 concurrent_copying_->is_marking_ = false;
Mathieu Chartiera9a4f5f2017-05-03 18:19:13 -07001672 if (kUseBakerReadBarrier && kGrayDirtyImmuneObjects) {
1673 CHECK(concurrent_copying_->is_using_read_barrier_entrypoints_);
1674 concurrent_copying_->is_using_read_barrier_entrypoints_ = false;
1675 } else {
1676 CHECK(!concurrent_copying_->is_using_read_barrier_entrypoints_);
1677 }
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001678 }
1679
1680 private:
1681 ConcurrentCopying* const concurrent_copying_;
1682};
1683
Hiroshi Yamauchi00370822015-08-18 14:47:25 -07001684void ConcurrentCopying::IssueDisableMarkingCheckpoint() {
1685 Thread* self = Thread::Current();
1686 DisableMarkingCheckpoint check_point(this);
1687 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1688 gc_barrier_->Init(self, 0);
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001689 DisableMarkingCallback dmc(this);
1690 size_t barrier_count = thread_list->RunCheckpoint(&check_point, &dmc);
Hiroshi Yamauchi00370822015-08-18 14:47:25 -07001691 // If there are no threads to wait which implies that all the checkpoint functions are finished,
1692 // then no need to release the mutator lock.
1693 if (barrier_count == 0) {
1694 return;
1695 }
1696 // Release locks then wait for all mutator threads to pass the barrier.
1697 Locks::mutator_lock_->SharedUnlock(self);
1698 {
1699 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
1700 gc_barrier_->Increment(self, barrier_count);
1701 }
1702 Locks::mutator_lock_->SharedLock(self);
1703}
1704
1705void ConcurrentCopying::DisableMarking() {
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001706 // Use a checkpoint to turn off the global is_marking and the thread-local is_gc_marking flags and
1707 // to ensure no threads are still in the middle of a read barrier which may have a from-space ref
1708 // cached in a local variable.
Hiroshi Yamauchi00370822015-08-18 14:47:25 -07001709 IssueDisableMarkingCheckpoint();
1710 if (kUseTableLookupReadBarrier) {
1711 heap_->rb_table_->ClearAll();
1712 DCHECK(heap_->rb_table_->IsAllCleared());
1713 }
Orion Hodson88591fe2018-03-06 13:35:43 +00001714 is_mark_stack_push_disallowed_.store(1, std::memory_order_seq_cst);
1715 mark_stack_mode_.store(kMarkStackModeOff, std::memory_order_seq_cst);
Hiroshi Yamauchi00370822015-08-18 14:47:25 -07001716}
1717
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001718void ConcurrentCopying::IssueEmptyCheckpoint() {
1719 Thread* self = Thread::Current();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001720 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001721 // Release locks then wait for all mutator threads to pass the barrier.
1722 Locks::mutator_lock_->SharedUnlock(self);
Hiroshi Yamauchia2224042017-02-08 16:35:45 -08001723 thread_list->RunEmptyCheckpoint();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001724 Locks::mutator_lock_->SharedLock(self);
1725}
1726
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -07001727void ConcurrentCopying::ExpandGcMarkStack() {
1728 DCHECK(gc_mark_stack_->IsFull());
1729 const size_t new_size = gc_mark_stack_->Capacity() * 2;
1730 std::vector<StackReference<mirror::Object>> temp(gc_mark_stack_->Begin(),
1731 gc_mark_stack_->End());
1732 gc_mark_stack_->Resize(new_size);
1733 for (auto& ref : temp) {
1734 gc_mark_stack_->PushBack(ref.AsMirrorPtr());
1735 }
1736 DCHECK(!gc_mark_stack_->IsFull());
1737}
1738
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08001739void ConcurrentCopying::PushOntoMarkStack(Thread* const self, mirror::Object* to_ref) {
Orion Hodson88591fe2018-03-06 13:35:43 +00001740 CHECK_EQ(is_mark_stack_push_disallowed_.load(std::memory_order_relaxed), 0)
David Sehr709b0702016-10-13 09:12:37 -07001741 << " " << to_ref << " " << mirror::Object::PrettyTypeOf(to_ref);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001742 CHECK(thread_running_gc_ != nullptr);
Orion Hodson88591fe2018-03-06 13:35:43 +00001743 MarkStackMode mark_stack_mode = mark_stack_mode_.load(std::memory_order_relaxed);
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001744 if (LIKELY(mark_stack_mode == kMarkStackModeThreadLocal)) {
1745 if (LIKELY(self == thread_running_gc_)) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001746 // If GC-running thread, use the GC mark stack instead of a thread-local mark stack.
1747 CHECK(self->GetThreadLocalMarkStack() == nullptr);
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -07001748 if (UNLIKELY(gc_mark_stack_->IsFull())) {
1749 ExpandGcMarkStack();
1750 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001751 gc_mark_stack_->PushBack(to_ref);
1752 } else {
1753 // Otherwise, use a thread-local mark stack.
1754 accounting::AtomicStack<mirror::Object>* tl_mark_stack = self->GetThreadLocalMarkStack();
1755 if (UNLIKELY(tl_mark_stack == nullptr || tl_mark_stack->IsFull())) {
1756 MutexLock mu(self, mark_stack_lock_);
1757 // Get a new thread local mark stack.
1758 accounting::AtomicStack<mirror::Object>* new_tl_mark_stack;
1759 if (!pooled_mark_stacks_.empty()) {
1760 // Use a pooled mark stack.
1761 new_tl_mark_stack = pooled_mark_stacks_.back();
1762 pooled_mark_stacks_.pop_back();
1763 } else {
1764 // None pooled. Create a new one.
1765 new_tl_mark_stack =
1766 accounting::AtomicStack<mirror::Object>::Create(
1767 "thread local mark stack", 4 * KB, 4 * KB);
1768 }
1769 DCHECK(new_tl_mark_stack != nullptr);
1770 DCHECK(new_tl_mark_stack->IsEmpty());
1771 new_tl_mark_stack->PushBack(to_ref);
1772 self->SetThreadLocalMarkStack(new_tl_mark_stack);
1773 if (tl_mark_stack != nullptr) {
1774 // Store the old full stack into a vector.
1775 revoked_mark_stacks_.push_back(tl_mark_stack);
1776 }
1777 } else {
1778 tl_mark_stack->PushBack(to_ref);
1779 }
1780 }
1781 } else if (mark_stack_mode == kMarkStackModeShared) {
1782 // Access the shared GC mark stack with a lock.
1783 MutexLock mu(self, mark_stack_lock_);
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -07001784 if (UNLIKELY(gc_mark_stack_->IsFull())) {
1785 ExpandGcMarkStack();
1786 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001787 gc_mark_stack_->PushBack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001788 } else {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001789 CHECK_EQ(static_cast<uint32_t>(mark_stack_mode),
Hiroshi Yamauchifa755182015-09-30 20:12:11 -07001790 static_cast<uint32_t>(kMarkStackModeGcExclusive))
1791 << "ref=" << to_ref
1792 << " self->gc_marking=" << self->GetIsGcMarking()
1793 << " cc->is_marking=" << is_marking_;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001794 CHECK(self == thread_running_gc_)
1795 << "Only GC-running thread should access the mark stack "
1796 << "in the GC exclusive mark stack mode";
1797 // Access the GC mark stack without a lock.
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -07001798 if (UNLIKELY(gc_mark_stack_->IsFull())) {
1799 ExpandGcMarkStack();
1800 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001801 gc_mark_stack_->PushBack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001802 }
1803}
1804
1805accounting::ObjectStack* ConcurrentCopying::GetAllocationStack() {
1806 return heap_->allocation_stack_.get();
1807}
1808
1809accounting::ObjectStack* ConcurrentCopying::GetLiveStack() {
1810 return heap_->live_stack_.get();
1811}
1812
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001813// The following visitors are used to verify that there's no references to the from-space left after
1814// marking.
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001815class ConcurrentCopying::VerifyNoFromSpaceRefsVisitor : public SingleRootVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001816 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001817 explicit VerifyNoFromSpaceRefsVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001818 : collector_(collector) {}
1819
Mathieu Chartierbc632f02017-04-20 13:31:39 -07001820 void operator()(mirror::Object* ref,
1821 MemberOffset offset = MemberOffset(0),
1822 mirror::Object* holder = nullptr) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001823 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001824 if (ref == nullptr) {
1825 // OK.
1826 return;
1827 }
Mathieu Chartierbc632f02017-04-20 13:31:39 -07001828 collector_->AssertToSpaceInvariant(holder, offset, ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001829 if (kUseBakerReadBarrier) {
Roland Levillain14e5a292018-06-28 12:00:56 +01001830 CHECK_EQ(ref->GetReadBarrierState(), ReadBarrier::NonGrayState())
1831 << "Ref " << ref << " " << ref->PrettyTypeOf() << " has gray rb_state";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001832 }
1833 }
1834
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001835 void VisitRoot(mirror::Object* root, const RootInfo& info ATTRIBUTE_UNUSED)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001836 override REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001837 DCHECK(root != nullptr);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001838 operator()(root);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001839 }
1840
1841 private:
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001842 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001843};
1844
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001845class ConcurrentCopying::VerifyNoFromSpaceRefsFieldVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001846 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001847 explicit VerifyNoFromSpaceRefsFieldVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001848 : collector_(collector) {}
1849
Mathieu Chartier31e88222016-10-14 18:43:19 -07001850 void operator()(ObjPtr<mirror::Object> obj,
1851 MemberOffset offset,
1852 bool is_static ATTRIBUTE_UNUSED) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001853 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001854 mirror::Object* ref =
1855 obj->GetFieldObject<mirror::Object, kDefaultVerifyFlags, kWithoutReadBarrier>(offset);
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001856 VerifyNoFromSpaceRefsVisitor visitor(collector_);
Mathieu Chartierbc632f02017-04-20 13:31:39 -07001857 visitor(ref, offset, obj.Ptr());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001858 }
Mathieu Chartier31e88222016-10-14 18:43:19 -07001859 void operator()(ObjPtr<mirror::Class> klass,
1860 ObjPtr<mirror::Reference> ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001861 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001862 CHECK(klass->IsTypeOfReferenceClass());
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07001863 this->operator()(ObjPtr<mirror::Object>(ref), mirror::Reference::ReferentOffset(), false);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001864 }
1865
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001866 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001867 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001868 if (!root->IsNull()) {
1869 VisitRoot(root);
1870 }
1871 }
1872
1873 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001874 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001875 VerifyNoFromSpaceRefsVisitor visitor(collector_);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001876 visitor(root->AsMirrorPtr());
1877 }
1878
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001879 private:
Mathieu Chartier97509952015-07-13 14:35:43 -07001880 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001881};
1882
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001883// Verify there's no from-space references left after the marking phase.
1884void ConcurrentCopying::VerifyNoFromSpaceReferences() {
1885 Thread* self = Thread::Current();
1886 DCHECK(Locks::mutator_lock_->IsExclusiveHeld(self));
Hiroshi Yamauchi00370822015-08-18 14:47:25 -07001887 // Verify all threads have is_gc_marking to be false
1888 {
1889 MutexLock mu(self, *Locks::thread_list_lock_);
1890 std::list<Thread*> thread_list = Runtime::Current()->GetThreadList()->GetList();
1891 for (Thread* thread : thread_list) {
1892 CHECK(!thread->GetIsGcMarking());
1893 }
1894 }
Andreas Gampe0c183382017-07-13 22:26:24 -07001895
1896 auto verify_no_from_space_refs_visitor = [&](mirror::Object* obj)
1897 REQUIRES_SHARED(Locks::mutator_lock_) {
1898 CHECK(obj != nullptr);
1899 space::RegionSpace* region_space = RegionSpace();
1900 CHECK(!region_space->IsInFromSpace(obj)) << "Scanning object " << obj << " in from space";
1901 VerifyNoFromSpaceRefsFieldVisitor visitor(this);
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001902 obj->VisitReferences</*kVisitNativeRoots=*/true, kDefaultVerifyFlags, kWithoutReadBarrier>(
Andreas Gampe0c183382017-07-13 22:26:24 -07001903 visitor,
1904 visitor);
1905 if (kUseBakerReadBarrier) {
Roland Levillain14e5a292018-06-28 12:00:56 +01001906 CHECK_EQ(obj->GetReadBarrierState(), ReadBarrier::NonGrayState())
1907 << "obj=" << obj << " has gray rb_state " << obj->GetReadBarrierState();
Andreas Gampe0c183382017-07-13 22:26:24 -07001908 }
1909 };
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001910 // Roots.
1911 {
1912 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001913 VerifyNoFromSpaceRefsVisitor ref_visitor(this);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001914 Runtime::Current()->VisitRoots(&ref_visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001915 }
1916 // The to-space.
Andreas Gampe0c183382017-07-13 22:26:24 -07001917 region_space_->WalkToSpace(verify_no_from_space_refs_visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001918 // Non-moving spaces.
1919 {
1920 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Andreas Gampe0c183382017-07-13 22:26:24 -07001921 heap_->GetMarkBitmap()->Visit(verify_no_from_space_refs_visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001922 }
1923 // The alloc stack.
1924 {
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001925 VerifyNoFromSpaceRefsVisitor ref_visitor(this);
Mathieu Chartiercb535da2015-01-23 13:50:03 -08001926 for (auto* it = heap_->allocation_stack_->Begin(), *end = heap_->allocation_stack_->End();
1927 it < end; ++it) {
1928 mirror::Object* const obj = it->AsMirrorPtr();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001929 if (obj != nullptr && obj->GetClass() != nullptr) {
1930 // TODO: need to call this only if obj is alive?
1931 ref_visitor(obj);
Andreas Gampe0c183382017-07-13 22:26:24 -07001932 verify_no_from_space_refs_visitor(obj);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001933 }
1934 }
1935 }
1936 // TODO: LOS. But only refs in LOS are classes.
1937}
1938
1939// The following visitors are used to assert the to-space invariant.
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001940class ConcurrentCopying::AssertToSpaceInvariantFieldVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001941 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001942 explicit AssertToSpaceInvariantFieldVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001943 : collector_(collector) {}
1944
Mathieu Chartier31e88222016-10-14 18:43:19 -07001945 void operator()(ObjPtr<mirror::Object> obj,
1946 MemberOffset offset,
1947 bool is_static ATTRIBUTE_UNUSED) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001948 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001949 mirror::Object* ref =
1950 obj->GetFieldObject<mirror::Object, kDefaultVerifyFlags, kWithoutReadBarrier>(offset);
Lokesh Gidra519c1c72018-11-09 17:10:47 -08001951 collector_->AssertToSpaceInvariant(obj.Ptr(), offset, ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001952 }
Mathieu Chartier31e88222016-10-14 18:43:19 -07001953 void operator()(ObjPtr<mirror::Class> klass, ObjPtr<mirror::Reference> ref ATTRIBUTE_UNUSED) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001954 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001955 CHECK(klass->IsTypeOfReferenceClass());
1956 }
1957
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001958 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001959 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001960 if (!root->IsNull()) {
1961 VisitRoot(root);
1962 }
1963 }
1964
1965 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001966 REQUIRES_SHARED(Locks::mutator_lock_) {
Lokesh Gidra519c1c72018-11-09 17:10:47 -08001967 mirror::Object* ref = root->AsMirrorPtr();
1968 collector_->AssertToSpaceInvariant(/* obj */ nullptr, MemberOffset(0), ref);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001969 }
1970
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001971 private:
Mathieu Chartier97509952015-07-13 14:35:43 -07001972 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001973};
1974
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001975void ConcurrentCopying::RevokeThreadLocalMarkStacks(bool disable_weak_ref_access,
1976 Closure* checkpoint_callback) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001977 Thread* self = Thread::Current();
1978 RevokeThreadLocalMarkStackCheckpoint check_point(this, disable_weak_ref_access);
1979 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1980 gc_barrier_->Init(self, 0);
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001981 size_t barrier_count = thread_list->RunCheckpoint(&check_point, checkpoint_callback);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001982 // If there are no threads to wait which implys that all the checkpoint functions are finished,
1983 // then no need to release the mutator lock.
1984 if (barrier_count == 0) {
1985 return;
1986 }
1987 Locks::mutator_lock_->SharedUnlock(self);
1988 {
1989 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
1990 gc_barrier_->Increment(self, barrier_count);
1991 }
1992 Locks::mutator_lock_->SharedLock(self);
1993}
1994
1995void ConcurrentCopying::RevokeThreadLocalMarkStack(Thread* thread) {
1996 Thread* self = Thread::Current();
1997 CHECK_EQ(self, thread);
1998 accounting::AtomicStack<mirror::Object>* tl_mark_stack = thread->GetThreadLocalMarkStack();
1999 if (tl_mark_stack != nullptr) {
2000 CHECK(is_marking_);
2001 MutexLock mu(self, mark_stack_lock_);
2002 revoked_mark_stacks_.push_back(tl_mark_stack);
2003 thread->SetThreadLocalMarkStack(nullptr);
2004 }
2005}
2006
2007void ConcurrentCopying::ProcessMarkStack() {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002008 if (kVerboseMode) {
2009 LOG(INFO) << "ProcessMarkStack. ";
2010 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002011 bool empty_prev = false;
2012 while (true) {
2013 bool empty = ProcessMarkStackOnce();
2014 if (empty_prev && empty) {
2015 // Saw empty mark stack for a second time, done.
2016 break;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002017 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002018 empty_prev = empty;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002019 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002020}
2021
2022bool ConcurrentCopying::ProcessMarkStackOnce() {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002023 DCHECK(thread_running_gc_ != nullptr);
2024 Thread* const self = Thread::Current();
2025 DCHECK(self == thread_running_gc_);
2026 DCHECK(thread_running_gc_->GetThreadLocalMarkStack() == nullptr);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002027 size_t count = 0;
Orion Hodson88591fe2018-03-06 13:35:43 +00002028 MarkStackMode mark_stack_mode = mark_stack_mode_.load(std::memory_order_relaxed);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002029 if (mark_stack_mode == kMarkStackModeThreadLocal) {
2030 // Process the thread-local mark stacks and the GC mark stack.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07002031 count += ProcessThreadLocalMarkStacks(/* disable_weak_ref_access= */ false,
Lokesh Gidra2a9824c2018-11-07 15:57:17 -08002032 /* checkpoint_callback= */ nullptr,
2033 [this] (mirror::Object* ref)
2034 REQUIRES_SHARED(Locks::mutator_lock_) {
2035 ProcessMarkStackRef(ref);
2036 });
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002037 while (!gc_mark_stack_->IsEmpty()) {
2038 mirror::Object* to_ref = gc_mark_stack_->PopBack();
2039 ProcessMarkStackRef(to_ref);
2040 ++count;
2041 }
2042 gc_mark_stack_->Reset();
2043 } else if (mark_stack_mode == kMarkStackModeShared) {
Hiroshi Yamauchi30493242016-11-03 13:06:52 -07002044 // Do an empty checkpoint to avoid a race with a mutator preempted in the middle of a read
2045 // barrier but before pushing onto the mark stack. b/32508093. Note the weak ref access is
2046 // disabled at this point.
2047 IssueEmptyCheckpoint();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002048 // Process the shared GC mark stack with a lock.
2049 {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002050 MutexLock mu(thread_running_gc_, mark_stack_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002051 CHECK(revoked_mark_stacks_.empty());
2052 }
2053 while (true) {
2054 std::vector<mirror::Object*> refs;
2055 {
2056 // Copy refs with lock. Note the number of refs should be small.
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002057 MutexLock mu(thread_running_gc_, mark_stack_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002058 if (gc_mark_stack_->IsEmpty()) {
2059 break;
2060 }
2061 for (StackReference<mirror::Object>* p = gc_mark_stack_->Begin();
2062 p != gc_mark_stack_->End(); ++p) {
2063 refs.push_back(p->AsMirrorPtr());
2064 }
2065 gc_mark_stack_->Reset();
2066 }
2067 for (mirror::Object* ref : refs) {
2068 ProcessMarkStackRef(ref);
2069 ++count;
2070 }
2071 }
2072 } else {
2073 CHECK_EQ(static_cast<uint32_t>(mark_stack_mode),
2074 static_cast<uint32_t>(kMarkStackModeGcExclusive));
2075 {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002076 MutexLock mu(thread_running_gc_, mark_stack_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002077 CHECK(revoked_mark_stacks_.empty());
2078 }
2079 // Process the GC mark stack in the exclusive mode. No need to take the lock.
2080 while (!gc_mark_stack_->IsEmpty()) {
2081 mirror::Object* to_ref = gc_mark_stack_->PopBack();
2082 ProcessMarkStackRef(to_ref);
2083 ++count;
2084 }
2085 gc_mark_stack_->Reset();
2086 }
2087
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002088 // Return true if the stack was empty.
2089 return count == 0;
2090}
2091
Lokesh Gidra2a9824c2018-11-07 15:57:17 -08002092template <typename Processor>
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07002093size_t ConcurrentCopying::ProcessThreadLocalMarkStacks(bool disable_weak_ref_access,
Lokesh Gidra2a9824c2018-11-07 15:57:17 -08002094 Closure* checkpoint_callback,
2095 const Processor& processor) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002096 // Run a checkpoint to collect all thread local mark stacks and iterate over them all.
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07002097 RevokeThreadLocalMarkStacks(disable_weak_ref_access, checkpoint_callback);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002098 size_t count = 0;
2099 std::vector<accounting::AtomicStack<mirror::Object>*> mark_stacks;
2100 {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002101 MutexLock mu(thread_running_gc_, mark_stack_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002102 // Make a copy of the mark stack vector.
2103 mark_stacks = revoked_mark_stacks_;
2104 revoked_mark_stacks_.clear();
2105 }
2106 for (accounting::AtomicStack<mirror::Object>* mark_stack : mark_stacks) {
2107 for (StackReference<mirror::Object>* p = mark_stack->Begin(); p != mark_stack->End(); ++p) {
2108 mirror::Object* to_ref = p->AsMirrorPtr();
Lokesh Gidra2a9824c2018-11-07 15:57:17 -08002109 processor(to_ref);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002110 ++count;
2111 }
2112 {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002113 MutexLock mu(thread_running_gc_, mark_stack_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002114 if (pooled_mark_stacks_.size() >= kMarkStackPoolSize) {
2115 // The pool has enough. Delete it.
2116 delete mark_stack;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002117 } else {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002118 // Otherwise, put it into the pool for later reuse.
2119 mark_stack->Reset();
2120 pooled_mark_stacks_.push_back(mark_stack);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002121 }
2122 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002123 }
2124 return count;
2125}
2126
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002127inline void ConcurrentCopying::ProcessMarkStackRef(mirror::Object* to_ref) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002128 DCHECK(!region_space_->IsInFromSpace(to_ref));
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002129 space::RegionSpace::RegionType rtype = region_space_->GetRegionType(to_ref);
Roland Levillain5fcf1ea2018-10-30 11:58:08 +00002130 if (kUseBakerReadBarrier) {
2131 DCHECK(to_ref->GetReadBarrierState() == ReadBarrier::GrayState())
2132 << " to_ref=" << to_ref
2133 << " rb_state=" << to_ref->GetReadBarrierState()
2134 << " is_marked=" << IsMarked(to_ref)
2135 << " type=" << to_ref->PrettyTypeOf()
2136 << " young_gen=" << std::boolalpha << young_gen_ << std::noboolalpha
2137 << " space=" << heap_->DumpSpaceNameFromAddress(to_ref)
Roland Levillain0e155592018-11-05 18:31:49 +00002138 << " region_type=" << rtype
2139 // TODO: Temporary; remove this when this is no longer needed (b/116087961).
2140 << " runtime->sentinel=" << Runtime::Current()->GetSentinel().Read<kWithoutReadBarrier>();
Lokesh Gidra420522a2018-10-26 17:31:27 -07002141 }
Mathieu Chartierc381c362016-08-23 13:27:53 -07002142 bool add_to_live_bytes = false;
Roland Levillain4e751132018-01-15 11:52:58 +00002143 // Invariant: There should be no object from a newly-allocated
2144 // region (either large or non-large) on the mark stack.
2145 DCHECK(!region_space_->IsInNewlyAllocatedRegion(to_ref)) << to_ref;
Lokesh Gidra519c1c72018-11-09 17:10:47 -08002146 bool perform_scan = false;
2147 switch (rtype) {
2148 case space::RegionSpace::RegionType::kRegionTypeUnevacFromSpace:
2149 // Mark the bitmap only in the GC thread here so that we don't need a CAS.
2150 if (!kUseBakerReadBarrier || !region_space_bitmap_->Set(to_ref)) {
2151 // It may be already marked if we accidentally pushed the same object twice due to the racy
2152 // bitmap read in MarkUnevacFromSpaceRegion.
2153 if (kEnableGenerationalConcurrentCopyingCollection && young_gen_) {
2154 CHECK(region_space_->IsLargeObject(to_ref));
2155 region_space_->ZeroLiveBytesForLargeObject(to_ref);
2156 }
2157 perform_scan = true;
2158 // Only add to the live bytes if the object was not already marked and we are not the young
2159 // GC.
Lokesh Gidra2a9824c2018-11-07 15:57:17 -08002160 // Why add live bytes even after 2-phase GC?
2161 // We need to ensure that if there is a unevac region with any live
2162 // objects, then its live_bytes must be non-zero. Otherwise,
2163 // ClearFromSpace() will clear the region. Considering, that we may skip
2164 // live objects during marking phase of 2-phase GC, we have to take care
2165 // of such objects here.
Lokesh Gidra519c1c72018-11-09 17:10:47 -08002166 add_to_live_bytes = true;
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002167 }
Lokesh Gidra519c1c72018-11-09 17:10:47 -08002168 break;
2169 case space::RegionSpace::RegionType::kRegionTypeToSpace:
2170 if (kEnableGenerationalConcurrentCopyingCollection) {
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002171 // Copied to to-space, set the bit so that the next GC can scan objects.
2172 region_space_bitmap_->Set(to_ref);
2173 }
Lokesh Gidra519c1c72018-11-09 17:10:47 -08002174 perform_scan = true;
2175 break;
2176 default:
2177 DCHECK(!region_space_->HasAddress(to_ref)) << to_ref;
2178 DCHECK(!immune_spaces_.ContainsObject(to_ref));
2179 // Non-moving or large-object space.
2180 if (kUseBakerReadBarrier) {
2181 accounting::ContinuousSpaceBitmap* mark_bitmap =
2182 heap_->GetNonMovingSpace()->GetMarkBitmap();
2183 const bool is_los = !mark_bitmap->HasAddress(to_ref);
2184 if (is_los) {
2185 if (!IsAligned<kPageSize>(to_ref)) {
2186 // Ref is a large object that is not aligned, it must be heap
2187 // corruption. Remove memory protection and dump data before
2188 // AtomicSetReadBarrierState since it will fault if the address is not
2189 // valid.
2190 region_space_->Unprotect();
2191 heap_->GetVerification()->LogHeapCorruption(/* obj */ nullptr,
2192 MemberOffset(0),
2193 to_ref,
2194 /* fatal */ true);
2195 }
2196 DCHECK(heap_->GetLargeObjectsSpace())
2197 << "ref=" << to_ref
2198 << " doesn't belong to non-moving space and large object space doesn't exist";
2199 accounting::LargeObjectBitmap* los_bitmap =
2200 heap_->GetLargeObjectsSpace()->GetMarkBitmap();
2201 DCHECK(los_bitmap->HasAddress(to_ref));
2202 // Only the GC thread could be setting the LOS bit map hence doesn't
2203 // need to be atomically done.
2204 perform_scan = !los_bitmap->Set(to_ref);
2205 } else {
2206 // Only the GC thread could be setting the non-moving space bit map
2207 // hence doesn't need to be atomically done.
2208 perform_scan = !mark_bitmap->Set(to_ref);
2209 }
2210 } else {
2211 perform_scan = true;
2212 }
2213 }
2214 if (perform_scan) {
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002215 if (kEnableGenerationalConcurrentCopyingCollection && young_gen_) {
2216 Scan<true>(to_ref);
2217 } else {
2218 Scan<false>(to_ref);
2219 }
Mathieu Chartierc381c362016-08-23 13:27:53 -07002220 }
Roland Levillain5fcf1ea2018-10-30 11:58:08 +00002221 if (kUseBakerReadBarrier) {
2222 DCHECK(to_ref->GetReadBarrierState() == ReadBarrier::GrayState())
2223 << " to_ref=" << to_ref
2224 << " rb_state=" << to_ref->GetReadBarrierState()
2225 << " is_marked=" << IsMarked(to_ref)
2226 << " type=" << to_ref->PrettyTypeOf()
2227 << " young_gen=" << std::boolalpha << young_gen_ << std::noboolalpha
2228 << " space=" << heap_->DumpSpaceNameFromAddress(to_ref)
Roland Levillain0e155592018-11-05 18:31:49 +00002229 << " region_type=" << rtype
2230 // TODO: Temporary; remove this when this is no longer needed (b/116087961).
2231 << " runtime->sentinel=" << Runtime::Current()->GetSentinel().Read<kWithoutReadBarrier>();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002232 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002233#ifdef USE_BAKER_OR_BROOKS_READ_BARRIER
Hiroshi Yamauchi39c12d42016-12-06 16:46:37 -08002234 mirror::Object* referent = nullptr;
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002235 if (UNLIKELY((to_ref->GetClass<kVerifyNone, kWithoutReadBarrier>()->IsTypeOfReferenceClass() &&
Hiroshi Yamauchi39c12d42016-12-06 16:46:37 -08002236 (referent = to_ref->AsReference()->GetReferent<kWithoutReadBarrier>()) != nullptr &&
2237 !IsInToSpace(referent)))) {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08002238 // Leave this reference gray in the queue so that GetReferent() will trigger a read barrier. We
Roland Levillain14e5a292018-06-28 12:00:56 +01002239 // will change it to non-gray later in ReferenceQueue::DisableReadBarrierForReference.
Roland Levillain2ae376f2018-01-30 11:35:11 +00002240 DCHECK(to_ref->AsReference()->GetPendingNext() != nullptr)
2241 << "Left unenqueued ref gray " << to_ref;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002242 } else {
Roland Levillain14e5a292018-06-28 12:00:56 +01002243 // We may occasionally leave a reference non-gray in the queue if its referent happens to be
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08002244 // concurrently marked after the Scan() call above has enqueued the Reference, in which case the
Roland Levillain14e5a292018-06-28 12:00:56 +01002245 // above IsInToSpace() evaluates to true and we change the color from gray to non-gray here in
2246 // this else block.
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002247 if (kUseBakerReadBarrier) {
Mathieu Chartier42c2e502018-06-19 12:30:56 -07002248 bool success = to_ref->AtomicSetReadBarrierState<std::memory_order_release>(
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002249 ReadBarrier::GrayState(),
Roland Levillain14e5a292018-06-28 12:00:56 +01002250 ReadBarrier::NonGrayState());
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08002251 DCHECK(success) << "Must succeed as we won the race.";
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002252 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002253 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002254#else
2255 DCHECK(!kUseBakerReadBarrier);
2256#endif
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08002257
Mathieu Chartierc381c362016-08-23 13:27:53 -07002258 if (add_to_live_bytes) {
Roland Levillain2ae376f2018-01-30 11:35:11 +00002259 // Add to the live bytes per unevacuated from-space. Note this code is always run by the
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08002260 // GC-running thread (no synchronization required).
2261 DCHECK(region_space_bitmap_->Test(to_ref));
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07002262 size_t obj_size = to_ref->SizeOf<kDefaultVerifyFlags>();
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08002263 size_t alloc_size = RoundUp(obj_size, space::RegionSpace::kAlignment);
2264 region_space_->AddLiveBytes(to_ref, alloc_size);
2265 }
Andreas Gampee3ce7872017-02-22 13:36:21 -08002266 if (ReadBarrier::kEnableToSpaceInvariantChecks) {
Andreas Gampe0c183382017-07-13 22:26:24 -07002267 CHECK(to_ref != nullptr);
2268 space::RegionSpace* region_space = RegionSpace();
2269 CHECK(!region_space->IsInFromSpace(to_ref)) << "Scanning object " << to_ref << " in from space";
2270 AssertToSpaceInvariant(nullptr, MemberOffset(0), to_ref);
2271 AssertToSpaceInvariantFieldVisitor visitor(this);
Andreas Gampe98ea9d92018-10-19 14:06:15 -07002272 to_ref->VisitReferences</*kVisitNativeRoots=*/true, kDefaultVerifyFlags, kWithoutReadBarrier>(
Andreas Gampe0c183382017-07-13 22:26:24 -07002273 visitor,
2274 visitor);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002275 }
2276}
2277
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07002278class ConcurrentCopying::DisableWeakRefAccessCallback : public Closure {
2279 public:
2280 explicit DisableWeakRefAccessCallback(ConcurrentCopying* concurrent_copying)
2281 : concurrent_copying_(concurrent_copying) {
2282 }
2283
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002284 void Run(Thread* self ATTRIBUTE_UNUSED) override REQUIRES(Locks::thread_list_lock_) {
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07002285 // This needs to run under the thread_list_lock_ critical section in ThreadList::RunCheckpoint()
2286 // to avoid a deadlock b/31500969.
2287 CHECK(concurrent_copying_->weak_ref_access_enabled_);
2288 concurrent_copying_->weak_ref_access_enabled_ = false;
2289 }
2290
2291 private:
2292 ConcurrentCopying* const concurrent_copying_;
2293};
2294
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002295void ConcurrentCopying::SwitchToSharedMarkStackMode() {
2296 Thread* self = Thread::Current();
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002297 DCHECK(thread_running_gc_ != nullptr);
2298 DCHECK(self == thread_running_gc_);
2299 DCHECK(thread_running_gc_->GetThreadLocalMarkStack() == nullptr);
Orion Hodson88591fe2018-03-06 13:35:43 +00002300 MarkStackMode before_mark_stack_mode = mark_stack_mode_.load(std::memory_order_relaxed);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002301 CHECK_EQ(static_cast<uint32_t>(before_mark_stack_mode),
2302 static_cast<uint32_t>(kMarkStackModeThreadLocal));
Orion Hodson88591fe2018-03-06 13:35:43 +00002303 mark_stack_mode_.store(kMarkStackModeShared, std::memory_order_relaxed);
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07002304 DisableWeakRefAccessCallback dwrac(this);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002305 // Process the thread local mark stacks one last time after switching to the shared mark stack
2306 // mode and disable weak ref accesses.
Lokesh Gidra2a9824c2018-11-07 15:57:17 -08002307 ProcessThreadLocalMarkStacks(/* disable_weak_ref_access= */ true,
2308 &dwrac,
2309 [this] (mirror::Object* ref)
2310 REQUIRES_SHARED(Locks::mutator_lock_) {
2311 ProcessMarkStackRef(ref);
2312 });
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002313 if (kVerboseMode) {
2314 LOG(INFO) << "Switched to shared mark stack mode and disabled weak ref access";
2315 }
2316}
2317
2318void ConcurrentCopying::SwitchToGcExclusiveMarkStackMode() {
2319 Thread* self = Thread::Current();
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002320 DCHECK(thread_running_gc_ != nullptr);
2321 DCHECK(self == thread_running_gc_);
2322 DCHECK(thread_running_gc_->GetThreadLocalMarkStack() == nullptr);
Orion Hodson88591fe2018-03-06 13:35:43 +00002323 MarkStackMode before_mark_stack_mode = mark_stack_mode_.load(std::memory_order_relaxed);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002324 CHECK_EQ(static_cast<uint32_t>(before_mark_stack_mode),
2325 static_cast<uint32_t>(kMarkStackModeShared));
Orion Hodson88591fe2018-03-06 13:35:43 +00002326 mark_stack_mode_.store(kMarkStackModeGcExclusive, std::memory_order_relaxed);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002327 QuasiAtomic::ThreadFenceForConstructor();
2328 if (kVerboseMode) {
2329 LOG(INFO) << "Switched to GC exclusive mark stack mode";
2330 }
2331}
2332
2333void ConcurrentCopying::CheckEmptyMarkStack() {
2334 Thread* self = Thread::Current();
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002335 DCHECK(thread_running_gc_ != nullptr);
2336 DCHECK(self == thread_running_gc_);
2337 DCHECK(thread_running_gc_->GetThreadLocalMarkStack() == nullptr);
Orion Hodson88591fe2018-03-06 13:35:43 +00002338 MarkStackMode mark_stack_mode = mark_stack_mode_.load(std::memory_order_relaxed);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002339 if (mark_stack_mode == kMarkStackModeThreadLocal) {
2340 // Thread-local mark stack mode.
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07002341 RevokeThreadLocalMarkStacks(false, nullptr);
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002342 MutexLock mu(thread_running_gc_, mark_stack_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002343 if (!revoked_mark_stacks_.empty()) {
2344 for (accounting::AtomicStack<mirror::Object>* mark_stack : revoked_mark_stacks_) {
2345 while (!mark_stack->IsEmpty()) {
2346 mirror::Object* obj = mark_stack->PopBack();
2347 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002348 uint32_t rb_state = obj->GetReadBarrierState();
2349 LOG(INFO) << "On mark queue : " << obj << " " << obj->PrettyTypeOf() << " rb_state="
2350 << rb_state << " is_marked=" << IsMarked(obj);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002351 } else {
David Sehr709b0702016-10-13 09:12:37 -07002352 LOG(INFO) << "On mark queue : " << obj << " " << obj->PrettyTypeOf()
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002353 << " is_marked=" << IsMarked(obj);
2354 }
2355 }
2356 }
2357 LOG(FATAL) << "mark stack is not empty";
2358 }
2359 } else {
2360 // Shared, GC-exclusive, or off.
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002361 MutexLock mu(thread_running_gc_, mark_stack_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002362 CHECK(gc_mark_stack_->IsEmpty());
2363 CHECK(revoked_mark_stacks_.empty());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002364 }
2365}
2366
2367void ConcurrentCopying::SweepSystemWeaks(Thread* self) {
2368 TimingLogger::ScopedTiming split("SweepSystemWeaks", GetTimings());
2369 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier97509952015-07-13 14:35:43 -07002370 Runtime::Current()->SweepSystemWeaks(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002371}
2372
2373void ConcurrentCopying::Sweep(bool swap_bitmaps) {
Roland Levillainb1e1dc32018-07-10 19:19:31 +01002374 if (kEnableGenerationalConcurrentCopyingCollection && young_gen_) {
2375 // Only sweep objects on the live stack.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07002376 SweepArray(heap_->GetLiveStack(), /* swap_bitmaps= */ false);
Roland Levillainb1e1dc32018-07-10 19:19:31 +01002377 } else {
2378 {
2379 TimingLogger::ScopedTiming t("MarkStackAsLive", GetTimings());
2380 accounting::ObjectStack* live_stack = heap_->GetLiveStack();
2381 if (kEnableFromSpaceAccountingCheck) {
2382 // Ensure that nobody inserted items in the live stack after we swapped the stacks.
2383 CHECK_GE(live_stack_freeze_size_, live_stack->Size());
2384 }
2385 heap_->MarkAllocStackAsLive(live_stack);
2386 live_stack->Reset();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002387 }
Roland Levillainb1e1dc32018-07-10 19:19:31 +01002388 CheckEmptyMarkStack();
2389 TimingLogger::ScopedTiming split("Sweep", GetTimings());
2390 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
2391 if (space->IsContinuousMemMapAllocSpace()) {
2392 space::ContinuousMemMapAllocSpace* alloc_space = space->AsContinuousMemMapAllocSpace();
2393 if (space == region_space_ || immune_spaces_.ContainsSpace(space)) {
2394 continue;
2395 }
2396 TimingLogger::ScopedTiming split2(
2397 alloc_space->IsZygoteSpace() ? "SweepZygoteSpace" : "SweepAllocSpace", GetTimings());
2398 RecordFree(alloc_space->Sweep(swap_bitmaps));
2399 }
2400 }
2401 SweepLargeObjects(swap_bitmaps);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002402 }
Roland Levillainb1e1dc32018-07-10 19:19:31 +01002403}
2404
2405// Copied and adapted from MarkSweep::SweepArray.
2406void ConcurrentCopying::SweepArray(accounting::ObjectStack* allocations, bool swap_bitmaps) {
2407 // This method is only used when Generational CC collection is enabled.
2408 DCHECK(kEnableGenerationalConcurrentCopyingCollection);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002409 CheckEmptyMarkStack();
Roland Levillainb1e1dc32018-07-10 19:19:31 +01002410 TimingLogger::ScopedTiming t("SweepArray", GetTimings());
2411 Thread* self = Thread::Current();
2412 mirror::Object** chunk_free_buffer = reinterpret_cast<mirror::Object**>(
2413 sweep_array_free_buffer_mem_map_.BaseBegin());
2414 size_t chunk_free_pos = 0;
2415 ObjectBytePair freed;
2416 ObjectBytePair freed_los;
2417 // How many objects are left in the array, modified after each space is swept.
2418 StackReference<mirror::Object>* objects = allocations->Begin();
2419 size_t count = allocations->Size();
2420 // Start by sweeping the continuous spaces.
2421 for (space::ContinuousSpace* space : heap_->GetContinuousSpaces()) {
2422 if (!space->IsAllocSpace() ||
2423 space == region_space_ ||
2424 immune_spaces_.ContainsSpace(space) ||
2425 space->GetLiveBitmap() == nullptr) {
2426 continue;
2427 }
2428 space::AllocSpace* alloc_space = space->AsAllocSpace();
2429 accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
2430 accounting::ContinuousSpaceBitmap* mark_bitmap = space->GetMarkBitmap();
2431 if (swap_bitmaps) {
2432 std::swap(live_bitmap, mark_bitmap);
2433 }
2434 StackReference<mirror::Object>* out = objects;
2435 for (size_t i = 0; i < count; ++i) {
2436 mirror::Object* const obj = objects[i].AsMirrorPtr();
2437 if (kUseThreadLocalAllocationStack && obj == nullptr) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002438 continue;
2439 }
Roland Levillainb1e1dc32018-07-10 19:19:31 +01002440 if (space->HasAddress(obj)) {
2441 // This object is in the space, remove it from the array and add it to the sweep buffer
2442 // if needed.
2443 if (!mark_bitmap->Test(obj)) {
2444 if (chunk_free_pos >= kSweepArrayChunkFreeSize) {
2445 TimingLogger::ScopedTiming t2("FreeList", GetTimings());
2446 freed.objects += chunk_free_pos;
2447 freed.bytes += alloc_space->FreeList(self, chunk_free_pos, chunk_free_buffer);
2448 chunk_free_pos = 0;
2449 }
2450 chunk_free_buffer[chunk_free_pos++] = obj;
2451 }
2452 } else {
2453 (out++)->Assign(obj);
2454 }
2455 }
2456 if (chunk_free_pos > 0) {
2457 TimingLogger::ScopedTiming t2("FreeList", GetTimings());
2458 freed.objects += chunk_free_pos;
2459 freed.bytes += alloc_space->FreeList(self, chunk_free_pos, chunk_free_buffer);
2460 chunk_free_pos = 0;
2461 }
2462 // All of the references which space contained are no longer in the allocation stack, update
2463 // the count.
2464 count = out - objects;
2465 }
2466 // Handle the large object space.
2467 space::LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
2468 if (large_object_space != nullptr) {
2469 accounting::LargeObjectBitmap* large_live_objects = large_object_space->GetLiveBitmap();
2470 accounting::LargeObjectBitmap* large_mark_objects = large_object_space->GetMarkBitmap();
2471 if (swap_bitmaps) {
2472 std::swap(large_live_objects, large_mark_objects);
2473 }
2474 for (size_t i = 0; i < count; ++i) {
2475 mirror::Object* const obj = objects[i].AsMirrorPtr();
2476 // Handle large objects.
2477 if (kUseThreadLocalAllocationStack && obj == nullptr) {
2478 continue;
2479 }
2480 if (!large_mark_objects->Test(obj)) {
2481 ++freed_los.objects;
2482 freed_los.bytes += large_object_space->Free(self, obj);
2483 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002484 }
2485 }
Roland Levillainb1e1dc32018-07-10 19:19:31 +01002486 {
2487 TimingLogger::ScopedTiming t2("RecordFree", GetTimings());
2488 RecordFree(freed);
2489 RecordFreeLOS(freed_los);
2490 t2.NewTiming("ResetStack");
2491 allocations->Reset();
2492 }
2493 sweep_array_free_buffer_mem_map_.MadviseDontNeedAndZero();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002494}
2495
Mathieu Chartier962cd7a2016-08-16 12:15:59 -07002496void ConcurrentCopying::MarkZygoteLargeObjects() {
2497 TimingLogger::ScopedTiming split(__FUNCTION__, GetTimings());
2498 Thread* const self = Thread::Current();
2499 WriterMutexLock rmu(self, *Locks::heap_bitmap_lock_);
2500 space::LargeObjectSpace* const los = heap_->GetLargeObjectsSpace();
Nicolas Geoffray7acddd82017-05-03 15:04:55 +01002501 if (los != nullptr) {
2502 // Pick the current live bitmap (mark bitmap if swapped).
2503 accounting::LargeObjectBitmap* const live_bitmap = los->GetLiveBitmap();
2504 accounting::LargeObjectBitmap* const mark_bitmap = los->GetMarkBitmap();
2505 // Walk through all of the objects and explicitly mark the zygote ones so they don't get swept.
2506 std::pair<uint8_t*, uint8_t*> range = los->GetBeginEndAtomic();
2507 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(range.first),
2508 reinterpret_cast<uintptr_t>(range.second),
2509 [mark_bitmap, los, self](mirror::Object* obj)
2510 REQUIRES(Locks::heap_bitmap_lock_)
2511 REQUIRES_SHARED(Locks::mutator_lock_) {
2512 if (los->IsZygoteLargeObject(self, obj)) {
2513 mark_bitmap->Set(obj);
2514 }
2515 });
2516 }
Mathieu Chartier962cd7a2016-08-16 12:15:59 -07002517}
2518
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002519void ConcurrentCopying::SweepLargeObjects(bool swap_bitmaps) {
2520 TimingLogger::ScopedTiming split("SweepLargeObjects", GetTimings());
Nicolas Geoffray7acddd82017-05-03 15:04:55 +01002521 if (heap_->GetLargeObjectsSpace() != nullptr) {
2522 RecordFreeLOS(heap_->GetLargeObjectsSpace()->Sweep(swap_bitmaps));
2523 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002524}
2525
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002526void ConcurrentCopying::ReclaimPhase() {
2527 TimingLogger::ScopedTiming split("ReclaimPhase", GetTimings());
2528 if (kVerboseMode) {
2529 LOG(INFO) << "GC ReclaimPhase";
2530 }
2531 Thread* self = Thread::Current();
2532
2533 {
2534 // Double-check that the mark stack is empty.
2535 // Note: need to set this after VerifyNoFromSpaceRef().
2536 is_asserting_to_space_invariant_ = false;
2537 QuasiAtomic::ThreadFenceForConstructor();
2538 if (kVerboseMode) {
2539 LOG(INFO) << "Issue an empty check point. ";
2540 }
2541 IssueEmptyCheckpoint();
2542 // Disable the check.
Orion Hodson88591fe2018-03-06 13:35:43 +00002543 is_mark_stack_push_disallowed_.store(0, std::memory_order_seq_cst);
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002544 if (kUseBakerReadBarrier) {
Orion Hodson88591fe2018-03-06 13:35:43 +00002545 updated_all_immune_objects_.store(false, std::memory_order_seq_cst);
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002546 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002547 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002548 }
2549
2550 {
2551 // Record freed objects.
2552 TimingLogger::ScopedTiming split2("RecordFree", GetTimings());
2553 // Don't include thread-locals that are in the to-space.
Mathieu Chartier371b0472017-02-27 16:37:21 -08002554 const uint64_t from_bytes = region_space_->GetBytesAllocatedInFromSpace();
2555 const uint64_t from_objects = region_space_->GetObjectsAllocatedInFromSpace();
2556 const uint64_t unevac_from_bytes = region_space_->GetBytesAllocatedInUnevacFromSpace();
2557 const uint64_t unevac_from_objects = region_space_->GetObjectsAllocatedInUnevacFromSpace();
Hans Boehmfb8b4e22018-09-05 16:45:42 -07002558 uint64_t to_bytes = bytes_moved_.load(std::memory_order_relaxed) + bytes_moved_gc_thread_;
Orion Hodson88591fe2018-03-06 13:35:43 +00002559 cumulative_bytes_moved_.fetch_add(to_bytes, std::memory_order_relaxed);
Hans Boehmfb8b4e22018-09-05 16:45:42 -07002560 uint64_t to_objects = objects_moved_.load(std::memory_order_relaxed) + objects_moved_gc_thread_;
Orion Hodson88591fe2018-03-06 13:35:43 +00002561 cumulative_objects_moved_.fetch_add(to_objects, std::memory_order_relaxed);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002562 if (kEnableFromSpaceAccountingCheck) {
2563 CHECK_EQ(from_space_num_objects_at_first_pause_, from_objects + unevac_from_objects);
2564 CHECK_EQ(from_space_num_bytes_at_first_pause_, from_bytes + unevac_from_bytes);
2565 }
2566 CHECK_LE(to_objects, from_objects);
2567 CHECK_LE(to_bytes, from_bytes);
Albert Mingkun Yange260e542018-11-05 13:45:59 +00002568 if (from_bytes > 0) {
2569 copied_live_bytes_ratio_sum_ += static_cast<float>(to_bytes) / from_bytes;
2570 gc_count_++;
2571 }
2572
Roland Levillain8f7ea9a2018-01-26 17:27:59 +00002573 // Cleared bytes and objects, populated by the call to RegionSpace::ClearFromSpace below.
Mathieu Chartier371b0472017-02-27 16:37:21 -08002574 uint64_t cleared_bytes;
2575 uint64_t cleared_objects;
2576 {
2577 TimingLogger::ScopedTiming split4("ClearFromSpace", GetTimings());
Lokesh Gidra2a9824c2018-11-07 15:57:17 -08002578 region_space_->ClearFromSpace(&cleared_bytes, &cleared_objects, /*clear_bitmap*/ !young_gen_);
Roland Levillain8f7ea9a2018-01-26 17:27:59 +00002579 // `cleared_bytes` and `cleared_objects` may be greater than the from space equivalents since
2580 // RegionSpace::ClearFromSpace may clear empty unevac regions.
Mathieu Chartier371b0472017-02-27 16:37:21 -08002581 CHECK_GE(cleared_bytes, from_bytes);
2582 CHECK_GE(cleared_objects, from_objects);
2583 }
2584 int64_t freed_bytes = cleared_bytes - to_bytes;
2585 int64_t freed_objects = cleared_objects - to_objects;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002586 if (kVerboseMode) {
2587 LOG(INFO) << "RecordFree:"
2588 << " from_bytes=" << from_bytes << " from_objects=" << from_objects
Roland Levillain2ae376f2018-01-30 11:35:11 +00002589 << " unevac_from_bytes=" << unevac_from_bytes
2590 << " unevac_from_objects=" << unevac_from_objects
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002591 << " to_bytes=" << to_bytes << " to_objects=" << to_objects
2592 << " freed_bytes=" << freed_bytes << " freed_objects=" << freed_objects
2593 << " from_space size=" << region_space_->FromSpaceSize()
2594 << " unevac_from_space size=" << region_space_->UnevacFromSpaceSize()
2595 << " to_space size=" << region_space_->ToSpaceSize();
Roland Levillain2ae376f2018-01-30 11:35:11 +00002596 LOG(INFO) << "(before) num_bytes_allocated="
Hans Boehmfb8b4e22018-09-05 16:45:42 -07002597 << heap_->num_bytes_allocated_.load();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002598 }
2599 RecordFree(ObjectBytePair(freed_objects, freed_bytes));
2600 if (kVerboseMode) {
Roland Levillain2ae376f2018-01-30 11:35:11 +00002601 LOG(INFO) << "(after) num_bytes_allocated="
Hans Boehmfb8b4e22018-09-05 16:45:42 -07002602 << heap_->num_bytes_allocated_.load();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002603 }
Albert Mingkun Yang66937422018-11-30 17:52:01 +00002604
2605 float reclaimed_bytes_ratio = static_cast<float>(freed_bytes) / num_bytes_allocated_before_gc_;
2606 reclaimed_bytes_ratio_sum_ += reclaimed_bytes_ratio;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002607 }
2608
2609 {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002610 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Andreas Gampe98ea9d92018-10-19 14:06:15 -07002611 Sweep(/* swap_bitmaps= */ false);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002612 SwapBitmaps();
2613 heap_->UnBindBitmaps();
2614
Mathieu Chartier7ec38dc2016-10-07 15:24:46 -07002615 // The bitmap was cleared at the start of the GC, there is nothing we need to do here.
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002616 DCHECK(region_space_bitmap_ != nullptr);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002617 region_space_bitmap_ = nullptr;
2618 }
2619
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002620 CheckEmptyMarkStack();
2621
Albert Mingkun Yangde94ea72018-11-16 10:15:49 +00002622 if (heap_->dump_region_info_after_gc_) {
2623 LOG(INFO) << "time=" << region_space_->Time();
2624 region_space_->DumpNonFreeRegions(LOG_STREAM(INFO));
2625 }
2626
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002627 if (kVerboseMode) {
2628 LOG(INFO) << "GC end of ReclaimPhase";
2629 }
2630}
2631
Roland Levillain001eff92018-01-24 14:24:33 +00002632std::string ConcurrentCopying::DumpReferenceInfo(mirror::Object* ref,
2633 const char* ref_name,
Andreas Gampebc802de2018-06-20 17:24:11 -07002634 const char* indent) {
Roland Levillain001eff92018-01-24 14:24:33 +00002635 std::ostringstream oss;
2636 oss << indent << heap_->GetVerification()->DumpObjectInfo(ref, ref_name) << '\n';
2637 if (ref != nullptr) {
2638 if (kUseBakerReadBarrier) {
2639 oss << indent << ref_name << "->GetMarkBit()=" << ref->GetMarkBit() << '\n';
2640 oss << indent << ref_name << "->GetReadBarrierState()=" << ref->GetReadBarrierState() << '\n';
2641 }
2642 }
2643 if (region_space_->HasAddress(ref)) {
2644 oss << indent << "Region containing " << ref_name << ":" << '\n';
2645 region_space_->DumpRegionForObject(oss, ref);
2646 if (region_space_bitmap_ != nullptr) {
2647 oss << indent << "region_space_bitmap_->Test(" << ref_name << ")="
2648 << std::boolalpha << region_space_bitmap_->Test(ref) << std::noboolalpha;
2649 }
2650 }
2651 return oss.str();
2652}
2653
2654std::string ConcurrentCopying::DumpHeapReference(mirror::Object* obj,
2655 MemberOffset offset,
2656 mirror::Object* ref) {
2657 std::ostringstream oss;
Andreas Gampebc802de2018-06-20 17:24:11 -07002658 constexpr const char* kIndent = " ";
2659 oss << kIndent << "Invalid reference: ref=" << ref
Roland Levillain001eff92018-01-24 14:24:33 +00002660 << " referenced from: object=" << obj << " offset= " << offset << '\n';
2661 // Information about `obj`.
Andreas Gampebc802de2018-06-20 17:24:11 -07002662 oss << DumpReferenceInfo(obj, "obj", kIndent) << '\n';
Roland Levillain001eff92018-01-24 14:24:33 +00002663 // Information about `ref`.
Andreas Gampebc802de2018-06-20 17:24:11 -07002664 oss << DumpReferenceInfo(ref, "ref", kIndent);
Roland Levillain001eff92018-01-24 14:24:33 +00002665 return oss.str();
2666}
2667
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07002668void ConcurrentCopying::AssertToSpaceInvariant(mirror::Object* obj,
2669 MemberOffset offset,
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002670 mirror::Object* ref) {
Roland Levillain001eff92018-01-24 14:24:33 +00002671 CHECK_EQ(heap_->collector_type_, kCollectorTypeCC) << static_cast<size_t>(heap_->collector_type_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002672 if (is_asserting_to_space_invariant_) {
Lokesh Gidra519c1c72018-11-09 17:10:47 -08002673 if (ref == nullptr) {
2674 // OK.
2675 return;
2676 } else if (region_space_->HasAddress(ref)) {
Roland Levillain001eff92018-01-24 14:24:33 +00002677 // Check to-space invariant in region space (moving space).
2678 using RegionType = space::RegionSpace::RegionType;
Roland Levillain2dd2e1e2018-02-28 16:24:51 +00002679 space::RegionSpace::RegionType type = region_space_->GetRegionTypeUnsafe(ref);
Roland Levillain001eff92018-01-24 14:24:33 +00002680 if (type == RegionType::kRegionTypeToSpace) {
2681 // OK.
2682 return;
2683 } else if (type == RegionType::kRegionTypeUnevacFromSpace) {
2684 if (!IsMarkedInUnevacFromSpace(ref)) {
2685 LOG(FATAL_WITHOUT_ABORT) << "Found unmarked reference in unevac from-space:";
Roland Levillainca3dded2018-08-10 15:35:17 +01002686 // Remove memory protection from the region space and log debugging information.
2687 region_space_->Unprotect();
Roland Levillain001eff92018-01-24 14:24:33 +00002688 LOG(FATAL_WITHOUT_ABORT) << DumpHeapReference(obj, offset, ref);
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002689 Thread::Current()->DumpJavaStack(LOG_STREAM(FATAL_WITHOUT_ABORT));
Roland Levillain001eff92018-01-24 14:24:33 +00002690 }
2691 CHECK(IsMarkedInUnevacFromSpace(ref)) << ref;
2692 } else {
2693 // Not OK: either a from-space ref or a reference in an unused region.
Roland Levillain001eff92018-01-24 14:24:33 +00002694 if (type == RegionType::kRegionTypeFromSpace) {
2695 LOG(FATAL_WITHOUT_ABORT) << "Found from-space reference:";
2696 } else {
2697 LOG(FATAL_WITHOUT_ABORT) << "Found reference in region with type " << type << ":";
2698 }
Roland Levillainca3dded2018-08-10 15:35:17 +01002699 // Remove memory protection from the region space and log debugging information.
2700 region_space_->Unprotect();
Roland Levillain001eff92018-01-24 14:24:33 +00002701 LOG(FATAL_WITHOUT_ABORT) << DumpHeapReference(obj, offset, ref);
2702 if (obj != nullptr) {
2703 LogFromSpaceRefHolder(obj, offset);
Roland Levillain57ce0542018-08-07 16:20:31 +01002704 LOG(FATAL_WITHOUT_ABORT) << "UNEVAC " << region_space_->IsInUnevacFromSpace(obj) << " "
2705 << obj << " " << obj->GetMarkBit();
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002706 if (region_space_->HasAddress(obj)) {
Roland Levillain57ce0542018-08-07 16:20:31 +01002707 region_space_->DumpRegionForObject(LOG_STREAM(FATAL_WITHOUT_ABORT), obj);
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002708 }
Roland Levillain57ce0542018-08-07 16:20:31 +01002709 LOG(FATAL_WITHOUT_ABORT) << "CARD " << static_cast<size_t>(
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002710 *Runtime::Current()->GetHeap()->GetCardTable()->CardFromAddr(
2711 reinterpret_cast<uint8_t*>(obj)));
Roland Levillain57ce0542018-08-07 16:20:31 +01002712 if (region_space_->HasAddress(obj)) {
2713 LOG(FATAL_WITHOUT_ABORT) << "BITMAP " << region_space_bitmap_->Test(obj);
2714 } else {
2715 accounting::ContinuousSpaceBitmap* mark_bitmap =
2716 heap_mark_bitmap_->GetContinuousSpaceBitmap(obj);
2717 if (mark_bitmap != nullptr) {
2718 LOG(FATAL_WITHOUT_ABORT) << "BITMAP " << mark_bitmap->Test(obj);
2719 } else {
2720 accounting::LargeObjectBitmap* los_bitmap =
2721 heap_mark_bitmap_->GetLargeObjectBitmap(obj);
2722 LOG(FATAL_WITHOUT_ABORT) << "BITMAP " << los_bitmap->Test(obj);
2723 }
2724 }
Roland Levillain001eff92018-01-24 14:24:33 +00002725 }
2726 ref->GetLockWord(false).Dump(LOG_STREAM(FATAL_WITHOUT_ABORT));
2727 LOG(FATAL_WITHOUT_ABORT) << "Non-free regions:";
2728 region_space_->DumpNonFreeRegions(LOG_STREAM(FATAL_WITHOUT_ABORT));
2729 PrintFileToLog("/proc/self/maps", LogSeverity::FATAL_WITHOUT_ABORT);
Andreas Gampe98ea9d92018-10-19 14:06:15 -07002730 MemMap::DumpMaps(LOG_STREAM(FATAL_WITHOUT_ABORT), /* terse= */ true);
Roland Levillain001eff92018-01-24 14:24:33 +00002731 LOG(FATAL) << "Invalid reference " << ref
2732 << " referenced from object " << obj << " at offset " << offset;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002733 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002734 } else {
Roland Levillain001eff92018-01-24 14:24:33 +00002735 // Check to-space invariant in non-moving space.
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002736 AssertToSpaceInvariantInNonMovingSpace(obj, ref);
2737 }
2738 }
2739}
2740
2741class RootPrinter {
2742 public:
2743 RootPrinter() { }
2744
2745 template <class MirrorType>
2746 ALWAYS_INLINE void VisitRootIfNonNull(mirror::CompressedReference<MirrorType>* root)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002747 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002748 if (!root->IsNull()) {
2749 VisitRoot(root);
2750 }
2751 }
2752
2753 template <class MirrorType>
2754 void VisitRoot(mirror::Object** root)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002755 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07002756 LOG(FATAL_WITHOUT_ABORT) << "root=" << root << " ref=" << *root;
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002757 }
2758
2759 template <class MirrorType>
2760 void VisitRoot(mirror::CompressedReference<MirrorType>* root)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002761 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07002762 LOG(FATAL_WITHOUT_ABORT) << "root=" << root << " ref=" << root->AsMirrorPtr();
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002763 }
2764};
2765
Roland Levillain001eff92018-01-24 14:24:33 +00002766std::string ConcurrentCopying::DumpGcRoot(mirror::Object* ref) {
2767 std::ostringstream oss;
Andreas Gampebc802de2018-06-20 17:24:11 -07002768 constexpr const char* kIndent = " ";
2769 oss << kIndent << "Invalid GC root: ref=" << ref << '\n';
Roland Levillain001eff92018-01-24 14:24:33 +00002770 // Information about `ref`.
Andreas Gampebc802de2018-06-20 17:24:11 -07002771 oss << DumpReferenceInfo(ref, "ref", kIndent);
Roland Levillain001eff92018-01-24 14:24:33 +00002772 return oss.str();
2773}
2774
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002775void ConcurrentCopying::AssertToSpaceInvariant(GcRootSource* gc_root_source,
2776 mirror::Object* ref) {
Roland Levillain001eff92018-01-24 14:24:33 +00002777 CHECK_EQ(heap_->collector_type_, kCollectorTypeCC) << static_cast<size_t>(heap_->collector_type_);
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002778 if (is_asserting_to_space_invariant_) {
Lokesh Gidra519c1c72018-11-09 17:10:47 -08002779 if (ref == nullptr) {
2780 // OK.
2781 return;
2782 } else if (region_space_->HasAddress(ref)) {
Roland Levillain001eff92018-01-24 14:24:33 +00002783 // Check to-space invariant in region space (moving space).
2784 using RegionType = space::RegionSpace::RegionType;
Roland Levillain2dd2e1e2018-02-28 16:24:51 +00002785 space::RegionSpace::RegionType type = region_space_->GetRegionTypeUnsafe(ref);
Roland Levillain001eff92018-01-24 14:24:33 +00002786 if (type == RegionType::kRegionTypeToSpace) {
2787 // OK.
2788 return;
2789 } else if (type == RegionType::kRegionTypeUnevacFromSpace) {
2790 if (!IsMarkedInUnevacFromSpace(ref)) {
2791 LOG(FATAL_WITHOUT_ABORT) << "Found unmarked reference in unevac from-space:";
Roland Levillainca3dded2018-08-10 15:35:17 +01002792 // Remove memory protection from the region space and log debugging information.
2793 region_space_->Unprotect();
Roland Levillain001eff92018-01-24 14:24:33 +00002794 LOG(FATAL_WITHOUT_ABORT) << DumpGcRoot(ref);
2795 }
2796 CHECK(IsMarkedInUnevacFromSpace(ref)) << ref;
2797 } else {
2798 // Not OK: either a from-space ref or a reference in an unused region.
Roland Levillain001eff92018-01-24 14:24:33 +00002799 if (type == RegionType::kRegionTypeFromSpace) {
2800 LOG(FATAL_WITHOUT_ABORT) << "Found from-space reference:";
2801 } else {
2802 LOG(FATAL_WITHOUT_ABORT) << "Found reference in region with type " << type << ":";
2803 }
Roland Levillainca3dded2018-08-10 15:35:17 +01002804 // Remove memory protection from the region space and log debugging information.
2805 region_space_->Unprotect();
Roland Levillain001eff92018-01-24 14:24:33 +00002806 LOG(FATAL_WITHOUT_ABORT) << DumpGcRoot(ref);
2807 if (gc_root_source == nullptr) {
2808 // No info.
2809 } else if (gc_root_source->HasArtField()) {
2810 ArtField* field = gc_root_source->GetArtField();
2811 LOG(FATAL_WITHOUT_ABORT) << "gc root in field " << field << " "
2812 << ArtField::PrettyField(field);
2813 RootPrinter root_printer;
2814 field->VisitRoots(root_printer);
2815 } else if (gc_root_source->HasArtMethod()) {
2816 ArtMethod* method = gc_root_source->GetArtMethod();
2817 LOG(FATAL_WITHOUT_ABORT) << "gc root in method " << method << " "
2818 << ArtMethod::PrettyMethod(method);
2819 RootPrinter root_printer;
2820 method->VisitRoots(root_printer, kRuntimePointerSize);
2821 }
2822 ref->GetLockWord(false).Dump(LOG_STREAM(FATAL_WITHOUT_ABORT));
2823 LOG(FATAL_WITHOUT_ABORT) << "Non-free regions:";
2824 region_space_->DumpNonFreeRegions(LOG_STREAM(FATAL_WITHOUT_ABORT));
2825 PrintFileToLog("/proc/self/maps", LogSeverity::FATAL_WITHOUT_ABORT);
Andreas Gampe98ea9d92018-10-19 14:06:15 -07002826 MemMap::DumpMaps(LOG_STREAM(FATAL_WITHOUT_ABORT), /* terse= */ true);
Roland Levillain001eff92018-01-24 14:24:33 +00002827 LOG(FATAL) << "Invalid reference " << ref;
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002828 }
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002829 } else {
Roland Levillain001eff92018-01-24 14:24:33 +00002830 // Check to-space invariant in non-moving space.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07002831 AssertToSpaceInvariantInNonMovingSpace(/* obj= */ nullptr, ref);
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002832 }
2833 }
2834}
2835
2836void ConcurrentCopying::LogFromSpaceRefHolder(mirror::Object* obj, MemberOffset offset) {
2837 if (kUseBakerReadBarrier) {
David Sehr709b0702016-10-13 09:12:37 -07002838 LOG(INFO) << "holder=" << obj << " " << obj->PrettyTypeOf()
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002839 << " holder rb_state=" << obj->GetReadBarrierState();
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002840 } else {
David Sehr709b0702016-10-13 09:12:37 -07002841 LOG(INFO) << "holder=" << obj << " " << obj->PrettyTypeOf();
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002842 }
2843 if (region_space_->IsInFromSpace(obj)) {
2844 LOG(INFO) << "holder is in the from-space.";
2845 } else if (region_space_->IsInToSpace(obj)) {
2846 LOG(INFO) << "holder is in the to-space.";
2847 } else if (region_space_->IsInUnevacFromSpace(obj)) {
2848 LOG(INFO) << "holder is in the unevac from-space.";
Mathieu Chartierc381c362016-08-23 13:27:53 -07002849 if (IsMarkedInUnevacFromSpace(obj)) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002850 LOG(INFO) << "holder is marked in the region space bitmap.";
2851 } else {
2852 LOG(INFO) << "holder is not marked in the region space bitmap.";
2853 }
2854 } else {
2855 // In a non-moving space.
Mathieu Chartier763a31e2015-11-16 16:05:55 -08002856 if (immune_spaces_.ContainsObject(obj)) {
2857 LOG(INFO) << "holder is in an immune image or the zygote space.";
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002858 } else {
Mathieu Chartier763a31e2015-11-16 16:05:55 -08002859 LOG(INFO) << "holder is in a non-immune, non-moving (or main) space.";
Lokesh Gidra519c1c72018-11-09 17:10:47 -08002860 accounting::ContinuousSpaceBitmap* mark_bitmap = heap_->GetNonMovingSpace()->GetMarkBitmap();
2861 accounting::LargeObjectBitmap* los_bitmap = nullptr;
2862 const bool is_los = !mark_bitmap->HasAddress(obj);
2863 if (is_los) {
2864 DCHECK(heap_->GetLargeObjectsSpace() && heap_->GetLargeObjectsSpace()->Contains(obj))
2865 << "obj=" << obj
2866 << " LOS bit map covers the entire lower 4GB address range";
2867 los_bitmap = heap_->GetLargeObjectsSpace()->GetMarkBitmap();
2868 }
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002869 if (!is_los && mark_bitmap->Test(obj)) {
Lokesh Gidra519c1c72018-11-09 17:10:47 -08002870 LOG(INFO) << "holder is marked in the non-moving space mark bit map.";
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002871 } else if (is_los && los_bitmap->Test(obj)) {
2872 LOG(INFO) << "holder is marked in the los bit map.";
2873 } else {
2874 // If ref is on the allocation stack, then it is considered
2875 // mark/alive (but not necessarily on the live stack.)
2876 if (IsOnAllocStack(obj)) {
2877 LOG(INFO) << "holder is on the alloc stack.";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002878 } else {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002879 LOG(INFO) << "holder is not marked or on the alloc stack.";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002880 }
2881 }
2882 }
2883 }
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002884 LOG(INFO) << "offset=" << offset.SizeValue();
2885}
2886
Lokesh Gidra519c1c72018-11-09 17:10:47 -08002887bool ConcurrentCopying::IsMarkedInNonMovingSpace(mirror::Object* from_ref) {
2888 DCHECK(!region_space_->HasAddress(from_ref)) << "ref=" << from_ref;
2889 DCHECK(!immune_spaces_.ContainsObject(from_ref)) << "ref=" << from_ref;
2890 if (kUseBakerReadBarrier && from_ref->GetReadBarrierStateAcquire() == ReadBarrier::GrayState()) {
2891 return true;
Lokesh Gidra2a9824c2018-11-07 15:57:17 -08002892 } else if (!kEnableGenerationalConcurrentCopyingCollection
Lokesh Gidra519c1c72018-11-09 17:10:47 -08002893 || done_scanning_.load(std::memory_order_acquire)) {
2894 // Read the comment in IsMarkedInUnevacFromSpace()
2895 accounting::ContinuousSpaceBitmap* mark_bitmap = heap_->GetNonMovingSpace()->GetMarkBitmap();
2896 accounting::LargeObjectBitmap* los_bitmap = nullptr;
2897 const bool is_los = !mark_bitmap->HasAddress(from_ref);
2898 if (is_los) {
2899 DCHECK(heap_->GetLargeObjectsSpace() && heap_->GetLargeObjectsSpace()->Contains(from_ref))
2900 << "ref=" << from_ref
2901 << " doesn't belong to non-moving space and large object space doesn't exist";
2902 los_bitmap = heap_->GetLargeObjectsSpace()->GetMarkBitmap();
2903 }
2904 if (is_los ? los_bitmap->Test(from_ref) : mark_bitmap->Test(from_ref)) {
2905 return true;
2906 }
2907 }
2908 return IsOnAllocStack(from_ref);
2909}
2910
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002911void ConcurrentCopying::AssertToSpaceInvariantInNonMovingSpace(mirror::Object* obj,
2912 mirror::Object* ref) {
Roland Levillainbe4b8fd2018-09-03 14:38:37 +01002913 CHECK(ref != nullptr);
Roland Levillain001eff92018-01-24 14:24:33 +00002914 CHECK(!region_space_->HasAddress(ref)) << "obj=" << obj << " ref=" << ref;
Roland Levillainef012222017-06-21 16:28:06 +01002915 // In a non-moving space. Check that the ref is marked.
Mathieu Chartier763a31e2015-11-16 16:05:55 -08002916 if (immune_spaces_.ContainsObject(ref)) {
Roland Levillain8def52a2018-09-05 15:31:19 +01002917 // Immune space case.
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002918 if (kUseBakerReadBarrier) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002919 // Immune object may not be gray if called from the GC.
2920 if (Thread::Current() == thread_running_gc_ && !gc_grays_immune_objects_) {
2921 return;
2922 }
Orion Hodson88591fe2018-03-06 13:35:43 +00002923 bool updated_all_immune_objects = updated_all_immune_objects_.load(std::memory_order_seq_cst);
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002924 CHECK(updated_all_immune_objects || ref->GetReadBarrierState() == ReadBarrier::GrayState())
2925 << "Unmarked immune space ref. obj=" << obj << " rb_state="
2926 << (obj != nullptr ? obj->GetReadBarrierState() : 0U)
2927 << " ref=" << ref << " ref rb_state=" << ref->GetReadBarrierState()
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002928 << " updated_all_immune_objects=" << updated_all_immune_objects;
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002929 }
2930 } else {
Roland Levillain8def52a2018-09-05 15:31:19 +01002931 // Non-moving space and large-object space (LOS) cases.
Roland Levillain8def52a2018-09-05 15:31:19 +01002932 // If `ref` is on the allocation stack, then it may not be
2933 // marked live, but considered marked/alive (but not
2934 // necessarily on the live stack).
Lokesh Gidra519c1c72018-11-09 17:10:47 -08002935 CHECK(IsMarkedInNonMovingSpace(ref))
Roland Levillain8def52a2018-09-05 15:31:19 +01002936 << "Unmarked ref that's not on the allocation stack."
2937 << " obj=" << obj
2938 << " ref=" << ref
2939 << " rb_state=" << ref->GetReadBarrierState()
Roland Levillain8def52a2018-09-05 15:31:19 +01002940 << " is_marking=" << std::boolalpha << is_marking_ << std::noboolalpha
2941 << " young_gen=" << std::boolalpha << young_gen_ << std::noboolalpha
2942 << " done_scanning="
2943 << std::boolalpha << done_scanning_.load(std::memory_order_acquire) << std::noboolalpha
2944 << " self=" << Thread::Current();
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002945 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002946}
2947
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002948// Used to scan ref fields of an object.
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002949template <bool kNoUnEvac>
Mathieu Chartiera07f5592016-06-16 11:44:28 -07002950class ConcurrentCopying::RefFieldsVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002951 public:
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002952 explicit RefFieldsVisitor(ConcurrentCopying* collector, Thread* const thread)
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002953 : collector_(collector), thread_(thread) {
2954 // Cannot have `kNoUnEvac` when Generational CC collection is disabled.
2955 DCHECK(kEnableGenerationalConcurrentCopyingCollection || !kNoUnEvac);
2956 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002957
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07002958 void operator()(mirror::Object* obj, MemberOffset offset, bool /* is_static */)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002959 const ALWAYS_INLINE REQUIRES_SHARED(Locks::mutator_lock_)
2960 REQUIRES_SHARED(Locks::heap_bitmap_lock_) {
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002961 collector_->Process<kNoUnEvac>(obj, offset);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002962 }
2963
Mathieu Chartier31e88222016-10-14 18:43:19 -07002964 void operator()(ObjPtr<mirror::Class> klass, ObjPtr<mirror::Reference> ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002965 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002966 CHECK(klass->IsTypeOfReferenceClass());
2967 collector_->DelayReferenceReferent(klass, ref);
2968 }
2969
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002970 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002971 ALWAYS_INLINE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002972 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002973 if (!root->IsNull()) {
2974 VisitRoot(root);
2975 }
2976 }
2977
2978 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002979 ALWAYS_INLINE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002980 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe98ea9d92018-10-19 14:06:15 -07002981 collector_->MarkRoot</*kGrayImmuneObject=*/false>(thread_, root);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002982 }
2983
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002984 private:
2985 ConcurrentCopying* const collector_;
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002986 Thread* const thread_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002987};
2988
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002989template <bool kNoUnEvac>
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002990inline void ConcurrentCopying::Scan(mirror::Object* to_ref) {
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002991 // Cannot have `kNoUnEvac` when Generational CC collection is disabled.
2992 DCHECK(kEnableGenerationalConcurrentCopyingCollection || !kNoUnEvac);
Hiroshi Yamauchi9b60d502017-02-03 15:09:26 -08002993 if (kDisallowReadBarrierDuringScan && !Runtime::Current()->IsActiveTransaction()) {
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07002994 // Avoid all read barriers during visit references to help performance.
Hiroshi Yamauchi9b60d502017-02-03 15:09:26 -08002995 // Don't do this in transaction mode because we may read the old value of an field which may
2996 // trigger read barriers.
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07002997 Thread::Current()->ModifyDebugDisallowReadBarrier(1);
2998 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002999 DCHECK(!region_space_->IsInFromSpace(to_ref));
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07003000 DCHECK_EQ(Thread::Current(), thread_running_gc_);
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07003001 RefFieldsVisitor<kNoUnEvac> visitor(this, thread_running_gc_);
Hiroshi Yamauchi5496f692016-02-17 13:29:59 -08003002 // Disable the read barrier for a performance reason.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07003003 to_ref->VisitReferences</*kVisitNativeRoots=*/true, kDefaultVerifyFlags, kWithoutReadBarrier>(
Hiroshi Yamauchi5496f692016-02-17 13:29:59 -08003004 visitor, visitor);
Hiroshi Yamauchi9b60d502017-02-03 15:09:26 -08003005 if (kDisallowReadBarrierDuringScan && !Runtime::Current()->IsActiveTransaction()) {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08003006 thread_running_gc_->ModifyDebugDisallowReadBarrier(-1);
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07003007 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003008}
3009
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07003010template <bool kNoUnEvac>
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003011inline void ConcurrentCopying::Process(mirror::Object* obj, MemberOffset offset) {
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07003012 // Cannot have `kNoUnEvac` when Generational CC collection is disabled.
3013 DCHECK(kEnableGenerationalConcurrentCopyingCollection || !kNoUnEvac);
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07003014 DCHECK_EQ(Thread::Current(), thread_running_gc_);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07003015 mirror::Object* ref = obj->GetFieldObject<
3016 mirror::Object, kVerifyNone, kWithoutReadBarrier, false>(offset);
Andreas Gampe98ea9d92018-10-19 14:06:15 -07003017 mirror::Object* to_ref = Mark</*kGrayImmuneObject=*/false, kNoUnEvac, /*kFromGCThread=*/true>(
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08003018 thread_running_gc_,
Mathieu Chartier4ce0c762017-05-18 10:01:07 -07003019 ref,
Andreas Gampe98ea9d92018-10-19 14:06:15 -07003020 /*holder=*/ obj,
Mathieu Chartier4ce0c762017-05-18 10:01:07 -07003021 offset);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003022 if (to_ref == ref) {
3023 return;
3024 }
3025 // This may fail if the mutator writes to the field at the same time. But it's ok.
3026 mirror::Object* expected_ref = ref;
3027 mirror::Object* new_ref = to_ref;
3028 do {
3029 if (expected_ref !=
3030 obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier, false>(offset)) {
3031 // It was updated by the mutator.
3032 break;
3033 }
Roland Levillain2ae376f2018-01-30 11:35:11 +00003034 // Use release CAS to make sure threads reading the reference see contents of copied objects.
Mathieu Chartiera9746b92018-06-22 10:25:40 -07003035 } while (!obj->CasFieldObjectWithoutWriteBarrier<false, false, kVerifyNone>(
Mathieu Chartierfdd513d2017-06-01 11:26:50 -07003036 offset,
3037 expected_ref,
Mathieu Chartiera9746b92018-06-22 10:25:40 -07003038 new_ref,
3039 CASMode::kWeak,
3040 std::memory_order_release));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003041}
3042
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07003043// Process some roots.
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07003044inline void ConcurrentCopying::VisitRoots(
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07003045 mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED) {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08003046 Thread* const self = Thread::Current();
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07003047 for (size_t i = 0; i < count; ++i) {
3048 mirror::Object** root = roots[i];
3049 mirror::Object* ref = *root;
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08003050 mirror::Object* to_ref = Mark(self, ref);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07003051 if (to_ref == ref) {
Mathieu Chartier4809d0a2015-04-07 10:39:04 -07003052 continue;
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07003053 }
3054 Atomic<mirror::Object*>* addr = reinterpret_cast<Atomic<mirror::Object*>*>(root);
3055 mirror::Object* expected_ref = ref;
3056 mirror::Object* new_ref = to_ref;
3057 do {
Orion Hodson88591fe2018-03-06 13:35:43 +00003058 if (expected_ref != addr->load(std::memory_order_relaxed)) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07003059 // It was updated by the mutator.
3060 break;
3061 }
Orion Hodson4557b382018-01-03 11:47:54 +00003062 } while (!addr->CompareAndSetWeakRelaxed(expected_ref, new_ref));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07003063 }
3064}
3065
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07003066template<bool kGrayImmuneObject>
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08003067inline void ConcurrentCopying::MarkRoot(Thread* const self,
3068 mirror::CompressedReference<mirror::Object>* root) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07003069 DCHECK(!root->IsNull());
3070 mirror::Object* const ref = root->AsMirrorPtr();
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08003071 mirror::Object* to_ref = Mark<kGrayImmuneObject>(self, ref);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07003072 if (to_ref != ref) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07003073 auto* addr = reinterpret_cast<Atomic<mirror::CompressedReference<mirror::Object>>*>(root);
3074 auto expected_ref = mirror::CompressedReference<mirror::Object>::FromMirrorPtr(ref);
3075 auto new_ref = mirror::CompressedReference<mirror::Object>::FromMirrorPtr(to_ref);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07003076 // If the cas fails, then it was updated by the mutator.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07003077 do {
Orion Hodson88591fe2018-03-06 13:35:43 +00003078 if (ref != addr->load(std::memory_order_relaxed).AsMirrorPtr()) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07003079 // It was updated by the mutator.
3080 break;
3081 }
Orion Hodson4557b382018-01-03 11:47:54 +00003082 } while (!addr->CompareAndSetWeakRelaxed(expected_ref, new_ref));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07003083 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003084}
3085
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07003086inline void ConcurrentCopying::VisitRoots(
Mathieu Chartierda7c6502015-07-23 16:01:26 -07003087 mirror::CompressedReference<mirror::Object>** roots, size_t count,
3088 const RootInfo& info ATTRIBUTE_UNUSED) {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08003089 Thread* const self = Thread::Current();
Mathieu Chartierda7c6502015-07-23 16:01:26 -07003090 for (size_t i = 0; i < count; ++i) {
3091 mirror::CompressedReference<mirror::Object>* const root = roots[i];
3092 if (!root->IsNull()) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07003093 // kGrayImmuneObject is true because this is used for the thread flip.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07003094 MarkRoot</*kGrayImmuneObject=*/true>(self, root);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07003095 }
3096 }
3097}
3098
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07003099// Temporary set gc_grays_immune_objects_ to true in a scope if the current thread is GC.
3100class ConcurrentCopying::ScopedGcGraysImmuneObjects {
3101 public:
3102 explicit ScopedGcGraysImmuneObjects(ConcurrentCopying* collector)
3103 : collector_(collector), enabled_(false) {
3104 if (kUseBakerReadBarrier &&
3105 collector_->thread_running_gc_ == Thread::Current() &&
3106 !collector_->gc_grays_immune_objects_) {
3107 collector_->gc_grays_immune_objects_ = true;
3108 enabled_ = true;
3109 }
3110 }
3111
3112 ~ScopedGcGraysImmuneObjects() {
3113 if (kUseBakerReadBarrier &&
3114 collector_->thread_running_gc_ == Thread::Current() &&
3115 enabled_) {
3116 DCHECK(collector_->gc_grays_immune_objects_);
3117 collector_->gc_grays_immune_objects_ = false;
3118 }
3119 }
3120
3121 private:
3122 ConcurrentCopying* const collector_;
3123 bool enabled_;
3124};
3125
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003126// Fill the given memory block with a dummy object. Used to fill in a
3127// copy of objects that was lost in race.
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08003128void ConcurrentCopying::FillWithDummyObject(Thread* const self,
3129 mirror::Object* dummy_obj,
3130 size_t byte_size) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07003131 // GC doesn't gray immune objects while scanning immune objects. But we need to trigger the read
3132 // barriers here because we need the updated reference to the int array class, etc. Temporary set
3133 // gc_grays_immune_objects_ to true so that we won't cause a DCHECK failure in MarkImmuneSpace().
3134 ScopedGcGraysImmuneObjects scoped_gc_gray_immune_objects(this);
Roland Levillain14d90572015-07-16 10:52:26 +01003135 CHECK_ALIGNED(byte_size, kObjectAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003136 memset(dummy_obj, 0, byte_size);
Mathieu Chartierd6636d32016-07-28 11:02:38 -07003137 // Avoid going through read barrier for since kDisallowReadBarrierDuringScan may be enabled.
3138 // Explicitly mark to make sure to get an object in the to-space.
3139 mirror::Class* int_array_class = down_cast<mirror::Class*>(
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08003140 Mark(self, GetClassRoot<mirror::IntArray, kWithoutReadBarrier>().Ptr()));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003141 CHECK(int_array_class != nullptr);
Andreas Gampe6c578712017-10-19 13:00:34 -07003142 if (ReadBarrier::kEnableToSpaceInvariantChecks) {
3143 AssertToSpaceInvariant(nullptr, MemberOffset(0), int_array_class);
3144 }
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07003145 size_t component_size = int_array_class->GetComponentSize<kWithoutReadBarrier>();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003146 CHECK_EQ(component_size, sizeof(int32_t));
3147 size_t data_offset = mirror::Array::DataOffset(component_size).SizeValue();
3148 if (data_offset > byte_size) {
3149 // An int array is too big. Use java.lang.Object.
Mathieu Chartier9aef9922017-04-23 13:53:50 -07003150 CHECK(java_lang_Object_ != nullptr);
Andreas Gampe6c578712017-10-19 13:00:34 -07003151 if (ReadBarrier::kEnableToSpaceInvariantChecks) {
3152 AssertToSpaceInvariant(nullptr, MemberOffset(0), java_lang_Object_);
3153 }
Vladimir Marko98db89c2018-09-07 11:45:46 +01003154 CHECK_EQ(byte_size, java_lang_Object_->GetObjectSize<kVerifyNone>());
Mathieu Chartier3ed8ec12017-04-20 19:28:54 -07003155 dummy_obj->SetClass(java_lang_Object_);
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07003156 CHECK_EQ(byte_size, (dummy_obj->SizeOf<kVerifyNone>()));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003157 } else {
3158 // Use an int array.
3159 dummy_obj->SetClass(int_array_class);
Vladimir Marko98db89c2018-09-07 11:45:46 +01003160 CHECK(dummy_obj->IsArrayInstance<kVerifyNone>());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003161 int32_t length = (byte_size - data_offset) / component_size;
Vladimir Marko98db89c2018-09-07 11:45:46 +01003162 mirror::Array* dummy_arr = dummy_obj->AsArray<kVerifyNone>();
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07003163 dummy_arr->SetLength(length);
3164 CHECK_EQ(dummy_arr->GetLength(), length)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003165 << "byte_size=" << byte_size << " length=" << length
3166 << " component_size=" << component_size << " data_offset=" << data_offset;
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07003167 CHECK_EQ(byte_size, (dummy_obj->SizeOf<kVerifyNone>()))
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003168 << "byte_size=" << byte_size << " length=" << length
3169 << " component_size=" << component_size << " data_offset=" << data_offset;
3170 }
3171}
3172
3173// Reuse the memory blocks that were copy of objects that were lost in race.
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08003174mirror::Object* ConcurrentCopying::AllocateInSkippedBlock(Thread* const self, size_t alloc_size) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003175 // Try to reuse the blocks that were unused due to CAS failures.
Roland Levillain14d90572015-07-16 10:52:26 +01003176 CHECK_ALIGNED(alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003177 size_t min_object_size = RoundUp(sizeof(mirror::Object), space::RegionSpace::kAlignment);
Mathieu Chartierd6636d32016-07-28 11:02:38 -07003178 size_t byte_size;
3179 uint8_t* addr;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003180 {
Mathieu Chartierd6636d32016-07-28 11:02:38 -07003181 MutexLock mu(self, skipped_blocks_lock_);
3182 auto it = skipped_blocks_map_.lower_bound(alloc_size);
3183 if (it == skipped_blocks_map_.end()) {
3184 // Not found.
3185 return nullptr;
3186 }
3187 byte_size = it->first;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003188 CHECK_GE(byte_size, alloc_size);
3189 if (byte_size > alloc_size && byte_size - alloc_size < min_object_size) {
3190 // If remainder would be too small for a dummy object, retry with a larger request size.
3191 it = skipped_blocks_map_.lower_bound(alloc_size + min_object_size);
3192 if (it == skipped_blocks_map_.end()) {
3193 // Not found.
3194 return nullptr;
3195 }
Roland Levillain14d90572015-07-16 10:52:26 +01003196 CHECK_ALIGNED(it->first - alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003197 CHECK_GE(it->first - alloc_size, min_object_size)
3198 << "byte_size=" << byte_size << " it->first=" << it->first << " alloc_size=" << alloc_size;
3199 }
Mathieu Chartierd6636d32016-07-28 11:02:38 -07003200 // Found a block.
3201 CHECK(it != skipped_blocks_map_.end());
3202 byte_size = it->first;
3203 addr = it->second;
3204 CHECK_GE(byte_size, alloc_size);
3205 CHECK(region_space_->IsInToSpace(reinterpret_cast<mirror::Object*>(addr)));
3206 CHECK_ALIGNED(byte_size, space::RegionSpace::kAlignment);
3207 if (kVerboseMode) {
3208 LOG(INFO) << "Reusing skipped bytes : " << reinterpret_cast<void*>(addr) << ", " << byte_size;
3209 }
3210 skipped_blocks_map_.erase(it);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003211 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003212 memset(addr, 0, byte_size);
3213 if (byte_size > alloc_size) {
3214 // Return the remainder to the map.
Roland Levillain14d90572015-07-16 10:52:26 +01003215 CHECK_ALIGNED(byte_size - alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003216 CHECK_GE(byte_size - alloc_size, min_object_size);
Mathieu Chartierd6636d32016-07-28 11:02:38 -07003217 // FillWithDummyObject may mark an object, avoid holding skipped_blocks_lock_ to prevent lock
3218 // violation and possible deadlock. The deadlock case is a recursive case:
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003219 // FillWithDummyObject -> Mark(IntArray.class) -> Copy -> AllocateInSkippedBlock.
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08003220 FillWithDummyObject(self,
3221 reinterpret_cast<mirror::Object*>(addr + alloc_size),
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003222 byte_size - alloc_size);
3223 CHECK(region_space_->IsInToSpace(reinterpret_cast<mirror::Object*>(addr + alloc_size)));
Mathieu Chartierd6636d32016-07-28 11:02:38 -07003224 {
3225 MutexLock mu(self, skipped_blocks_lock_);
3226 skipped_blocks_map_.insert(std::make_pair(byte_size - alloc_size, addr + alloc_size));
3227 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003228 }
3229 return reinterpret_cast<mirror::Object*>(addr);
3230}
3231
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08003232mirror::Object* ConcurrentCopying::Copy(Thread* const self,
3233 mirror::Object* from_ref,
Mathieu Chartieref496d92017-04-28 18:58:59 -07003234 mirror::Object* holder,
3235 MemberOffset offset) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003236 DCHECK(region_space_->IsInFromSpace(from_ref));
Mathieu Chartieref496d92017-04-28 18:58:59 -07003237 // If the class pointer is null, the object is invalid. This could occur for a dangling pointer
3238 // from a previous GC that is either inside or outside the allocated region.
3239 mirror::Class* klass = from_ref->GetClass<kVerifyNone, kWithoutReadBarrier>();
3240 if (UNLIKELY(klass == nullptr)) {
Roland Levillainca3dded2018-08-10 15:35:17 +01003241 // Remove memory protection from the region space and log debugging information.
3242 region_space_->Unprotect();
Andreas Gampe98ea9d92018-10-19 14:06:15 -07003243 heap_->GetVerification()->LogHeapCorruption(holder, offset, from_ref, /* fatal= */ true);
Mathieu Chartieref496d92017-04-28 18:58:59 -07003244 }
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07003245 // There must not be a read barrier to avoid nested RB that might violate the to-space invariant.
3246 // Note that from_ref is a from space ref so the SizeOf() call will access the from-space meta
3247 // objects, but it's ok and necessary.
3248 size_t obj_size = from_ref->SizeOf<kDefaultVerifyFlags>();
Nicolas Geoffray4b361a82017-07-06 15:30:10 +01003249 size_t region_space_alloc_size = (obj_size <= space::RegionSpace::kRegionSize)
3250 ? RoundUp(obj_size, space::RegionSpace::kAlignment)
3251 : RoundUp(obj_size, space::RegionSpace::kRegionSize);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003252 size_t region_space_bytes_allocated = 0U;
3253 size_t non_moving_space_bytes_allocated = 0U;
3254 size_t bytes_allocated = 0U;
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07003255 size_t dummy;
Lokesh Gidraf2a69312018-03-27 18:48:59 -07003256 bool fall_back_to_non_moving = false;
Andreas Gampe98ea9d92018-10-19 14:06:15 -07003257 mirror::Object* to_ref = region_space_->AllocNonvirtual</*kForEvac=*/ true>(
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07003258 region_space_alloc_size, &region_space_bytes_allocated, nullptr, &dummy);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003259 bytes_allocated = region_space_bytes_allocated;
Lokesh Gidraf2a69312018-03-27 18:48:59 -07003260 if (LIKELY(to_ref != nullptr)) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003261 DCHECK_EQ(region_space_alloc_size, region_space_bytes_allocated);
Lokesh Gidraf2a69312018-03-27 18:48:59 -07003262 } else {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003263 // Failed to allocate in the region space. Try the skipped blocks.
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08003264 to_ref = AllocateInSkippedBlock(self, region_space_alloc_size);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003265 if (to_ref != nullptr) {
3266 // Succeeded to allocate in a skipped block.
3267 if (heap_->use_tlab_) {
3268 // This is necessary for the tlab case as it's not accounted in the space.
3269 region_space_->RecordAlloc(to_ref);
3270 }
3271 bytes_allocated = region_space_alloc_size;
Hans Boehmfb8b4e22018-09-05 16:45:42 -07003272 heap_->num_bytes_allocated_.fetch_sub(bytes_allocated, std::memory_order_relaxed);
3273 to_space_bytes_skipped_.fetch_sub(bytes_allocated, std::memory_order_relaxed);
3274 to_space_objects_skipped_.fetch_sub(1, std::memory_order_relaxed);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003275 } else {
3276 // Fall back to the non-moving space.
3277 fall_back_to_non_moving = true;
3278 if (kVerboseMode) {
3279 LOG(INFO) << "Out of memory in the to-space. Fall back to non-moving. skipped_bytes="
Hans Boehmfb8b4e22018-09-05 16:45:42 -07003280 << to_space_bytes_skipped_.load(std::memory_order_relaxed)
Orion Hodson88591fe2018-03-06 13:35:43 +00003281 << " skipped_objects="
Hans Boehmfb8b4e22018-09-05 16:45:42 -07003282 << to_space_objects_skipped_.load(std::memory_order_relaxed);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003283 }
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08003284 to_ref = heap_->non_moving_space_->Alloc(self, obj_size,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07003285 &non_moving_space_bytes_allocated, nullptr, &dummy);
Mathieu Chartierb01335c2017-03-22 13:15:01 -07003286 if (UNLIKELY(to_ref == nullptr)) {
3287 LOG(FATAL_WITHOUT_ABORT) << "Fall-back non-moving space allocation failed for a "
3288 << obj_size << " byte object in region type "
3289 << region_space_->GetRegionType(from_ref);
3290 LOG(FATAL) << "Object address=" << from_ref << " type=" << from_ref->PrettyTypeOf();
3291 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003292 bytes_allocated = non_moving_space_bytes_allocated;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003293 }
3294 }
3295 DCHECK(to_ref != nullptr);
3296
Mathieu Chartierd818adb2016-09-15 13:12:47 -07003297 // Copy the object excluding the lock word since that is handled in the loop.
Mathieu Chartieref496d92017-04-28 18:58:59 -07003298 to_ref->SetClass(klass);
Mathieu Chartierd818adb2016-09-15 13:12:47 -07003299 const size_t kObjectHeaderSize = sizeof(mirror::Object);
3300 DCHECK_GE(obj_size, kObjectHeaderSize);
3301 static_assert(kObjectHeaderSize == sizeof(mirror::HeapReference<mirror::Class>) +
3302 sizeof(LockWord),
3303 "Object header size does not match");
3304 // Memcpy can tear for words since it may do byte copy. It is only safe to do this since the
3305 // object in the from space is immutable other than the lock word. b/31423258
3306 memcpy(reinterpret_cast<uint8_t*>(to_ref) + kObjectHeaderSize,
3307 reinterpret_cast<const uint8_t*>(from_ref) + kObjectHeaderSize,
3308 obj_size - kObjectHeaderSize);
3309
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003310 // Attempt to install the forward pointer. This is in a loop as the
3311 // lock word atomic write can fail.
3312 while (true) {
Mathieu Chartierd818adb2016-09-15 13:12:47 -07003313 LockWord old_lock_word = from_ref->GetLockWord(false);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003314
3315 if (old_lock_word.GetState() == LockWord::kForwardingAddress) {
3316 // Lost the race. Another thread (either GC or mutator) stored
3317 // the forwarding pointer first. Make the lost copy (to_ref)
3318 // look like a valid but dead (dummy) object and keep it for
3319 // future reuse.
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08003320 FillWithDummyObject(self, to_ref, bytes_allocated);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003321 if (!fall_back_to_non_moving) {
3322 DCHECK(region_space_->IsInToSpace(to_ref));
3323 if (bytes_allocated > space::RegionSpace::kRegionSize) {
3324 // Free the large alloc.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07003325 region_space_->FreeLarge</*kForEvac=*/ true>(to_ref, bytes_allocated);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003326 } else {
3327 // Record the lost copy for later reuse.
Hans Boehmfb8b4e22018-09-05 16:45:42 -07003328 heap_->num_bytes_allocated_.fetch_add(bytes_allocated, std::memory_order_relaxed);
3329 to_space_bytes_skipped_.fetch_add(bytes_allocated, std::memory_order_relaxed);
3330 to_space_objects_skipped_.fetch_add(1, std::memory_order_relaxed);
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08003331 MutexLock mu(self, skipped_blocks_lock_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003332 skipped_blocks_map_.insert(std::make_pair(bytes_allocated,
3333 reinterpret_cast<uint8_t*>(to_ref)));
3334 }
3335 } else {
3336 DCHECK(heap_->non_moving_space_->HasAddress(to_ref));
3337 DCHECK_EQ(bytes_allocated, non_moving_space_bytes_allocated);
3338 // Free the non-moving-space chunk.
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08003339 heap_->non_moving_space_->Free(self, to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003340 }
3341
3342 // Get the winner's forward ptr.
3343 mirror::Object* lost_fwd_ptr = to_ref;
3344 to_ref = reinterpret_cast<mirror::Object*>(old_lock_word.ForwardingAddress());
3345 CHECK(to_ref != nullptr);
3346 CHECK_NE(to_ref, lost_fwd_ptr);
Mathieu Chartierdfcd6f42016-09-13 10:02:48 -07003347 CHECK(region_space_->IsInToSpace(to_ref) || heap_->non_moving_space_->HasAddress(to_ref))
3348 << "to_ref=" << to_ref << " " << heap_->DumpSpaces();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003349 CHECK_NE(to_ref->GetLockWord(false).GetState(), LockWord::kForwardingAddress);
3350 return to_ref;
3351 }
3352
Mathieu Chartierd818adb2016-09-15 13:12:47 -07003353 // Copy the old lock word over since we did not copy it yet.
3354 to_ref->SetLockWord(old_lock_word, false);
Hiroshi Yamauchi60f63f52015-04-23 16:12:40 -07003355 // Set the gray ptr.
3356 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07003357 to_ref->SetReadBarrierState(ReadBarrier::GrayState());
Hiroshi Yamauchi60f63f52015-04-23 16:12:40 -07003358 }
3359
Mathieu Chartiera8131262016-11-29 17:55:19 -08003360 // Do a fence to prevent the field CAS in ConcurrentCopying::Process from possibly reordering
3361 // before the object copy.
Orion Hodson27b96762018-03-13 16:06:57 +00003362 std::atomic_thread_fence(std::memory_order_release);
Mathieu Chartiera8131262016-11-29 17:55:19 -08003363
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003364 LockWord new_lock_word = LockWord::FromForwardingAddress(reinterpret_cast<size_t>(to_ref));
3365
3366 // Try to atomically write the fwd ptr.
Mathieu Chartier42c2e502018-06-19 12:30:56 -07003367 bool success = from_ref->CasLockWord(old_lock_word,
3368 new_lock_word,
3369 CASMode::kWeak,
3370 std::memory_order_relaxed);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003371 if (LIKELY(success)) {
3372 // The CAS succeeded.
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08003373 DCHECK(thread_running_gc_ != nullptr);
3374 if (LIKELY(self == thread_running_gc_)) {
3375 objects_moved_gc_thread_ += 1;
3376 bytes_moved_gc_thread_ += region_space_alloc_size;
3377 } else {
3378 objects_moved_.fetch_add(1, std::memory_order_relaxed);
3379 bytes_moved_.fetch_add(region_space_alloc_size, std::memory_order_relaxed);
3380 }
3381
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003382 if (LIKELY(!fall_back_to_non_moving)) {
3383 DCHECK(region_space_->IsInToSpace(to_ref));
3384 } else {
3385 DCHECK(heap_->non_moving_space_->HasAddress(to_ref));
3386 DCHECK_EQ(bytes_allocated, non_moving_space_bytes_allocated);
Lokesh Gidra519c1c72018-11-09 17:10:47 -08003387 if (!kEnableGenerationalConcurrentCopyingCollection || !young_gen_) {
3388 // Mark it in the live bitmap.
3389 CHECK(!heap_->non_moving_space_->GetLiveBitmap()->AtomicTestAndSet(to_ref));
3390 }
3391 if (!kUseBakerReadBarrier) {
3392 // Mark it in the mark bitmap.
3393 CHECK(!heap_->non_moving_space_->GetMarkBitmap()->AtomicTestAndSet(to_ref));
3394 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003395 }
3396 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07003397 DCHECK(to_ref->GetReadBarrierState() == ReadBarrier::GrayState());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003398 }
3399 DCHECK(GetFwdPtr(from_ref) == to_ref);
3400 CHECK_NE(to_ref->GetLockWord(false).GetState(), LockWord::kForwardingAddress);
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08003401 PushOntoMarkStack(self, to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003402 return to_ref;
3403 } else {
3404 // The CAS failed. It may have lost the race or may have failed
3405 // due to monitor/hashcode ops. Either way, retry.
3406 }
3407 }
3408}
3409
3410mirror::Object* ConcurrentCopying::IsMarked(mirror::Object* from_ref) {
3411 DCHECK(from_ref != nullptr);
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08003412 space::RegionSpace::RegionType rtype = region_space_->GetRegionType(from_ref);
3413 if (rtype == space::RegionSpace::RegionType::kRegionTypeToSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003414 // It's already marked.
3415 return from_ref;
3416 }
3417 mirror::Object* to_ref;
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08003418 if (rtype == space::RegionSpace::RegionType::kRegionTypeFromSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003419 to_ref = GetFwdPtr(from_ref);
3420 DCHECK(to_ref == nullptr || region_space_->IsInToSpace(to_ref) ||
3421 heap_->non_moving_space_->HasAddress(to_ref))
3422 << "from_ref=" << from_ref << " to_ref=" << to_ref;
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08003423 } else if (rtype == space::RegionSpace::RegionType::kRegionTypeUnevacFromSpace) {
Mathieu Chartierc381c362016-08-23 13:27:53 -07003424 if (IsMarkedInUnevacFromSpace(from_ref)) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003425 to_ref = from_ref;
3426 } else {
3427 to_ref = nullptr;
3428 }
3429 } else {
Roland Levillain001eff92018-01-24 14:24:33 +00003430 // At this point, `from_ref` should not be in the region space
3431 // (i.e. within an "unused" region).
3432 DCHECK(!region_space_->HasAddress(from_ref)) << from_ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003433 // from_ref is in a non-moving space.
Mathieu Chartier763a31e2015-11-16 16:05:55 -08003434 if (immune_spaces_.ContainsObject(from_ref)) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07003435 // An immune object is alive.
3436 to_ref = from_ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003437 } else {
3438 // Non-immune non-moving space. Use the mark bitmap.
Lokesh Gidra519c1c72018-11-09 17:10:47 -08003439 if (IsMarkedInNonMovingSpace(from_ref)) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003440 // Already marked.
3441 to_ref = from_ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003442 } else {
Lokesh Gidra519c1c72018-11-09 17:10:47 -08003443 to_ref = nullptr;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003444 }
3445 }
3446 }
3447 return to_ref;
3448}
3449
3450bool ConcurrentCopying::IsOnAllocStack(mirror::Object* ref) {
Hans Boehmcc55e1d2017-07-27 15:28:07 -07003451 // TODO: Explain why this is here. What release operation does it pair with?
Orion Hodson27b96762018-03-13 16:06:57 +00003452 std::atomic_thread_fence(std::memory_order_acquire);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003453 accounting::ObjectStack* alloc_stack = GetAllocationStack();
Mathieu Chartiercb535da2015-01-23 13:50:03 -08003454 return alloc_stack->Contains(ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003455}
3456
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08003457mirror::Object* ConcurrentCopying::MarkNonMoving(Thread* const self,
3458 mirror::Object* ref,
Mathieu Chartier1ca68902017-04-18 11:26:22 -07003459 mirror::Object* holder,
3460 MemberOffset offset) {
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07003461 // ref is in a non-moving space (from_ref == to_ref).
3462 DCHECK(!region_space_->HasAddress(ref)) << ref;
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07003463 DCHECK(!immune_spaces_.ContainsObject(ref));
3464 // Use the mark bitmap.
Lokesh Gidra519c1c72018-11-09 17:10:47 -08003465 accounting::ContinuousSpaceBitmap* mark_bitmap = heap_->GetNonMovingSpace()->GetMarkBitmap();
3466 accounting::LargeObjectBitmap* los_bitmap = nullptr;
3467 const bool is_los = !mark_bitmap->HasAddress(ref);
3468 if (is_los) {
3469 if (!IsAligned<kPageSize>(ref)) {
3470 // Ref is a large object that is not aligned, it must be heap
3471 // corruption. Remove memory protection and dump data before
3472 // AtomicSetReadBarrierState since it will fault if the address is not
3473 // valid.
3474 region_space_->Unprotect();
3475 heap_->GetVerification()->LogHeapCorruption(holder, offset, ref, /* fatal= */ true);
3476 }
3477 DCHECK(heap_->GetLargeObjectsSpace())
3478 << "ref=" << ref
3479 << " doesn't belong to non-moving space and large object space doesn't exist";
3480 los_bitmap = heap_->GetLargeObjectsSpace()->GetMarkBitmap();
3481 DCHECK(los_bitmap->HasAddress(ref));
3482 }
Lokesh Gidra2a9824c2018-11-07 15:57:17 -08003483 if (kEnableGenerationalConcurrentCopyingCollection) {
Roland Levillainade74a62018-08-08 15:55:42 +01003484 // The sticky-bit CC collector is only compatible with Baker-style read barriers.
3485 DCHECK(kUseBakerReadBarrier);
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07003486 // Not done scanning, use AtomicSetReadBarrierPointer.
Roland Levillain2d94e292018-08-15 16:46:30 +01003487 if (!done_scanning_.load(std::memory_order_acquire)) {
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07003488 // Since the mark bitmap is still filled in from last GC, we can not use that or else the
Roland Levillainade74a62018-08-08 15:55:42 +01003489 // mutator may see references to the from space. Instead, use the Baker pointer itself as
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07003490 // the mark bit.
Lokesh Gidra16d82a22018-10-10 22:40:02 -07003491 //
3492 // We need to avoid marking objects that are on allocation stack as that will lead to a
3493 // situation (after this GC cycle is finished) where some object(s) are on both allocation
3494 // stack and live bitmap. This leads to visiting the same object(s) twice during a heapdump
3495 // (b/117426281).
3496 if (!IsOnAllocStack(ref) &&
3497 ref->AtomicSetReadBarrierState(ReadBarrier::NonGrayState(), ReadBarrier::GrayState())) {
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07003498 // TODO: We don't actually need to scan this object later, we just need to clear the gray
3499 // bit.
Lokesh Gidra16d82a22018-10-10 22:40:02 -07003500 // We don't need to mark newly allocated objects (those in allocation stack) as they can
3501 // only point to to-space objects. Also, they are considered live till the next GC cycle.
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07003502 PushOntoMarkStack(self, ref);
3503 }
3504 return ref;
3505 }
3506 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07003507 if (!is_los && mark_bitmap->Test(ref)) {
3508 // Already marked.
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07003509 } else if (is_los && los_bitmap->Test(ref)) {
3510 // Already marked in LOS.
Lokesh Gidra519c1c72018-11-09 17:10:47 -08003511 } else if (IsOnAllocStack(ref)) {
3512 // If it's on the allocation stack, it's considered marked. Keep it white (non-gray).
3513 // Objects on the allocation stack need not be marked.
3514 if (!is_los) {
3515 DCHECK(!mark_bitmap->Test(ref));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003516 } else {
Lokesh Gidra519c1c72018-11-09 17:10:47 -08003517 DCHECK(!los_bitmap->Test(ref));
3518 }
3519 if (kUseBakerReadBarrier) {
3520 DCHECK_EQ(ref->GetReadBarrierState(), ReadBarrier::NonGrayState());
3521 }
3522 } else {
3523 // Not marked nor on the allocation stack. Try to mark it.
3524 // This may or may not succeed, which is ok.
3525 bool success = false;
3526 if (kUseBakerReadBarrier) {
3527 success = ref->AtomicSetReadBarrierState(ReadBarrier::NonGrayState(),
3528 ReadBarrier::GrayState());
3529 } else {
3530 success = is_los ?
3531 !los_bitmap->AtomicTestAndSet(ref) :
3532 !mark_bitmap->AtomicTestAndSet(ref);
3533 }
3534 if (success) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07003535 if (kUseBakerReadBarrier) {
Lokesh Gidra519c1c72018-11-09 17:10:47 -08003536 DCHECK_EQ(ref->GetReadBarrierState(), ReadBarrier::GrayState());
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07003537 }
Lokesh Gidra519c1c72018-11-09 17:10:47 -08003538 PushOntoMarkStack(self, ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003539 }
3540 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07003541 return ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003542}
3543
3544void ConcurrentCopying::FinishPhase() {
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -08003545 Thread* const self = Thread::Current();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07003546 {
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -08003547 MutexLock mu(self, mark_stack_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07003548 CHECK_EQ(pooled_mark_stacks_.size(), kMarkStackPoolSize);
3549 }
Mathieu Chartiera1467d02017-02-22 09:22:50 -08003550 // kVerifyNoMissingCardMarks relies on the region space cards not being cleared to avoid false
3551 // positives.
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07003552 if (!kEnableGenerationalConcurrentCopyingCollection && !kVerifyNoMissingCardMarks) {
Mathieu Chartier6e6078a2016-10-24 15:45:41 -07003553 TimingLogger::ScopedTiming split("ClearRegionSpaceCards", GetTimings());
3554 // We do not currently use the region space cards at all, madvise them away to save ram.
3555 heap_->GetCardTable()->ClearCardRange(region_space_->Begin(), region_space_->Limit());
Lokesh Gidrad0c5b252018-12-05 01:10:40 -08003556 } else if (kEnableGenerationalConcurrentCopyingCollection && !young_gen_) {
Lokesh Gidra1c34b712018-12-18 13:41:58 -08003557 region_space_inter_region_bitmap_->Clear();
3558 non_moving_space_inter_region_bitmap_->Clear();
Mathieu Chartier6e6078a2016-10-24 15:45:41 -07003559 }
3560 {
3561 MutexLock mu(self, skipped_blocks_lock_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003562 skipped_blocks_map_.clear();
3563 }
Mathieu Chartier56fe2582016-07-14 13:30:03 -07003564 {
3565 ReaderMutexLock mu(self, *Locks::mutator_lock_);
Mathieu Chartier21328a12016-07-22 10:47:45 -07003566 {
3567 WriterMutexLock mu2(self, *Locks::heap_bitmap_lock_);
3568 heap_->ClearMarkedObjects();
3569 }
3570 if (kUseBakerReadBarrier && kFilterModUnionCards) {
3571 TimingLogger::ScopedTiming split("FilterModUnionCards", GetTimings());
3572 ReaderMutexLock mu2(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier21328a12016-07-22 10:47:45 -07003573 for (space::ContinuousSpace* space : immune_spaces_.GetSpaces()) {
3574 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
Mathieu Chartier6e6078a2016-10-24 15:45:41 -07003575 accounting::ModUnionTable* table = heap_->FindModUnionTableFromSpace(space);
Mathieu Chartier21328a12016-07-22 10:47:45 -07003576 // Filter out cards that don't need to be set.
3577 if (table != nullptr) {
3578 table->FilterCards();
3579 }
3580 }
3581 }
Mathieu Chartier36a270a2016-07-28 18:08:51 -07003582 if (kUseBakerReadBarrier) {
3583 TimingLogger::ScopedTiming split("EmptyRBMarkBitStack", GetTimings());
Mathieu Chartier6e6078a2016-10-24 15:45:41 -07003584 DCHECK(rb_mark_bit_stack_ != nullptr);
Mathieu Chartier36a270a2016-07-28 18:08:51 -07003585 const auto* limit = rb_mark_bit_stack_->End();
3586 for (StackReference<mirror::Object>* it = rb_mark_bit_stack_->Begin(); it != limit; ++it) {
Roland Levillain001eff92018-01-24 14:24:33 +00003587 CHECK(it->AsMirrorPtr()->AtomicSetMarkBit(1, 0))
3588 << "rb_mark_bit_stack_->Begin()" << rb_mark_bit_stack_->Begin() << '\n'
3589 << "rb_mark_bit_stack_->End()" << rb_mark_bit_stack_->End() << '\n'
3590 << "rb_mark_bit_stack_->IsFull()"
3591 << std::boolalpha << rb_mark_bit_stack_->IsFull() << std::noboolalpha << '\n'
3592 << DumpReferenceInfo(it->AsMirrorPtr(), "*it");
Mathieu Chartier36a270a2016-07-28 18:08:51 -07003593 }
3594 rb_mark_bit_stack_->Reset();
3595 }
Mathieu Chartier56fe2582016-07-14 13:30:03 -07003596 }
3597 if (measure_read_barrier_slow_path_) {
3598 MutexLock mu(self, rb_slow_path_histogram_lock_);
Orion Hodson88591fe2018-03-06 13:35:43 +00003599 rb_slow_path_time_histogram_.AdjustAndAddValue(
3600 rb_slow_path_ns_.load(std::memory_order_relaxed));
3601 rb_slow_path_count_total_ += rb_slow_path_count_.load(std::memory_order_relaxed);
3602 rb_slow_path_count_gc_total_ += rb_slow_path_count_gc_.load(std::memory_order_relaxed);
Mathieu Chartier56fe2582016-07-14 13:30:03 -07003603 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003604}
3605
Hiroshi Yamauchi65f5f242016-12-19 11:44:47 -08003606bool ConcurrentCopying::IsNullOrMarkedHeapReference(mirror::HeapReference<mirror::Object>* field,
3607 bool do_atomic_update) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003608 mirror::Object* from_ref = field->AsMirrorPtr();
Hiroshi Yamauchi65f5f242016-12-19 11:44:47 -08003609 if (from_ref == nullptr) {
3610 return true;
3611 }
Mathieu Chartier97509952015-07-13 14:35:43 -07003612 mirror::Object* to_ref = IsMarked(from_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003613 if (to_ref == nullptr) {
3614 return false;
3615 }
3616 if (from_ref != to_ref) {
Hiroshi Yamauchi65f5f242016-12-19 11:44:47 -08003617 if (do_atomic_update) {
3618 do {
3619 if (field->AsMirrorPtr() != from_ref) {
3620 // Concurrently overwritten by a mutator.
3621 break;
3622 }
3623 } while (!field->CasWeakRelaxed(from_ref, to_ref));
3624 } else {
Hans Boehmcc55e1d2017-07-27 15:28:07 -07003625 // TODO: Why is this seq_cst when the above is relaxed? Document memory ordering.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07003626 field->Assign</* kIsVolatile= */ true>(to_ref);
Hiroshi Yamauchi65f5f242016-12-19 11:44:47 -08003627 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003628 }
3629 return true;
3630}
3631
Mathieu Chartier97509952015-07-13 14:35:43 -07003632mirror::Object* ConcurrentCopying::MarkObject(mirror::Object* from_ref) {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08003633 return Mark(Thread::Current(), from_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003634}
3635
Mathieu Chartier31e88222016-10-14 18:43:19 -07003636void ConcurrentCopying::DelayReferenceReferent(ObjPtr<mirror::Class> klass,
3637 ObjPtr<mirror::Reference> reference) {
Mathieu Chartier97509952015-07-13 14:35:43 -07003638 heap_->GetReferenceProcessor()->DelayReferenceReferent(klass, reference, this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003639}
3640
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07003641void ConcurrentCopying::ProcessReferences(Thread* self) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003642 TimingLogger::ScopedTiming split("ProcessReferences", GetTimings());
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07003643 // We don't really need to lock the heap bitmap lock as we use CAS to mark in bitmaps.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003644 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
3645 GetHeap()->GetReferenceProcessor()->ProcessReferences(
Andreas Gampe98ea9d92018-10-19 14:06:15 -07003646 /*concurrent=*/ true, GetTimings(), GetCurrentIteration()->GetClearSoftReferences(), this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003647}
3648
3649void ConcurrentCopying::RevokeAllThreadLocalBuffers() {
3650 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
3651 region_space_->RevokeAllThreadLocalBuffers();
3652}
3653
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08003654mirror::Object* ConcurrentCopying::MarkFromReadBarrierWithMeasurements(Thread* const self,
3655 mirror::Object* from_ref) {
3656 if (self != thread_running_gc_) {
Orion Hodson88591fe2018-03-06 13:35:43 +00003657 rb_slow_path_count_.fetch_add(1u, std::memory_order_relaxed);
Mathieu Chartier56fe2582016-07-14 13:30:03 -07003658 } else {
Orion Hodson88591fe2018-03-06 13:35:43 +00003659 rb_slow_path_count_gc_.fetch_add(1u, std::memory_order_relaxed);
Mathieu Chartier56fe2582016-07-14 13:30:03 -07003660 }
3661 ScopedTrace tr(__FUNCTION__);
3662 const uint64_t start_time = measure_read_barrier_slow_path_ ? NanoTime() : 0u;
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07003663 mirror::Object* ret =
Andreas Gampe98ea9d92018-10-19 14:06:15 -07003664 Mark</*kGrayImmuneObject=*/true, /*kNoUnEvac=*/false, /*kFromGCThread=*/false>(self,
3665 from_ref);
Mathieu Chartier56fe2582016-07-14 13:30:03 -07003666 if (measure_read_barrier_slow_path_) {
Orion Hodson88591fe2018-03-06 13:35:43 +00003667 rb_slow_path_ns_.fetch_add(NanoTime() - start_time, std::memory_order_relaxed);
Mathieu Chartier56fe2582016-07-14 13:30:03 -07003668 }
3669 return ret;
3670}
3671
3672void ConcurrentCopying::DumpPerformanceInfo(std::ostream& os) {
3673 GarbageCollector::DumpPerformanceInfo(os);
Albert Mingkun Yangaf9cce12018-11-07 09:58:35 +00003674 size_t num_gc_cycles = GetCumulativeTimings().GetIterations();
Mathieu Chartier56fe2582016-07-14 13:30:03 -07003675 MutexLock mu(Thread::Current(), rb_slow_path_histogram_lock_);
3676 if (rb_slow_path_time_histogram_.SampleSize() > 0) {
3677 Histogram<uint64_t>::CumulativeData cumulative_data;
3678 rb_slow_path_time_histogram_.CreateHistogram(&cumulative_data);
3679 rb_slow_path_time_histogram_.PrintConfidenceIntervals(os, 0.99, cumulative_data);
3680 }
3681 if (rb_slow_path_count_total_ > 0) {
3682 os << "Slow path count " << rb_slow_path_count_total_ << "\n";
3683 }
3684 if (rb_slow_path_count_gc_total_ > 0) {
3685 os << "GC slow path count " << rb_slow_path_count_gc_total_ << "\n";
3686 }
Albert Mingkun Yange260e542018-11-05 13:45:59 +00003687
Albert Mingkun Yangaf9cce12018-11-07 09:58:35 +00003688 os << "Average " << (young_gen_ ? "minor" : "major") << " GC reclaim bytes ratio "
3689 << (reclaimed_bytes_ratio_sum_ / num_gc_cycles) << " over " << num_gc_cycles
3690 << " GC cycles\n";
3691
3692 os << "Average " << (young_gen_ ? "minor" : "major") << " GC copied live bytes ratio "
3693 << (copied_live_bytes_ratio_sum_ / gc_count_) << " over " << gc_count_
3694 << " " << (young_gen_ ? "minor" : "major") << " GCs\n";
3695
Orion Hodson88591fe2018-03-06 13:35:43 +00003696 os << "Cumulative bytes moved "
3697 << cumulative_bytes_moved_.load(std::memory_order_relaxed) << "\n";
3698 os << "Cumulative objects moved "
3699 << cumulative_objects_moved_.load(std::memory_order_relaxed) << "\n";
Lokesh Gidra29895822017-12-15 15:37:40 -08003700
3701 os << "Peak regions allocated "
Lokesh Gidrab4f15412018-01-05 18:29:34 -08003702 << region_space_->GetMaxPeakNumNonFreeRegions() << " ("
3703 << PrettySize(region_space_->GetMaxPeakNumNonFreeRegions() * space::RegionSpace::kRegionSize)
3704 << ") / " << region_space_->GetNumRegions() / 2 << " ("
3705 << PrettySize(region_space_->GetNumRegions() * space::RegionSpace::kRegionSize / 2)
Lokesh Gidra29895822017-12-15 15:37:40 -08003706 << ")\n";
Mathieu Chartier56fe2582016-07-14 13:30:03 -07003707}
3708
Hiroshi Yamauchid5307ec2014-03-27 21:07:51 -07003709} // namespace collector
3710} // namespace gc
3711} // namespace art