blob: a9ba54a4ff772205d51582fb013b4bb028c8018a [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),
Mathieu Chartier8d1a9962016-08-17 16:39:45 -070096 young_gen_(young_gen),
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080097 skipped_blocks_lock_("concurrent copying bytes blocks lock", kMarkSweepMarkStackLock),
Mathieu Chartier56fe2582016-07-14 13:30:03 -070098 measure_read_barrier_slow_path_(measure_read_barrier_slow_path),
Andreas Gamped9911ee2017-03-27 13:27:24 -070099 mark_from_read_barrier_measurements_(false),
Mathieu Chartier56fe2582016-07-14 13:30:03 -0700100 rb_slow_path_ns_(0),
101 rb_slow_path_count_(0),
102 rb_slow_path_count_gc_(0),
103 rb_slow_path_histogram_lock_("Read barrier histogram lock"),
104 rb_slow_path_time_histogram_("Mutator time in read barrier slow path", 500, 32),
105 rb_slow_path_count_total_(0),
106 rb_slow_path_count_gc_total_(0),
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800107 rb_table_(heap_->GetReadBarrierTable()),
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700108 force_evacuate_all_(false),
Andreas Gamped9911ee2017-03-27 13:27:24 -0700109 gc_grays_immune_objects_(false),
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700110 immune_gray_stack_lock_("concurrent copying immune gray stack lock",
111 kMarkSweepMarkStackLock) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800112 static_assert(space::RegionSpace::kRegionSize == accounting::ReadBarrierTable::kRegionSize,
113 "The region space size and the read barrier table region size must match");
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700114 CHECK(kEnableGenerationalConcurrentCopyingCollection || !young_gen_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700115 Thread* self = Thread::Current();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800116 {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800117 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
118 // Cache this so that we won't have to lock heap_bitmap_lock_ in
119 // Mark() which could cause a nested lock on heap_bitmap_lock_
120 // when GC causes a RB while doing GC or a lock order violation
121 // (class_linker_lock_ and heap_bitmap_lock_).
122 heap_mark_bitmap_ = heap->GetMarkBitmap();
123 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700124 {
125 MutexLock mu(self, mark_stack_lock_);
126 for (size_t i = 0; i < kMarkStackPoolSize; ++i) {
127 accounting::AtomicStack<mirror::Object>* mark_stack =
128 accounting::AtomicStack<mirror::Object>::Create(
129 "thread local mark stack", kMarkStackSize, kMarkStackSize);
130 pooled_mark_stacks_.push_back(mark_stack);
131 }
132 }
Roland Levillainb1e1dc32018-07-10 19:19:31 +0100133 if (kEnableGenerationalConcurrentCopyingCollection) {
134 // Allocate sweep array free buffer.
135 std::string error_msg;
136 sweep_array_free_buffer_mem_map_ = MemMap::MapAnonymous(
137 "concurrent copying sweep array free buffer",
138 /* addr */ nullptr,
139 RoundUp(kSweepArrayChunkFreeSize * sizeof(mirror::Object*), kPageSize),
140 PROT_READ | PROT_WRITE,
141 /* low_4gb */ false,
142 /* reuse */ false,
143 &error_msg);
144 CHECK(sweep_array_free_buffer_mem_map_.IsValid())
145 << "Couldn't allocate sweep array free buffer: " << error_msg;
146 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800147}
148
Hiroshi Yamauchi057d9772017-02-17 15:33:23 -0800149void ConcurrentCopying::MarkHeapReference(mirror::HeapReference<mirror::Object>* field,
150 bool do_atomic_update) {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -0800151 Thread* const self = Thread::Current();
Hiroshi Yamauchi057d9772017-02-17 15:33:23 -0800152 if (UNLIKELY(do_atomic_update)) {
153 // Used to mark the referent in DelayReferenceReferent in transaction mode.
154 mirror::Object* from_ref = field->AsMirrorPtr();
155 if (from_ref == nullptr) {
156 return;
157 }
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -0800158 mirror::Object* to_ref = Mark(self, from_ref);
Hiroshi Yamauchi057d9772017-02-17 15:33:23 -0800159 if (from_ref != to_ref) {
160 do {
161 if (field->AsMirrorPtr() != from_ref) {
162 // Concurrently overwritten by a mutator.
163 break;
164 }
165 } while (!field->CasWeakRelaxed(from_ref, to_ref));
166 }
167 } else {
168 // Used for preserving soft references, should be OK to not have a CAS here since there should be
169 // no other threads which can trigger read barriers on the same referent during reference
170 // processing.
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -0800171 field->Assign(Mark(self, field->AsMirrorPtr()));
Hiroshi Yamauchi057d9772017-02-17 15:33:23 -0800172 }
Mathieu Chartier97509952015-07-13 14:35:43 -0700173}
174
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800175ConcurrentCopying::~ConcurrentCopying() {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700176 STLDeleteElements(&pooled_mark_stacks_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800177}
178
179void ConcurrentCopying::RunPhases() {
180 CHECK(kUseBakerReadBarrier || kUseTableLookupReadBarrier);
181 CHECK(!is_active_);
182 is_active_ = true;
183 Thread* self = Thread::Current();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700184 thread_running_gc_ = self;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800185 Locks::mutator_lock_->AssertNotHeld(self);
186 {
187 ReaderMutexLock mu(self, *Locks::mutator_lock_);
188 InitializePhase();
189 }
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700190 if (kUseBakerReadBarrier && kGrayDirtyImmuneObjects) {
191 // Switch to read barrier mark entrypoints before we gray the objects. This is required in case
Roland Levillain97c46462017-05-11 14:04:03 +0100192 // a mutator sees a gray bit and dispatches on the entrypoint. (b/37876887).
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700193 ActivateReadBarrierEntrypoints();
194 // Gray dirty immune objects concurrently to reduce GC pause times. We re-process gray cards in
195 // the pause.
196 ReaderMutexLock mu(self, *Locks::mutator_lock_);
197 GrayAllDirtyImmuneObjects();
198 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800199 FlipThreadRoots();
200 {
201 ReaderMutexLock mu(self, *Locks::mutator_lock_);
202 MarkingPhase();
203 }
204 // Verify no from space refs. This causes a pause.
Andreas Gampee3ce7872017-02-22 13:36:21 -0800205 if (kEnableNoFromSpaceRefsVerification) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800206 TimingLogger::ScopedTiming split("(Paused)VerifyNoFromSpaceReferences", GetTimings());
Andreas Gampe4934eb12017-01-30 13:15:26 -0800207 ScopedPause pause(this, false);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700208 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800209 if (kVerboseMode) {
210 LOG(INFO) << "Verifying no from-space refs";
211 }
212 VerifyNoFromSpaceReferences();
Mathieu Chartier720e71a2015-04-06 17:10:58 -0700213 if (kVerboseMode) {
214 LOG(INFO) << "Done verifying no from-space refs";
215 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700216 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800217 }
218 {
219 ReaderMutexLock mu(self, *Locks::mutator_lock_);
220 ReclaimPhase();
221 }
222 FinishPhase();
223 CHECK(is_active_);
224 is_active_ = false;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700225 thread_running_gc_ = nullptr;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800226}
227
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700228class ConcurrentCopying::ActivateReadBarrierEntrypointsCheckpoint : public Closure {
229 public:
230 explicit ActivateReadBarrierEntrypointsCheckpoint(ConcurrentCopying* concurrent_copying)
231 : concurrent_copying_(concurrent_copying) {}
232
233 void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
234 // Note: self is not necessarily equal to thread since thread may be suspended.
235 Thread* self = Thread::Current();
236 DCHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
237 << thread->GetState() << " thread " << thread << " self " << self;
238 // Switch to the read barrier entrypoints.
239 thread->SetReadBarrierEntrypoints();
240 // If thread is a running mutator, then act on behalf of the garbage collector.
241 // See the code in ThreadList::RunCheckpoint.
242 concurrent_copying_->GetBarrier().Pass(self);
243 }
244
245 private:
246 ConcurrentCopying* const concurrent_copying_;
247};
248
249class ConcurrentCopying::ActivateReadBarrierEntrypointsCallback : public Closure {
250 public:
251 explicit ActivateReadBarrierEntrypointsCallback(ConcurrentCopying* concurrent_copying)
252 : concurrent_copying_(concurrent_copying) {}
253
254 void Run(Thread* self ATTRIBUTE_UNUSED) OVERRIDE REQUIRES(Locks::thread_list_lock_) {
255 // This needs to run under the thread_list_lock_ critical section in ThreadList::RunCheckpoint()
256 // to avoid a race with ThreadList::Register().
257 CHECK(!concurrent_copying_->is_using_read_barrier_entrypoints_);
258 concurrent_copying_->is_using_read_barrier_entrypoints_ = true;
259 }
260
261 private:
262 ConcurrentCopying* const concurrent_copying_;
263};
264
265void ConcurrentCopying::ActivateReadBarrierEntrypoints() {
266 Thread* const self = Thread::Current();
267 ActivateReadBarrierEntrypointsCheckpoint checkpoint(this);
268 ThreadList* thread_list = Runtime::Current()->GetThreadList();
269 gc_barrier_->Init(self, 0);
270 ActivateReadBarrierEntrypointsCallback callback(this);
271 const size_t barrier_count = thread_list->RunCheckpoint(&checkpoint, &callback);
272 // If there are no threads to wait which implies that all the checkpoint functions are finished,
273 // then no need to release the mutator lock.
274 if (barrier_count == 0) {
275 return;
276 }
277 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
278 gc_barrier_->Increment(self, barrier_count);
279}
280
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800281void ConcurrentCopying::BindBitmaps() {
282 Thread* self = Thread::Current();
283 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
284 // Mark all of the spaces we never collect as immune.
285 for (const auto& space : heap_->GetContinuousSpaces()) {
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800286 if (space->GetGcRetentionPolicy() == space::kGcRetentionPolicyNeverCollect ||
287 space->GetGcRetentionPolicy() == space::kGcRetentionPolicyFullCollect) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800288 CHECK(space->IsZygoteSpace() || space->IsImageSpace());
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800289 immune_spaces_.AddSpace(space);
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700290 } else {
291 CHECK(!space->IsZygoteSpace());
292 CHECK(!space->IsImageSpace());
293 if (kEnableGenerationalConcurrentCopyingCollection) {
294 if (space == region_space_) {
295 region_space_bitmap_ = region_space_->GetMarkBitmap();
296 } else if (young_gen_ && space->IsContinuousMemMapAllocSpace()) {
297 DCHECK_EQ(space->GetGcRetentionPolicy(), space::kGcRetentionPolicyAlwaysCollect);
298 space->AsContinuousMemMapAllocSpace()->BindLiveToMarkBitmap();
299 }
300 // Age all of the cards for the region space so that we know which evac regions to scan.
301 Runtime::Current()->GetHeap()->GetCardTable()->ModifyCardsAtomic(
302 space->Begin(),
303 space->End(),
304 AgeCardVisitor(),
305 VoidFunctor());
306 } else {
307 if (space == region_space_) {
308 // It is OK to clear the bitmap with mutators running since the only place it is read is
309 // VisitObjects which has exclusion with CC.
310 region_space_bitmap_ = region_space_->GetMarkBitmap();
311 region_space_bitmap_->Clear();
312 }
313 }
314 }
315 }
316 if (kEnableGenerationalConcurrentCopyingCollection && young_gen_) {
317 for (const auto& space : GetHeap()->GetDiscontinuousSpaces()) {
318 CHECK(space->IsLargeObjectSpace());
319 space->AsLargeObjectSpace()->CopyLiveToMarked();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800320 }
321 }
322}
323
324void ConcurrentCopying::InitializePhase() {
325 TimingLogger::ScopedTiming split("InitializePhase", GetTimings());
326 if (kVerboseMode) {
327 LOG(INFO) << "GC InitializePhase";
328 LOG(INFO) << "Region-space : " << reinterpret_cast<void*>(region_space_->Begin()) << "-"
329 << reinterpret_cast<void*>(region_space_->Limit());
330 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700331 CheckEmptyMarkStack();
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800332 if (kIsDebugBuild) {
333 MutexLock mu(Thread::Current(), mark_stack_lock_);
334 CHECK(false_gray_stack_.empty());
335 }
Mathieu Chartier56fe2582016-07-14 13:30:03 -0700336
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700337 rb_mark_bit_stack_full_ = false;
Mathieu Chartier56fe2582016-07-14 13:30:03 -0700338 mark_from_read_barrier_measurements_ = measure_read_barrier_slow_path_;
339 if (measure_read_barrier_slow_path_) {
Orion Hodson88591fe2018-03-06 13:35:43 +0000340 rb_slow_path_ns_.store(0, std::memory_order_relaxed);
341 rb_slow_path_count_.store(0, std::memory_order_relaxed);
342 rb_slow_path_count_gc_.store(0, std::memory_order_relaxed);
Mathieu Chartier56fe2582016-07-14 13:30:03 -0700343 }
344
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800345 immune_spaces_.Reset();
Orion Hodson88591fe2018-03-06 13:35:43 +0000346 bytes_moved_.store(0, std::memory_order_relaxed);
347 objects_moved_.store(0, std::memory_order_relaxed);
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -0800348 bytes_moved_gc_thread_ = 0;
349 objects_moved_gc_thread_ = 0;
Hiroshi Yamauchi60985b72016-08-24 13:53:12 -0700350 GcCause gc_cause = GetCurrentIteration()->GetGcCause();
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700351
352 force_evacuate_all_ = false;
353 if (!kEnableGenerationalConcurrentCopyingCollection || !young_gen_) {
354 if (gc_cause == kGcCauseExplicit ||
355 gc_cause == kGcCauseCollectorTransition ||
356 GetCurrentIteration()->GetClearSoftReferences()) {
357 force_evacuate_all_ = true;
358 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800359 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700360 if (kUseBakerReadBarrier) {
Orion Hodson88591fe2018-03-06 13:35:43 +0000361 updated_all_immune_objects_.store(false, std::memory_order_relaxed);
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700362 // GC may gray immune objects in the thread flip.
363 gc_grays_immune_objects_ = true;
364 if (kIsDebugBuild) {
365 MutexLock mu(Thread::Current(), immune_gray_stack_lock_);
366 DCHECK(immune_gray_stack_.empty());
367 }
368 }
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700369 if (kEnableGenerationalConcurrentCopyingCollection) {
370 done_scanning_.store(false, std::memory_order_relaxed);
371 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800372 BindBitmaps();
373 if (kVerboseMode) {
Roland Levillain57ce0542018-08-07 16:20:31 +0100374 LOG(INFO) << "young_gen=" << std::boolalpha << young_gen_ << std::noboolalpha;
375 LOG(INFO) << "force_evacuate_all=" << std::boolalpha << force_evacuate_all_ << std::noboolalpha;
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800376 LOG(INFO) << "Largest immune region: " << immune_spaces_.GetLargestImmuneRegion().Begin()
377 << "-" << immune_spaces_.GetLargestImmuneRegion().End();
378 for (space::ContinuousSpace* space : immune_spaces_.GetSpaces()) {
379 LOG(INFO) << "Immune space: " << *space;
380 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800381 LOG(INFO) << "GC end of InitializePhase";
382 }
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700383 if (kEnableGenerationalConcurrentCopyingCollection && !young_gen_) {
384 region_space_bitmap_->Clear();
385 }
Mathieu Chartier962cd7a2016-08-16 12:15:59 -0700386 // Mark all of the zygote large objects without graying them.
387 MarkZygoteLargeObjects();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800388}
389
390// Used to switch the thread roots of a thread from from-space refs to to-space refs.
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700391class ConcurrentCopying::ThreadFlipVisitor : public Closure, public RootVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800392 public:
Roland Levillain3887c462015-08-12 18:15:42 +0100393 ThreadFlipVisitor(ConcurrentCopying* concurrent_copying, bool use_tlab)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800394 : concurrent_copying_(concurrent_copying), use_tlab_(use_tlab) {
395 }
396
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700397 virtual void Run(Thread* thread) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800398 // Note: self is not necessarily equal to thread since thread may be suspended.
399 Thread* self = Thread::Current();
400 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
401 << thread->GetState() << " thread " << thread << " self " << self;
Mathieu Chartierfe814e82016-11-09 14:32:49 -0800402 thread->SetIsGcMarkingAndUpdateEntrypoints(true);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800403 if (use_tlab_ && thread->HasTlab()) {
404 if (ConcurrentCopying::kEnableFromSpaceAccountingCheck) {
405 // This must come before the revoke.
406 size_t thread_local_objects = thread->GetThreadLocalObjectsAllocated();
407 concurrent_copying_->region_space_->RevokeThreadLocalBuffers(thread);
Roland Levillain2ae376f2018-01-30 11:35:11 +0000408 reinterpret_cast<Atomic<size_t>*>(
409 &concurrent_copying_->from_space_num_objects_at_first_pause_)->
Orion Hodson88591fe2018-03-06 13:35:43 +0000410 fetch_add(thread_local_objects, std::memory_order_seq_cst);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800411 } else {
412 concurrent_copying_->region_space_->RevokeThreadLocalBuffers(thread);
413 }
414 }
415 if (kUseThreadLocalAllocationStack) {
416 thread->RevokeThreadLocalAllocationStack();
417 }
418 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700419 // We can use the non-CAS VisitRoots functions below because we update thread-local GC roots
420 // only.
Andreas Gampe513061a2017-06-01 09:17:34 -0700421 thread->VisitRoots(this, kVisitRootFlagAllRoots);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800422 concurrent_copying_->GetBarrier().Pass(self);
423 }
424
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700425 void VisitRoots(mirror::Object*** roots,
426 size_t count,
427 const RootInfo& info ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700428 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -0800429 Thread* self = Thread::Current();
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700430 for (size_t i = 0; i < count; ++i) {
431 mirror::Object** root = roots[i];
432 mirror::Object* ref = *root;
433 if (ref != nullptr) {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -0800434 mirror::Object* to_ref = concurrent_copying_->Mark(self, ref);
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700435 if (to_ref != ref) {
436 *root = to_ref;
437 }
438 }
439 }
440 }
441
442 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots,
443 size_t count,
444 const RootInfo& info ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700445 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -0800446 Thread* self = Thread::Current();
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700447 for (size_t i = 0; i < count; ++i) {
448 mirror::CompressedReference<mirror::Object>* const root = roots[i];
449 if (!root->IsNull()) {
450 mirror::Object* ref = root->AsMirrorPtr();
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -0800451 mirror::Object* to_ref = concurrent_copying_->Mark(self, ref);
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700452 if (to_ref != ref) {
453 root->Assign(to_ref);
454 }
455 }
456 }
457 }
458
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800459 private:
460 ConcurrentCopying* const concurrent_copying_;
461 const bool use_tlab_;
462};
463
464// Called back from Runtime::FlipThreadRoots() during a pause.
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700465class ConcurrentCopying::FlipCallback : public Closure {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800466 public:
467 explicit FlipCallback(ConcurrentCopying* concurrent_copying)
468 : concurrent_copying_(concurrent_copying) {
469 }
470
Mathieu Chartier90443472015-07-16 20:32:27 -0700471 virtual void Run(Thread* thread) OVERRIDE REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800472 ConcurrentCopying* cc = concurrent_copying_;
473 TimingLogger::ScopedTiming split("(Paused)FlipCallback", cc->GetTimings());
474 // Note: self is not necessarily equal to thread since thread may be suspended.
475 Thread* self = Thread::Current();
Mathieu Chartiera1467d02017-02-22 09:22:50 -0800476 if (kVerifyNoMissingCardMarks) {
477 cc->VerifyNoMissingCardMarks();
478 }
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700479 CHECK_EQ(thread, self);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800480 Locks::mutator_lock_->AssertExclusiveHeld(self);
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700481 space::RegionSpace::EvacMode evac_mode = space::RegionSpace::kEvacModeLivePercentNewlyAllocated;
482 if (cc->young_gen_) {
483 CHECK(!cc->force_evacuate_all_);
484 evac_mode = space::RegionSpace::kEvacModeNewlyAllocated;
485 } else if (cc->force_evacuate_all_) {
486 evac_mode = space::RegionSpace::kEvacModeForceAll;
487 }
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700488 {
489 TimingLogger::ScopedTiming split2("(Paused)SetFromSpace", cc->GetTimings());
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700490 // Only change live bytes for full CC.
491 cc->region_space_->SetFromSpace(
492 cc->rb_table_, evac_mode, /*clear_live_bytes*/ !cc->young_gen_);
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700493 }
Mathieu Chartiera4f6af92015-08-11 17:35:25 -0700494 cc->SwapStacks();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800495 if (ConcurrentCopying::kEnableFromSpaceAccountingCheck) {
496 cc->RecordLiveStackFreezeSize(self);
497 cc->from_space_num_objects_at_first_pause_ = cc->region_space_->GetObjectsAllocated();
498 cc->from_space_num_bytes_at_first_pause_ = cc->region_space_->GetBytesAllocated();
499 }
500 cc->is_marking_ = true;
Orion Hodson88591fe2018-03-06 13:35:43 +0000501 cc->mark_stack_mode_.store(ConcurrentCopying::kMarkStackModeThreadLocal,
502 std::memory_order_relaxed);
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700503 if (kIsDebugBuild && !cc->young_gen_) {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800504 cc->region_space_->AssertAllRegionLiveBytesZeroOrCleared();
505 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800506 if (UNLIKELY(Runtime::Current()->IsActiveTransaction())) {
Mathieu Chartier184c9dc2015-03-05 13:20:54 -0800507 CHECK(Runtime::Current()->IsAotCompiler());
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700508 TimingLogger::ScopedTiming split3("(Paused)VisitTransactionRoots", cc->GetTimings());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700509 Runtime::Current()->VisitTransactionRoots(cc);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800510 }
Mathieu Chartier21328a12016-07-22 10:47:45 -0700511 if (kUseBakerReadBarrier && kGrayDirtyImmuneObjects) {
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700512 cc->GrayAllNewlyDirtyImmuneObjects();
Mathieu Chartier21328a12016-07-22 10:47:45 -0700513 if (kIsDebugBuild) {
Roland Levillain001eff92018-01-24 14:24:33 +0000514 // Check that all non-gray immune objects only reference immune objects.
Mathieu Chartier21328a12016-07-22 10:47:45 -0700515 cc->VerifyGrayImmuneObjects();
516 }
517 }
Mathieu Chartier9aef9922017-04-23 13:53:50 -0700518 // May be null during runtime creation, in this case leave java_lang_Object null.
519 // This is safe since single threaded behavior should mean FillDummyObject does not
520 // happen when java_lang_Object_ is null.
521 if (WellKnownClasses::java_lang_Object != nullptr) {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -0800522 cc->java_lang_Object_ = down_cast<mirror::Class*>(cc->Mark(thread,
Mathieu Chartier9aef9922017-04-23 13:53:50 -0700523 WellKnownClasses::ToClass(WellKnownClasses::java_lang_Object).Ptr()));
524 } else {
525 cc->java_lang_Object_ = nullptr;
526 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800527 }
528
529 private:
530 ConcurrentCopying* const concurrent_copying_;
531};
532
Mathieu Chartier21328a12016-07-22 10:47:45 -0700533class ConcurrentCopying::VerifyGrayImmuneObjectsVisitor {
534 public:
535 explicit VerifyGrayImmuneObjectsVisitor(ConcurrentCopying* collector)
536 : collector_(collector) {}
537
Mathieu Chartier31e88222016-10-14 18:43:19 -0700538 void operator()(ObjPtr<mirror::Object> obj, MemberOffset offset, bool /* is_static */)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700539 const ALWAYS_INLINE REQUIRES_SHARED(Locks::mutator_lock_)
540 REQUIRES_SHARED(Locks::heap_bitmap_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700541 CheckReference(obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(offset),
542 obj, offset);
543 }
544
Mathieu Chartier31e88222016-10-14 18:43:19 -0700545 void operator()(ObjPtr<mirror::Class> klass, ObjPtr<mirror::Reference> ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700546 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700547 CHECK(klass->IsTypeOfReferenceClass());
548 CheckReference(ref->GetReferent<kWithoutReadBarrier>(),
549 ref,
550 mirror::Reference::ReferentOffset());
551 }
552
553 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
554 ALWAYS_INLINE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700555 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700556 if (!root->IsNull()) {
557 VisitRoot(root);
558 }
559 }
560
561 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
562 ALWAYS_INLINE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700563 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700564 CheckReference(root->AsMirrorPtr(), nullptr, MemberOffset(0));
565 }
566
567 private:
568 ConcurrentCopying* const collector_;
569
Mathieu Chartier31e88222016-10-14 18:43:19 -0700570 void CheckReference(ObjPtr<mirror::Object> ref,
571 ObjPtr<mirror::Object> holder,
572 MemberOffset offset) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700573 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700574 if (ref != nullptr) {
Mathieu Chartier31e88222016-10-14 18:43:19 -0700575 if (!collector_->immune_spaces_.ContainsObject(ref.Ptr())) {
Mathieu Chartier962cd7a2016-08-16 12:15:59 -0700576 // Not immune, must be a zygote large object.
577 CHECK(Runtime::Current()->GetHeap()->GetLargeObjectsSpace()->IsZygoteLargeObject(
Mathieu Chartier31e88222016-10-14 18:43:19 -0700578 Thread::Current(), ref.Ptr()))
Mathieu Chartier962cd7a2016-08-16 12:15:59 -0700579 << "Non gray object references non immune, non zygote large object "<< ref << " "
David Sehr709b0702016-10-13 09:12:37 -0700580 << mirror::Object::PrettyTypeOf(ref) << " in holder " << holder << " "
581 << mirror::Object::PrettyTypeOf(holder) << " offset=" << offset.Uint32Value();
Mathieu Chartier962cd7a2016-08-16 12:15:59 -0700582 } else {
583 // Make sure the large object class is immune since we will never scan the large object.
584 CHECK(collector_->immune_spaces_.ContainsObject(
585 ref->GetClass<kVerifyNone, kWithoutReadBarrier>()));
586 }
Mathieu Chartier21328a12016-07-22 10:47:45 -0700587 }
588 }
589};
590
591void ConcurrentCopying::VerifyGrayImmuneObjects() {
592 TimingLogger::ScopedTiming split(__FUNCTION__, GetTimings());
593 for (auto& space : immune_spaces_.GetSpaces()) {
594 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
595 accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
596 VerifyGrayImmuneObjectsVisitor visitor(this);
597 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()),
598 reinterpret_cast<uintptr_t>(space->Limit()),
599 [&visitor](mirror::Object* obj)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700600 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700601 // If an object is not gray, it should only have references to things in the immune spaces.
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700602 if (obj->GetReadBarrierState() != ReadBarrier::GrayState()) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700603 obj->VisitReferences</*kVisitNativeRoots*/true,
604 kDefaultVerifyFlags,
605 kWithoutReadBarrier>(visitor, visitor);
606 }
607 });
608 }
609}
610
Mathieu Chartiera1467d02017-02-22 09:22:50 -0800611class ConcurrentCopying::VerifyNoMissingCardMarkVisitor {
612 public:
613 VerifyNoMissingCardMarkVisitor(ConcurrentCopying* cc, ObjPtr<mirror::Object> holder)
614 : cc_(cc),
615 holder_(holder) {}
616
617 void operator()(ObjPtr<mirror::Object> obj,
618 MemberOffset offset,
619 bool is_static ATTRIBUTE_UNUSED) const
620 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
621 if (offset.Uint32Value() != mirror::Object::ClassOffset().Uint32Value()) {
622 CheckReference(obj->GetFieldObject<mirror::Object, kDefaultVerifyFlags, kWithoutReadBarrier>(
623 offset), offset.Uint32Value());
624 }
625 }
626 void operator()(ObjPtr<mirror::Class> klass,
627 ObjPtr<mirror::Reference> ref) const
628 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
629 CHECK(klass->IsTypeOfReferenceClass());
630 this->operator()(ref, mirror::Reference::ReferentOffset(), false);
631 }
632
633 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
634 REQUIRES_SHARED(Locks::mutator_lock_) {
635 if (!root->IsNull()) {
636 VisitRoot(root);
637 }
638 }
639
640 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
641 REQUIRES_SHARED(Locks::mutator_lock_) {
642 CheckReference(root->AsMirrorPtr());
643 }
644
645 void CheckReference(mirror::Object* ref, int32_t offset = -1) const
646 REQUIRES_SHARED(Locks::mutator_lock_) {
647 CHECK(ref == nullptr || !cc_->region_space_->IsInNewlyAllocatedRegion(ref))
648 << holder_->PrettyTypeOf() << "(" << holder_.Ptr() << ") references object "
649 << ref->PrettyTypeOf() << "(" << ref << ") in newly allocated region at offset=" << offset;
650 }
651
652 private:
653 ConcurrentCopying* const cc_;
654 ObjPtr<mirror::Object> const holder_;
655};
656
Mathieu Chartiera1467d02017-02-22 09:22:50 -0800657void ConcurrentCopying::VerifyNoMissingCardMarks() {
Andreas Gampe0c183382017-07-13 22:26:24 -0700658 auto visitor = [&](mirror::Object* obj)
659 REQUIRES(Locks::mutator_lock_)
660 REQUIRES(!mark_stack_lock_) {
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700661 // Objects on clean cards should never have references to newly allocated regions. Note
662 // that aged cards are also not clean.
Andreas Gampe0c183382017-07-13 22:26:24 -0700663 if (heap_->GetCardTable()->GetCard(obj) == gc::accounting::CardTable::kCardClean) {
664 VerifyNoMissingCardMarkVisitor internal_visitor(this, /*holder*/ obj);
665 obj->VisitReferences</*kVisitNativeRoots*/true, kVerifyNone, kWithoutReadBarrier>(
666 internal_visitor, internal_visitor);
667 }
668 };
Mathieu Chartiera1467d02017-02-22 09:22:50 -0800669 TimingLogger::ScopedTiming split(__FUNCTION__, GetTimings());
Andreas Gampe0c183382017-07-13 22:26:24 -0700670 region_space_->Walk(visitor);
Mathieu Chartiera1467d02017-02-22 09:22:50 -0800671 {
672 ReaderMutexLock rmu(Thread::Current(), *Locks::heap_bitmap_lock_);
Andreas Gampe0c183382017-07-13 22:26:24 -0700673 heap_->GetLiveBitmap()->Visit(visitor);
Mathieu Chartiera1467d02017-02-22 09:22:50 -0800674 }
675}
676
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800677// Switch threads that from from-space to to-space refs. Forward/mark the thread roots.
678void ConcurrentCopying::FlipThreadRoots() {
679 TimingLogger::ScopedTiming split("FlipThreadRoots", GetTimings());
680 if (kVerboseMode) {
681 LOG(INFO) << "time=" << region_space_->Time();
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700682 region_space_->DumpNonFreeRegions(LOG_STREAM(INFO));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800683 }
684 Thread* self = Thread::Current();
685 Locks::mutator_lock_->AssertNotHeld(self);
686 gc_barrier_->Init(self, 0);
687 ThreadFlipVisitor thread_flip_visitor(this, heap_->use_tlab_);
688 FlipCallback flip_callback(this);
Andreas Gampe4934eb12017-01-30 13:15:26 -0800689
Andreas Gampe6e644452017-05-09 16:30:27 -0700690 size_t barrier_count = Runtime::Current()->GetThreadList()->FlipThreadRoots(
691 &thread_flip_visitor, &flip_callback, this, GetHeap()->GetGcPauseListener());
Andreas Gampe4934eb12017-01-30 13:15:26 -0800692
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800693 {
694 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
695 gc_barrier_->Increment(self, barrier_count);
696 }
697 is_asserting_to_space_invariant_ = true;
698 QuasiAtomic::ThreadFenceForConstructor();
699 if (kVerboseMode) {
700 LOG(INFO) << "time=" << region_space_->Time();
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700701 region_space_->DumpNonFreeRegions(LOG_STREAM(INFO));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800702 LOG(INFO) << "GC end of FlipThreadRoots";
703 }
704}
705
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700706template <bool kConcurrent>
Mathieu Chartier21328a12016-07-22 10:47:45 -0700707class ConcurrentCopying::GrayImmuneObjectVisitor {
708 public:
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700709 explicit GrayImmuneObjectVisitor(Thread* self) : self_(self) {}
Mathieu Chartier21328a12016-07-22 10:47:45 -0700710
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700711 ALWAYS_INLINE void operator()(mirror::Object* obj) const REQUIRES_SHARED(Locks::mutator_lock_) {
Roland Levillain14e5a292018-06-28 12:00:56 +0100712 if (kUseBakerReadBarrier && obj->GetReadBarrierState() == ReadBarrier::NonGrayState()) {
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700713 if (kConcurrent) {
714 Locks::mutator_lock_->AssertSharedHeld(self_);
Roland Levillain14e5a292018-06-28 12:00:56 +0100715 obj->AtomicSetReadBarrierState(ReadBarrier::NonGrayState(), ReadBarrier::GrayState());
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700716 // Mod union table VisitObjects may visit the same object multiple times so we can't check
717 // the result of the atomic set.
718 } else {
719 Locks::mutator_lock_->AssertExclusiveHeld(self_);
720 obj->SetReadBarrierState(ReadBarrier::GrayState());
Mathieu Chartier21328a12016-07-22 10:47:45 -0700721 }
Mathieu Chartier21328a12016-07-22 10:47:45 -0700722 }
723 }
724
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700725 static void Callback(mirror::Object* obj, void* arg) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700726 reinterpret_cast<GrayImmuneObjectVisitor<kConcurrent>*>(arg)->operator()(obj);
Mathieu Chartier21328a12016-07-22 10:47:45 -0700727 }
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700728
729 private:
730 Thread* const self_;
Mathieu Chartier21328a12016-07-22 10:47:45 -0700731};
732
733void ConcurrentCopying::GrayAllDirtyImmuneObjects() {
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700734 TimingLogger::ScopedTiming split("GrayAllDirtyImmuneObjects", GetTimings());
735 accounting::CardTable* const card_table = heap_->GetCardTable();
736 Thread* const self = Thread::Current();
737 using VisitorType = GrayImmuneObjectVisitor</* kIsConcurrent */ true>;
738 VisitorType visitor(self);
739 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier21328a12016-07-22 10:47:45 -0700740 for (space::ContinuousSpace* space : immune_spaces_.GetSpaces()) {
741 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700742 accounting::ModUnionTable* table = heap_->FindModUnionTableFromSpace(space);
Mathieu Chartier21328a12016-07-22 10:47:45 -0700743 // Mark all the objects on dirty cards since these may point to objects in other space.
744 // Once these are marked, the GC will eventually clear them later.
745 // Table is non null for boot image and zygote spaces. It is only null for application image
746 // spaces.
747 if (table != nullptr) {
Mathieu Chartier6e6078a2016-10-24 15:45:41 -0700748 table->ProcessCards();
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700749 table->VisitObjects(&VisitorType::Callback, &visitor);
750 // Don't clear cards here since we need to rescan in the pause. If we cleared the cards here,
751 // there would be races with the mutator marking new cards.
752 } else {
753 // Keep cards aged if we don't have a mod-union table since we may need to scan them in future
754 // GCs. This case is for app images.
755 card_table->ModifyCardsAtomic(
756 space->Begin(),
757 space->End(),
758 [](uint8_t card) {
759 return (card != gc::accounting::CardTable::kCardClean)
760 ? gc::accounting::CardTable::kCardAged
761 : card;
762 },
763 /* card modified visitor */ VoidFunctor());
764 card_table->Scan</* kClearCard */ false>(space->GetMarkBitmap(),
765 space->Begin(),
766 space->End(),
767 visitor,
768 gc::accounting::CardTable::kCardAged);
769 }
770 }
771}
772
773void ConcurrentCopying::GrayAllNewlyDirtyImmuneObjects() {
774 TimingLogger::ScopedTiming split("(Paused)GrayAllNewlyDirtyImmuneObjects", GetTimings());
775 accounting::CardTable* const card_table = heap_->GetCardTable();
776 using VisitorType = GrayImmuneObjectVisitor</* kIsConcurrent */ false>;
777 Thread* const self = Thread::Current();
778 VisitorType visitor(self);
779 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
780 for (space::ContinuousSpace* space : immune_spaces_.GetSpaces()) {
781 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
782 accounting::ModUnionTable* table = heap_->FindModUnionTableFromSpace(space);
783
784 // Don't need to scan aged cards since we did these before the pause. Note that scanning cards
785 // also handles the mod-union table cards.
786 card_table->Scan</* kClearCard */ false>(space->GetMarkBitmap(),
787 space->Begin(),
788 space->End(),
789 visitor,
790 gc::accounting::CardTable::kCardDirty);
791 if (table != nullptr) {
792 // Add the cards to the mod-union table so that we can clear cards to save RAM.
793 table->ProcessCards();
Mathieu Chartier6e6078a2016-10-24 15:45:41 -0700794 TimingLogger::ScopedTiming split2("(Paused)ClearCards", GetTimings());
795 card_table->ClearCardRange(space->Begin(),
796 AlignDown(space->End(), accounting::CardTable::kCardSize));
Mathieu Chartier21328a12016-07-22 10:47:45 -0700797 }
798 }
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700799 // 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 -0700800 // barriers in the immune spaces.
Orion Hodson88591fe2018-03-06 13:35:43 +0000801 updated_all_immune_objects_.store(true, std::memory_order_relaxed);
Mathieu Chartier21328a12016-07-22 10:47:45 -0700802}
803
Mathieu Chartiera4f6af92015-08-11 17:35:25 -0700804void ConcurrentCopying::SwapStacks() {
805 heap_->SwapStacks();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800806}
807
808void ConcurrentCopying::RecordLiveStackFreezeSize(Thread* self) {
809 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
810 live_stack_freeze_size_ = heap_->GetLiveStack()->Size();
811}
812
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700813// Used to visit objects in the immune spaces.
814inline void ConcurrentCopying::ScanImmuneObject(mirror::Object* obj) {
815 DCHECK(obj != nullptr);
816 DCHECK(immune_spaces_.ContainsObject(obj));
817 // Update the fields without graying it or pushing it onto the mark stack.
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700818 if (kEnableGenerationalConcurrentCopyingCollection && young_gen_) {
819 // Young GC does not care about references to unevac space. It is safe to not gray these as
820 // long as scan immune objects happens after scanning the dirty cards.
821 Scan<true>(obj);
822 } else {
823 Scan<false>(obj);
824 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700825}
826
827class ConcurrentCopying::ImmuneSpaceScanObjVisitor {
828 public:
829 explicit ImmuneSpaceScanObjVisitor(ConcurrentCopying* cc)
830 : collector_(cc) {}
831
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700832 ALWAYS_INLINE void operator()(mirror::Object* obj) const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700833 if (kUseBakerReadBarrier && kGrayDirtyImmuneObjects) {
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700834 // Only need to scan gray objects.
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700835 if (obj->GetReadBarrierState() == ReadBarrier::GrayState()) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700836 collector_->ScanImmuneObject(obj);
Roland Levillain14e5a292018-06-28 12:00:56 +0100837 // Done scanning the object, go back to black (non-gray).
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700838 bool success = obj->AtomicSetReadBarrierState(ReadBarrier::GrayState(),
Roland Levillain14e5a292018-06-28 12:00:56 +0100839 ReadBarrier::NonGrayState());
Mathieu Chartier2af7a3e2017-12-14 18:36:05 -0800840 CHECK(success)
841 << Runtime::Current()->GetHeap()->GetVerification()->DumpObjectInfo(obj, "failed CAS");
Mathieu Chartier21328a12016-07-22 10:47:45 -0700842 }
843 } else {
844 collector_->ScanImmuneObject(obj);
845 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700846 }
847
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700848 static void Callback(mirror::Object* obj, void* arg) REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi5408f232016-07-29 15:07:05 -0700849 reinterpret_cast<ImmuneSpaceScanObjVisitor*>(arg)->operator()(obj);
850 }
851
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700852 private:
853 ConcurrentCopying* const collector_;
854};
855
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800856// Concurrently mark roots that are guarded by read barriers and process the mark stack.
857void ConcurrentCopying::MarkingPhase() {
858 TimingLogger::ScopedTiming split("MarkingPhase", GetTimings());
859 if (kVerboseMode) {
860 LOG(INFO) << "GC MarkingPhase";
861 }
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -0700862 Thread* self = Thread::Current();
863 if (kIsDebugBuild) {
864 MutexLock mu(self, *Locks::thread_list_lock_);
865 CHECK(weak_ref_access_enabled_);
866 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700867
868 // Scan immune spaces.
869 // Update all the fields in the immune spaces first without graying the objects so that we
870 // minimize dirty pages in the immune spaces. Note mutators can concurrently access and gray some
871 // of the objects.
872 if (kUseBakerReadBarrier) {
873 gc_grays_immune_objects_ = false;
Hiroshi Yamauchi16292fc2016-06-20 20:23:34 -0700874 }
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700875 if (kEnableGenerationalConcurrentCopyingCollection && young_gen_) {
Roland Levillain57ce0542018-08-07 16:20:31 +0100876 if (kVerboseMode) {
877 LOG(INFO) << "GC ScanCardsForSpace";
878 }
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700879 TimingLogger::ScopedTiming split2("ScanCardsForSpace", GetTimings());
880 WriterMutexLock rmu(Thread::Current(), *Locks::heap_bitmap_lock_);
881 CHECK_EQ(done_scanning_.load(std::memory_order_relaxed), false);
882 if (kIsDebugBuild) {
883 // Leave some time for mutators to race ahead to try and find races between the GC card
884 // scanning and mutators reading references.
885 usleep(10 * 1000);
886 }
887 for (space::ContinuousSpace* space : GetHeap()->GetContinuousSpaces()) {
888 if (space->IsImageSpace() || space->IsZygoteSpace()) {
889 // Image and zygote spaces are already handled since we gray the objects in the pause.
890 continue;
891 }
892 // Scan all of the objects on dirty cards in unevac from space, and non moving space. These
893 // are from previous GCs and may reference things in the from space.
894 Runtime::Current()->GetHeap()->GetCardTable()->Scan<false>(
895 space->GetMarkBitmap(),
896 space->Begin(),
897 space->End(),
898 [this, space](mirror::Object* obj)
899 REQUIRES(Locks::heap_bitmap_lock_)
900 REQUIRES_SHARED(Locks::mutator_lock_) {
901 // Don't push or gray unevac refs.
902 if (kIsDebugBuild && space == region_space_) {
903 // We may get unevac large objects.
904 if (!region_space_->IsInUnevacFromSpace(obj)) {
905 CHECK(region_space_bitmap_->Test(obj));
906 region_space_->DumpRegionForObject(LOG_STREAM(FATAL_WITHOUT_ABORT), obj);
907 LOG(FATAL) << "Scanning " << obj << " not in unevac space";
908 }
909 }
910 Scan<true>(obj);
911 },
912 accounting::CardTable::kCardDirty - 1);
913 }
914 // Done scanning unevac space.
915 done_scanning_.store(true, std::memory_order_seq_cst);
Roland Levillain57ce0542018-08-07 16:20:31 +0100916 if (kVerboseMode) {
917 LOG(INFO) << "GC end of ScanCardsForSpace";
918 }
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700919 }
Mathieu Chartier21328a12016-07-22 10:47:45 -0700920 {
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700921 // For a sticky-bit collection, this phase needs to be after the card scanning since the
922 // mutator may read an unevac space object out of an image object. If the image object is no
923 // longer gray it will trigger a read barrier for the unevac space object.
Mathieu Chartier21328a12016-07-22 10:47:45 -0700924 TimingLogger::ScopedTiming split2("ScanImmuneSpaces", GetTimings());
925 for (auto& space : immune_spaces_.GetSpaces()) {
926 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
927 accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
Hiroshi Yamauchi5408f232016-07-29 15:07:05 -0700928 accounting::ModUnionTable* table = heap_->FindModUnionTableFromSpace(space);
Mathieu Chartier21328a12016-07-22 10:47:45 -0700929 ImmuneSpaceScanObjVisitor visitor(this);
Hiroshi Yamauchi5408f232016-07-29 15:07:05 -0700930 if (kUseBakerReadBarrier && kGrayDirtyImmuneObjects && table != nullptr) {
931 table->VisitObjects(ImmuneSpaceScanObjVisitor::Callback, &visitor);
932 } else {
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700933 // TODO: Scan only the aged cards.
Hiroshi Yamauchi5408f232016-07-29 15:07:05 -0700934 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()),
935 reinterpret_cast<uintptr_t>(space->Limit()),
936 visitor);
937 }
Mathieu Chartier21328a12016-07-22 10:47:45 -0700938 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700939 }
940 if (kUseBakerReadBarrier) {
941 // This release fence makes the field updates in the above loop visible before allowing mutator
942 // getting access to immune objects without graying it first.
Orion Hodson88591fe2018-03-06 13:35:43 +0000943 updated_all_immune_objects_.store(true, std::memory_order_release);
Roland Levillain14e5a292018-06-28 12:00:56 +0100944 // Now "un-gray" (conceptually blacken) immune objects concurrently accessed and grayed by
945 // mutators. We can't do this in the above loop because we would incorrectly disable the read
946 // barrier by un-graying (conceptually blackening) an object which may point to an unscanned,
947 // white object, breaking the to-space invariant (a mutator shall never observe a from-space
948 // (white) object).
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700949 //
Roland Levillain14e5a292018-06-28 12:00:56 +0100950 // Make sure no mutators are in the middle of marking an immune object before un-graying
951 // (blackening) immune objects.
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700952 IssueEmptyCheckpoint();
953 MutexLock mu(Thread::Current(), immune_gray_stack_lock_);
954 if (kVerboseMode) {
955 LOG(INFO) << "immune gray stack size=" << immune_gray_stack_.size();
956 }
957 for (mirror::Object* obj : immune_gray_stack_) {
Roland Levillain14e5a292018-06-28 12:00:56 +0100958 DCHECK_EQ(obj->GetReadBarrierState(), ReadBarrier::GrayState());
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700959 bool success = obj->AtomicSetReadBarrierState(ReadBarrier::GrayState(),
Roland Levillain14e5a292018-06-28 12:00:56 +0100960 ReadBarrier::NonGrayState());
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700961 DCHECK(success);
962 }
963 immune_gray_stack_.clear();
964 }
965
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800966 {
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -0700967 TimingLogger::ScopedTiming split2("VisitConcurrentRoots", GetTimings());
968 Runtime::Current()->VisitConcurrentRoots(this, kVisitRootFlagAllRoots);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800969 }
970 {
971 // TODO: don't visit the transaction roots if it's not active.
972 TimingLogger::ScopedTiming split5("VisitNonThreadRoots", GetTimings());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700973 Runtime::Current()->VisitNonThreadRoots(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800974 }
975
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800976 {
Mathieu Chartiera6b1ead2015-10-06 10:32:38 -0700977 TimingLogger::ScopedTiming split7("ProcessMarkStack", GetTimings());
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700978 // We transition through three mark stack modes (thread-local, shared, GC-exclusive). The
979 // primary reasons are the fact that we need to use a checkpoint to process thread-local mark
980 // stacks, but after we disable weak refs accesses, we can't use a checkpoint due to a deadlock
981 // issue because running threads potentially blocking at WaitHoldingLocks, and that once we
982 // reach the point where we process weak references, we can avoid using a lock when accessing
983 // the GC mark stack, which makes mark stack processing more efficient.
984
985 // Process the mark stack once in the thread local stack mode. This marks most of the live
986 // objects, aside from weak ref accesses with read barriers (Reference::GetReferent() and system
987 // weaks) that may happen concurrently while we processing the mark stack and newly mark/gray
988 // objects and push refs on the mark stack.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800989 ProcessMarkStack();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700990 // Switch to the shared mark stack mode. That is, revoke and process thread-local mark stacks
991 // for the last time before transitioning to the shared mark stack mode, which would process new
992 // refs that may have been concurrently pushed onto the mark stack during the ProcessMarkStack()
993 // call above. At the same time, disable weak ref accesses using a per-thread flag. It's
994 // important to do these together in a single checkpoint so that we can ensure that mutators
995 // won't newly gray objects and push new refs onto the mark stack due to weak ref accesses and
996 // mutators safely transition to the shared mark stack mode (without leaving unprocessed refs on
997 // the thread-local mark stacks), without a race. This is why we use a thread-local weak ref
998 // access flag Thread::tls32_.weak_ref_access_enabled_ instead of the global ones.
999 SwitchToSharedMarkStackMode();
1000 CHECK(!self->GetWeakRefAccessEnabled());
1001 // Now that weak refs accesses are disabled, once we exhaust the shared mark stack again here
1002 // (which may be non-empty if there were refs found on thread-local mark stacks during the above
1003 // SwitchToSharedMarkStackMode() call), we won't have new refs to process, that is, mutators
1004 // (via read barriers) have no way to produce any more refs to process. Marking converges once
1005 // before we process weak refs below.
1006 ProcessMarkStack();
1007 CheckEmptyMarkStack();
1008 // Switch to the GC exclusive mark stack mode so that we can process the mark stack without a
1009 // lock from this point on.
1010 SwitchToGcExclusiveMarkStackMode();
1011 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001012 if (kVerboseMode) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001013 LOG(INFO) << "ProcessReferences";
1014 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001015 // Process weak references. This may produce new refs to process and have them processed via
Mathieu Chartier97509952015-07-13 14:35:43 -07001016 // ProcessMarkStack (in the GC exclusive mark stack mode).
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001017 ProcessReferences(self);
1018 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001019 if (kVerboseMode) {
1020 LOG(INFO) << "SweepSystemWeaks";
1021 }
1022 SweepSystemWeaks(self);
1023 if (kVerboseMode) {
1024 LOG(INFO) << "SweepSystemWeaks done";
1025 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001026 // Process the mark stack here one last time because the above SweepSystemWeaks() call may have
1027 // marked some objects (strings alive) as hash_set::Erase() can call the hash function for
1028 // arbitrary elements in the weak intern table in InternTable::Table::SweepWeaks().
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001029 ProcessMarkStack();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001030 CheckEmptyMarkStack();
1031 // Re-enable weak ref accesses.
1032 ReenableWeakRefAccess(self);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07001033 // Free data for class loaders that we unloaded.
1034 Runtime::Current()->GetClassLinker()->CleanupClassLoaders();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001035 // Marking is done. Disable marking.
Hiroshi Yamauchi00370822015-08-18 14:47:25 -07001036 DisableMarking();
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001037 if (kUseBakerReadBarrier) {
1038 ProcessFalseGrayStack();
1039 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001040 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001041 }
1042
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001043 if (kIsDebugBuild) {
1044 MutexLock mu(self, *Locks::thread_list_lock_);
1045 CHECK(weak_ref_access_enabled_);
1046 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001047 if (kVerboseMode) {
1048 LOG(INFO) << "GC end of MarkingPhase";
1049 }
1050}
1051
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001052void ConcurrentCopying::ReenableWeakRefAccess(Thread* self) {
1053 if (kVerboseMode) {
1054 LOG(INFO) << "ReenableWeakRefAccess";
1055 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001056 // Iterate all threads (don't need to or can't use a checkpoint) and re-enable weak ref access.
1057 {
1058 MutexLock mu(self, *Locks::thread_list_lock_);
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001059 weak_ref_access_enabled_ = true; // This is for new threads.
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001060 std::list<Thread*> thread_list = Runtime::Current()->GetThreadList()->GetList();
1061 for (Thread* thread : thread_list) {
1062 thread->SetWeakRefAccessEnabled(true);
1063 }
1064 }
1065 // Unblock blocking threads.
1066 GetHeap()->GetReferenceProcessor()->BroadcastForSlowPath(self);
1067 Runtime::Current()->BroadcastForNewSystemWeaks();
1068}
1069
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001070class ConcurrentCopying::DisableMarkingCheckpoint : public Closure {
Hiroshi Yamauchi00370822015-08-18 14:47:25 -07001071 public:
1072 explicit DisableMarkingCheckpoint(ConcurrentCopying* concurrent_copying)
1073 : concurrent_copying_(concurrent_copying) {
1074 }
1075
1076 void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
1077 // Note: self is not necessarily equal to thread since thread may be suspended.
1078 Thread* self = Thread::Current();
1079 DCHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
1080 << thread->GetState() << " thread " << thread << " self " << self;
1081 // Disable the thread-local is_gc_marking flag.
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -07001082 // Note a thread that has just started right before this checkpoint may have already this flag
1083 // set to false, which is ok.
Mathieu Chartierfe814e82016-11-09 14:32:49 -08001084 thread->SetIsGcMarkingAndUpdateEntrypoints(false);
Hiroshi Yamauchi00370822015-08-18 14:47:25 -07001085 // If thread is a running mutator, then act on behalf of the garbage collector.
1086 // See the code in ThreadList::RunCheckpoint.
Mathieu Chartier10d25082015-10-28 18:36:09 -07001087 concurrent_copying_->GetBarrier().Pass(self);
Hiroshi Yamauchi00370822015-08-18 14:47:25 -07001088 }
1089
1090 private:
1091 ConcurrentCopying* const concurrent_copying_;
1092};
1093
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001094class ConcurrentCopying::DisableMarkingCallback : public Closure {
1095 public:
1096 explicit DisableMarkingCallback(ConcurrentCopying* concurrent_copying)
1097 : concurrent_copying_(concurrent_copying) {
1098 }
1099
1100 void Run(Thread* self ATTRIBUTE_UNUSED) OVERRIDE REQUIRES(Locks::thread_list_lock_) {
1101 // This needs to run under the thread_list_lock_ critical section in ThreadList::RunCheckpoint()
1102 // to avoid a race with ThreadList::Register().
1103 CHECK(concurrent_copying_->is_marking_);
1104 concurrent_copying_->is_marking_ = false;
Mathieu Chartiera9a4f5f2017-05-03 18:19:13 -07001105 if (kUseBakerReadBarrier && kGrayDirtyImmuneObjects) {
1106 CHECK(concurrent_copying_->is_using_read_barrier_entrypoints_);
1107 concurrent_copying_->is_using_read_barrier_entrypoints_ = false;
1108 } else {
1109 CHECK(!concurrent_copying_->is_using_read_barrier_entrypoints_);
1110 }
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001111 }
1112
1113 private:
1114 ConcurrentCopying* const concurrent_copying_;
1115};
1116
Hiroshi Yamauchi00370822015-08-18 14:47:25 -07001117void ConcurrentCopying::IssueDisableMarkingCheckpoint() {
1118 Thread* self = Thread::Current();
1119 DisableMarkingCheckpoint check_point(this);
1120 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1121 gc_barrier_->Init(self, 0);
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001122 DisableMarkingCallback dmc(this);
1123 size_t barrier_count = thread_list->RunCheckpoint(&check_point, &dmc);
Hiroshi Yamauchi00370822015-08-18 14:47:25 -07001124 // If there are no threads to wait which implies that all the checkpoint functions are finished,
1125 // then no need to release the mutator lock.
1126 if (barrier_count == 0) {
1127 return;
1128 }
1129 // Release locks then wait for all mutator threads to pass the barrier.
1130 Locks::mutator_lock_->SharedUnlock(self);
1131 {
1132 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
1133 gc_barrier_->Increment(self, barrier_count);
1134 }
1135 Locks::mutator_lock_->SharedLock(self);
1136}
1137
1138void ConcurrentCopying::DisableMarking() {
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001139 // Use a checkpoint to turn off the global is_marking and the thread-local is_gc_marking flags and
1140 // to ensure no threads are still in the middle of a read barrier which may have a from-space ref
1141 // cached in a local variable.
Hiroshi Yamauchi00370822015-08-18 14:47:25 -07001142 IssueDisableMarkingCheckpoint();
1143 if (kUseTableLookupReadBarrier) {
1144 heap_->rb_table_->ClearAll();
1145 DCHECK(heap_->rb_table_->IsAllCleared());
1146 }
Orion Hodson88591fe2018-03-06 13:35:43 +00001147 is_mark_stack_push_disallowed_.store(1, std::memory_order_seq_cst);
1148 mark_stack_mode_.store(kMarkStackModeOff, std::memory_order_seq_cst);
Hiroshi Yamauchi00370822015-08-18 14:47:25 -07001149}
1150
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08001151void ConcurrentCopying::PushOntoFalseGrayStack(Thread* const self, mirror::Object* ref) {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001152 CHECK(kUseBakerReadBarrier);
1153 DCHECK(ref != nullptr);
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08001154 MutexLock mu(self, mark_stack_lock_);
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001155 false_gray_stack_.push_back(ref);
1156}
1157
1158void ConcurrentCopying::ProcessFalseGrayStack() {
1159 CHECK(kUseBakerReadBarrier);
Roland Levillain14e5a292018-06-28 12:00:56 +01001160 // Change the objects on the false gray stack from gray to non-gray (conceptually black).
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001161 MutexLock mu(Thread::Current(), mark_stack_lock_);
1162 for (mirror::Object* obj : false_gray_stack_) {
1163 DCHECK(IsMarked(obj));
Roland Levillain14e5a292018-06-28 12:00:56 +01001164 // The object could be non-gray (conceptually black) here if a thread got preempted after a
1165 // success at the AtomicSetReadBarrierState in MarkNonMoving(), GC started marking through it
1166 // (but not finished so still gray), the thread ran to register it onto the false gray stack,
1167 // and then GC eventually marked it black (non-gray) after it finished scanning it.
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001168 if (obj->GetReadBarrierState() == ReadBarrier::GrayState()) {
1169 bool success = obj->AtomicSetReadBarrierState(ReadBarrier::GrayState(),
Roland Levillain14e5a292018-06-28 12:00:56 +01001170 ReadBarrier::NonGrayState());
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001171 DCHECK(success);
1172 }
1173 }
1174 false_gray_stack_.clear();
1175}
1176
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001177void ConcurrentCopying::IssueEmptyCheckpoint() {
1178 Thread* self = Thread::Current();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001179 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001180 // Release locks then wait for all mutator threads to pass the barrier.
1181 Locks::mutator_lock_->SharedUnlock(self);
Hiroshi Yamauchia2224042017-02-08 16:35:45 -08001182 thread_list->RunEmptyCheckpoint();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001183 Locks::mutator_lock_->SharedLock(self);
1184}
1185
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -07001186void ConcurrentCopying::ExpandGcMarkStack() {
1187 DCHECK(gc_mark_stack_->IsFull());
1188 const size_t new_size = gc_mark_stack_->Capacity() * 2;
1189 std::vector<StackReference<mirror::Object>> temp(gc_mark_stack_->Begin(),
1190 gc_mark_stack_->End());
1191 gc_mark_stack_->Resize(new_size);
1192 for (auto& ref : temp) {
1193 gc_mark_stack_->PushBack(ref.AsMirrorPtr());
1194 }
1195 DCHECK(!gc_mark_stack_->IsFull());
1196}
1197
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08001198void ConcurrentCopying::PushOntoMarkStack(Thread* const self, mirror::Object* to_ref) {
Orion Hodson88591fe2018-03-06 13:35:43 +00001199 CHECK_EQ(is_mark_stack_push_disallowed_.load(std::memory_order_relaxed), 0)
David Sehr709b0702016-10-13 09:12:37 -07001200 << " " << to_ref << " " << mirror::Object::PrettyTypeOf(to_ref);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001201 CHECK(thread_running_gc_ != nullptr);
Orion Hodson88591fe2018-03-06 13:35:43 +00001202 MarkStackMode mark_stack_mode = mark_stack_mode_.load(std::memory_order_relaxed);
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001203 if (LIKELY(mark_stack_mode == kMarkStackModeThreadLocal)) {
1204 if (LIKELY(self == thread_running_gc_)) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001205 // If GC-running thread, use the GC mark stack instead of a thread-local mark stack.
1206 CHECK(self->GetThreadLocalMarkStack() == nullptr);
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -07001207 if (UNLIKELY(gc_mark_stack_->IsFull())) {
1208 ExpandGcMarkStack();
1209 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001210 gc_mark_stack_->PushBack(to_ref);
1211 } else {
1212 // Otherwise, use a thread-local mark stack.
1213 accounting::AtomicStack<mirror::Object>* tl_mark_stack = self->GetThreadLocalMarkStack();
1214 if (UNLIKELY(tl_mark_stack == nullptr || tl_mark_stack->IsFull())) {
1215 MutexLock mu(self, mark_stack_lock_);
1216 // Get a new thread local mark stack.
1217 accounting::AtomicStack<mirror::Object>* new_tl_mark_stack;
1218 if (!pooled_mark_stacks_.empty()) {
1219 // Use a pooled mark stack.
1220 new_tl_mark_stack = pooled_mark_stacks_.back();
1221 pooled_mark_stacks_.pop_back();
1222 } else {
1223 // None pooled. Create a new one.
1224 new_tl_mark_stack =
1225 accounting::AtomicStack<mirror::Object>::Create(
1226 "thread local mark stack", 4 * KB, 4 * KB);
1227 }
1228 DCHECK(new_tl_mark_stack != nullptr);
1229 DCHECK(new_tl_mark_stack->IsEmpty());
1230 new_tl_mark_stack->PushBack(to_ref);
1231 self->SetThreadLocalMarkStack(new_tl_mark_stack);
1232 if (tl_mark_stack != nullptr) {
1233 // Store the old full stack into a vector.
1234 revoked_mark_stacks_.push_back(tl_mark_stack);
1235 }
1236 } else {
1237 tl_mark_stack->PushBack(to_ref);
1238 }
1239 }
1240 } else if (mark_stack_mode == kMarkStackModeShared) {
1241 // Access the shared GC mark stack with a lock.
1242 MutexLock mu(self, mark_stack_lock_);
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -07001243 if (UNLIKELY(gc_mark_stack_->IsFull())) {
1244 ExpandGcMarkStack();
1245 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001246 gc_mark_stack_->PushBack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001247 } else {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001248 CHECK_EQ(static_cast<uint32_t>(mark_stack_mode),
Hiroshi Yamauchifa755182015-09-30 20:12:11 -07001249 static_cast<uint32_t>(kMarkStackModeGcExclusive))
1250 << "ref=" << to_ref
1251 << " self->gc_marking=" << self->GetIsGcMarking()
1252 << " cc->is_marking=" << is_marking_;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001253 CHECK(self == thread_running_gc_)
1254 << "Only GC-running thread should access the mark stack "
1255 << "in the GC exclusive mark stack mode";
1256 // Access the GC mark stack without a lock.
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -07001257 if (UNLIKELY(gc_mark_stack_->IsFull())) {
1258 ExpandGcMarkStack();
1259 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001260 gc_mark_stack_->PushBack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001261 }
1262}
1263
1264accounting::ObjectStack* ConcurrentCopying::GetAllocationStack() {
1265 return heap_->allocation_stack_.get();
1266}
1267
1268accounting::ObjectStack* ConcurrentCopying::GetLiveStack() {
1269 return heap_->live_stack_.get();
1270}
1271
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001272// The following visitors are used to verify that there's no references to the from-space left after
1273// marking.
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001274class ConcurrentCopying::VerifyNoFromSpaceRefsVisitor : public SingleRootVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001275 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001276 explicit VerifyNoFromSpaceRefsVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001277 : collector_(collector) {}
1278
Mathieu Chartierbc632f02017-04-20 13:31:39 -07001279 void operator()(mirror::Object* ref,
1280 MemberOffset offset = MemberOffset(0),
1281 mirror::Object* holder = nullptr) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001282 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001283 if (ref == nullptr) {
1284 // OK.
1285 return;
1286 }
Mathieu Chartierbc632f02017-04-20 13:31:39 -07001287 collector_->AssertToSpaceInvariant(holder, offset, ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001288 if (kUseBakerReadBarrier) {
Roland Levillain14e5a292018-06-28 12:00:56 +01001289 CHECK_EQ(ref->GetReadBarrierState(), ReadBarrier::NonGrayState())
1290 << "Ref " << ref << " " << ref->PrettyTypeOf() << " has gray rb_state";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001291 }
1292 }
1293
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001294 void VisitRoot(mirror::Object* root, const RootInfo& info ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001295 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001296 DCHECK(root != nullptr);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001297 operator()(root);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001298 }
1299
1300 private:
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001301 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001302};
1303
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001304class ConcurrentCopying::VerifyNoFromSpaceRefsFieldVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001305 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001306 explicit VerifyNoFromSpaceRefsFieldVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001307 : collector_(collector) {}
1308
Mathieu Chartier31e88222016-10-14 18:43:19 -07001309 void operator()(ObjPtr<mirror::Object> obj,
1310 MemberOffset offset,
1311 bool is_static ATTRIBUTE_UNUSED) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001312 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001313 mirror::Object* ref =
1314 obj->GetFieldObject<mirror::Object, kDefaultVerifyFlags, kWithoutReadBarrier>(offset);
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001315 VerifyNoFromSpaceRefsVisitor visitor(collector_);
Mathieu Chartierbc632f02017-04-20 13:31:39 -07001316 visitor(ref, offset, obj.Ptr());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001317 }
Mathieu Chartier31e88222016-10-14 18:43:19 -07001318 void operator()(ObjPtr<mirror::Class> klass,
1319 ObjPtr<mirror::Reference> ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001320 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001321 CHECK(klass->IsTypeOfReferenceClass());
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07001322 this->operator()(ObjPtr<mirror::Object>(ref), mirror::Reference::ReferentOffset(), false);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001323 }
1324
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001325 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001326 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001327 if (!root->IsNull()) {
1328 VisitRoot(root);
1329 }
1330 }
1331
1332 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001333 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001334 VerifyNoFromSpaceRefsVisitor visitor(collector_);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001335 visitor(root->AsMirrorPtr());
1336 }
1337
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001338 private:
Mathieu Chartier97509952015-07-13 14:35:43 -07001339 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001340};
1341
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001342// Verify there's no from-space references left after the marking phase.
1343void ConcurrentCopying::VerifyNoFromSpaceReferences() {
1344 Thread* self = Thread::Current();
1345 DCHECK(Locks::mutator_lock_->IsExclusiveHeld(self));
Hiroshi Yamauchi00370822015-08-18 14:47:25 -07001346 // Verify all threads have is_gc_marking to be false
1347 {
1348 MutexLock mu(self, *Locks::thread_list_lock_);
1349 std::list<Thread*> thread_list = Runtime::Current()->GetThreadList()->GetList();
1350 for (Thread* thread : thread_list) {
1351 CHECK(!thread->GetIsGcMarking());
1352 }
1353 }
Andreas Gampe0c183382017-07-13 22:26:24 -07001354
1355 auto verify_no_from_space_refs_visitor = [&](mirror::Object* obj)
1356 REQUIRES_SHARED(Locks::mutator_lock_) {
1357 CHECK(obj != nullptr);
1358 space::RegionSpace* region_space = RegionSpace();
1359 CHECK(!region_space->IsInFromSpace(obj)) << "Scanning object " << obj << " in from space";
1360 VerifyNoFromSpaceRefsFieldVisitor visitor(this);
1361 obj->VisitReferences</*kVisitNativeRoots*/true, kDefaultVerifyFlags, kWithoutReadBarrier>(
1362 visitor,
1363 visitor);
1364 if (kUseBakerReadBarrier) {
Roland Levillain14e5a292018-06-28 12:00:56 +01001365 CHECK_EQ(obj->GetReadBarrierState(), ReadBarrier::NonGrayState())
1366 << "obj=" << obj << " has gray rb_state " << obj->GetReadBarrierState();
Andreas Gampe0c183382017-07-13 22:26:24 -07001367 }
1368 };
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001369 // Roots.
1370 {
1371 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001372 VerifyNoFromSpaceRefsVisitor ref_visitor(this);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001373 Runtime::Current()->VisitRoots(&ref_visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001374 }
1375 // The to-space.
Andreas Gampe0c183382017-07-13 22:26:24 -07001376 region_space_->WalkToSpace(verify_no_from_space_refs_visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001377 // Non-moving spaces.
1378 {
1379 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Andreas Gampe0c183382017-07-13 22:26:24 -07001380 heap_->GetMarkBitmap()->Visit(verify_no_from_space_refs_visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001381 }
1382 // The alloc stack.
1383 {
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001384 VerifyNoFromSpaceRefsVisitor ref_visitor(this);
Mathieu Chartiercb535da2015-01-23 13:50:03 -08001385 for (auto* it = heap_->allocation_stack_->Begin(), *end = heap_->allocation_stack_->End();
1386 it < end; ++it) {
1387 mirror::Object* const obj = it->AsMirrorPtr();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001388 if (obj != nullptr && obj->GetClass() != nullptr) {
1389 // TODO: need to call this only if obj is alive?
1390 ref_visitor(obj);
Andreas Gampe0c183382017-07-13 22:26:24 -07001391 verify_no_from_space_refs_visitor(obj);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001392 }
1393 }
1394 }
1395 // TODO: LOS. But only refs in LOS are classes.
1396}
1397
1398// The following visitors are used to assert the to-space invariant.
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001399class ConcurrentCopying::AssertToSpaceInvariantRefsVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001400 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001401 explicit AssertToSpaceInvariantRefsVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001402 : collector_(collector) {}
1403
1404 void operator()(mirror::Object* ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001405 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001406 if (ref == nullptr) {
1407 // OK.
1408 return;
1409 }
1410 collector_->AssertToSpaceInvariant(nullptr, MemberOffset(0), ref);
1411 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001412
1413 private:
Mathieu Chartier97509952015-07-13 14:35:43 -07001414 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001415};
1416
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001417class ConcurrentCopying::AssertToSpaceInvariantFieldVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001418 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001419 explicit AssertToSpaceInvariantFieldVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001420 : collector_(collector) {}
1421
Mathieu Chartier31e88222016-10-14 18:43:19 -07001422 void operator()(ObjPtr<mirror::Object> obj,
1423 MemberOffset offset,
1424 bool is_static ATTRIBUTE_UNUSED) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001425 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001426 mirror::Object* ref =
1427 obj->GetFieldObject<mirror::Object, kDefaultVerifyFlags, kWithoutReadBarrier>(offset);
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001428 AssertToSpaceInvariantRefsVisitor visitor(collector_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001429 visitor(ref);
1430 }
Mathieu Chartier31e88222016-10-14 18:43:19 -07001431 void operator()(ObjPtr<mirror::Class> klass, ObjPtr<mirror::Reference> ref ATTRIBUTE_UNUSED) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001432 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001433 CHECK(klass->IsTypeOfReferenceClass());
1434 }
1435
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001436 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001437 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001438 if (!root->IsNull()) {
1439 VisitRoot(root);
1440 }
1441 }
1442
1443 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001444 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001445 AssertToSpaceInvariantRefsVisitor visitor(collector_);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001446 visitor(root->AsMirrorPtr());
1447 }
1448
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001449 private:
Mathieu Chartier97509952015-07-13 14:35:43 -07001450 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001451};
1452
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001453class ConcurrentCopying::RevokeThreadLocalMarkStackCheckpoint : public Closure {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001454 public:
Roland Levillain3887c462015-08-12 18:15:42 +01001455 RevokeThreadLocalMarkStackCheckpoint(ConcurrentCopying* concurrent_copying,
1456 bool disable_weak_ref_access)
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001457 : concurrent_copying_(concurrent_copying),
1458 disable_weak_ref_access_(disable_weak_ref_access) {
1459 }
1460
1461 virtual void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
1462 // Note: self is not necessarily equal to thread since thread may be suspended.
1463 Thread* self = Thread::Current();
1464 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
1465 << thread->GetState() << " thread " << thread << " self " << self;
1466 // Revoke thread local mark stacks.
1467 accounting::AtomicStack<mirror::Object>* tl_mark_stack = thread->GetThreadLocalMarkStack();
1468 if (tl_mark_stack != nullptr) {
1469 MutexLock mu(self, concurrent_copying_->mark_stack_lock_);
1470 concurrent_copying_->revoked_mark_stacks_.push_back(tl_mark_stack);
1471 thread->SetThreadLocalMarkStack(nullptr);
1472 }
1473 // Disable weak ref access.
1474 if (disable_weak_ref_access_) {
1475 thread->SetWeakRefAccessEnabled(false);
1476 }
1477 // If thread is a running mutator, then act on behalf of the garbage collector.
1478 // See the code in ThreadList::RunCheckpoint.
Mathieu Chartier10d25082015-10-28 18:36:09 -07001479 concurrent_copying_->GetBarrier().Pass(self);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001480 }
1481
1482 private:
1483 ConcurrentCopying* const concurrent_copying_;
1484 const bool disable_weak_ref_access_;
1485};
1486
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001487void ConcurrentCopying::RevokeThreadLocalMarkStacks(bool disable_weak_ref_access,
1488 Closure* checkpoint_callback) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001489 Thread* self = Thread::Current();
1490 RevokeThreadLocalMarkStackCheckpoint check_point(this, disable_weak_ref_access);
1491 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1492 gc_barrier_->Init(self, 0);
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001493 size_t barrier_count = thread_list->RunCheckpoint(&check_point, checkpoint_callback);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001494 // If there are no threads to wait which implys that all the checkpoint functions are finished,
1495 // then no need to release the mutator lock.
1496 if (barrier_count == 0) {
1497 return;
1498 }
1499 Locks::mutator_lock_->SharedUnlock(self);
1500 {
1501 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
1502 gc_barrier_->Increment(self, barrier_count);
1503 }
1504 Locks::mutator_lock_->SharedLock(self);
1505}
1506
1507void ConcurrentCopying::RevokeThreadLocalMarkStack(Thread* thread) {
1508 Thread* self = Thread::Current();
1509 CHECK_EQ(self, thread);
1510 accounting::AtomicStack<mirror::Object>* tl_mark_stack = thread->GetThreadLocalMarkStack();
1511 if (tl_mark_stack != nullptr) {
1512 CHECK(is_marking_);
1513 MutexLock mu(self, mark_stack_lock_);
1514 revoked_mark_stacks_.push_back(tl_mark_stack);
1515 thread->SetThreadLocalMarkStack(nullptr);
1516 }
1517}
1518
1519void ConcurrentCopying::ProcessMarkStack() {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001520 if (kVerboseMode) {
1521 LOG(INFO) << "ProcessMarkStack. ";
1522 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001523 bool empty_prev = false;
1524 while (true) {
1525 bool empty = ProcessMarkStackOnce();
1526 if (empty_prev && empty) {
1527 // Saw empty mark stack for a second time, done.
1528 break;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001529 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001530 empty_prev = empty;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001531 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001532}
1533
1534bool ConcurrentCopying::ProcessMarkStackOnce() {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08001535 DCHECK(thread_running_gc_ != nullptr);
1536 Thread* const self = Thread::Current();
1537 DCHECK(self == thread_running_gc_);
1538 DCHECK(thread_running_gc_->GetThreadLocalMarkStack() == nullptr);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001539 size_t count = 0;
Orion Hodson88591fe2018-03-06 13:35:43 +00001540 MarkStackMode mark_stack_mode = mark_stack_mode_.load(std::memory_order_relaxed);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001541 if (mark_stack_mode == kMarkStackModeThreadLocal) {
1542 // Process the thread-local mark stacks and the GC mark stack.
Roland Levillainaf290312018-02-27 20:02:17 +00001543 count += ProcessThreadLocalMarkStacks(/* disable_weak_ref_access */ false,
1544 /* checkpoint_callback */ nullptr);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001545 while (!gc_mark_stack_->IsEmpty()) {
1546 mirror::Object* to_ref = gc_mark_stack_->PopBack();
1547 ProcessMarkStackRef(to_ref);
1548 ++count;
1549 }
1550 gc_mark_stack_->Reset();
1551 } else if (mark_stack_mode == kMarkStackModeShared) {
Hiroshi Yamauchi30493242016-11-03 13:06:52 -07001552 // Do an empty checkpoint to avoid a race with a mutator preempted in the middle of a read
1553 // barrier but before pushing onto the mark stack. b/32508093. Note the weak ref access is
1554 // disabled at this point.
1555 IssueEmptyCheckpoint();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001556 // Process the shared GC mark stack with a lock.
1557 {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08001558 MutexLock mu(thread_running_gc_, mark_stack_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001559 CHECK(revoked_mark_stacks_.empty());
1560 }
1561 while (true) {
1562 std::vector<mirror::Object*> refs;
1563 {
1564 // Copy refs with lock. Note the number of refs should be small.
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08001565 MutexLock mu(thread_running_gc_, mark_stack_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001566 if (gc_mark_stack_->IsEmpty()) {
1567 break;
1568 }
1569 for (StackReference<mirror::Object>* p = gc_mark_stack_->Begin();
1570 p != gc_mark_stack_->End(); ++p) {
1571 refs.push_back(p->AsMirrorPtr());
1572 }
1573 gc_mark_stack_->Reset();
1574 }
1575 for (mirror::Object* ref : refs) {
1576 ProcessMarkStackRef(ref);
1577 ++count;
1578 }
1579 }
1580 } else {
1581 CHECK_EQ(static_cast<uint32_t>(mark_stack_mode),
1582 static_cast<uint32_t>(kMarkStackModeGcExclusive));
1583 {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08001584 MutexLock mu(thread_running_gc_, mark_stack_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001585 CHECK(revoked_mark_stacks_.empty());
1586 }
1587 // Process the GC mark stack in the exclusive mode. No need to take the lock.
1588 while (!gc_mark_stack_->IsEmpty()) {
1589 mirror::Object* to_ref = gc_mark_stack_->PopBack();
1590 ProcessMarkStackRef(to_ref);
1591 ++count;
1592 }
1593 gc_mark_stack_->Reset();
1594 }
1595
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001596 // Return true if the stack was empty.
1597 return count == 0;
1598}
1599
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001600size_t ConcurrentCopying::ProcessThreadLocalMarkStacks(bool disable_weak_ref_access,
1601 Closure* checkpoint_callback) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001602 // Run a checkpoint to collect all thread local mark stacks and iterate over them all.
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001603 RevokeThreadLocalMarkStacks(disable_weak_ref_access, checkpoint_callback);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001604 size_t count = 0;
1605 std::vector<accounting::AtomicStack<mirror::Object>*> mark_stacks;
1606 {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08001607 MutexLock mu(thread_running_gc_, mark_stack_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001608 // Make a copy of the mark stack vector.
1609 mark_stacks = revoked_mark_stacks_;
1610 revoked_mark_stacks_.clear();
1611 }
1612 for (accounting::AtomicStack<mirror::Object>* mark_stack : mark_stacks) {
1613 for (StackReference<mirror::Object>* p = mark_stack->Begin(); p != mark_stack->End(); ++p) {
1614 mirror::Object* to_ref = p->AsMirrorPtr();
1615 ProcessMarkStackRef(to_ref);
1616 ++count;
1617 }
1618 {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08001619 MutexLock mu(thread_running_gc_, mark_stack_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001620 if (pooled_mark_stacks_.size() >= kMarkStackPoolSize) {
1621 // The pool has enough. Delete it.
1622 delete mark_stack;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001623 } else {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001624 // Otherwise, put it into the pool for later reuse.
1625 mark_stack->Reset();
1626 pooled_mark_stacks_.push_back(mark_stack);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001627 }
1628 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001629 }
1630 return count;
1631}
1632
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001633inline void ConcurrentCopying::ProcessMarkStackRef(mirror::Object* to_ref) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001634 DCHECK(!region_space_->IsInFromSpace(to_ref));
1635 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001636 DCHECK(to_ref->GetReadBarrierState() == ReadBarrier::GrayState())
1637 << " " << to_ref << " " << to_ref->GetReadBarrierState()
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001638 << " is_marked=" << IsMarked(to_ref);
1639 }
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07001640 space::RegionSpace::RegionType rtype = region_space_->GetRegionType(to_ref);
Mathieu Chartierc381c362016-08-23 13:27:53 -07001641 bool add_to_live_bytes = false;
Roland Levillain4e751132018-01-15 11:52:58 +00001642 // Invariant: There should be no object from a newly-allocated
1643 // region (either large or non-large) on the mark stack.
1644 DCHECK(!region_space_->IsInNewlyAllocatedRegion(to_ref)) << to_ref;
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07001645 if (rtype == space::RegionSpace::RegionType::kRegionTypeUnevacFromSpace) {
Mathieu Chartierc381c362016-08-23 13:27:53 -07001646 // Mark the bitmap only in the GC thread here so that we don't need a CAS.
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07001647 if (!kUseBakerReadBarrier ||
1648 !region_space_bitmap_->Set(to_ref)) {
Mathieu Chartierc381c362016-08-23 13:27:53 -07001649 // It may be already marked if we accidentally pushed the same object twice due to the racy
1650 // bitmap read in MarkUnevacFromSpaceRegion.
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07001651 if (kEnableGenerationalConcurrentCopyingCollection && young_gen_) {
1652 CHECK(region_space_->IsLargeObject(to_ref));
1653 region_space_->ZeroLiveBytesForLargeObject(to_ref);
1654 Scan<true>(to_ref);
1655 } else {
1656 Scan<false>(to_ref);
1657 }
1658 // Only add to the live bytes if the object was not already marked and we are not the young
1659 // GC.
Mathieu Chartierc381c362016-08-23 13:27:53 -07001660 add_to_live_bytes = true;
1661 }
1662 } else {
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07001663 if (kEnableGenerationalConcurrentCopyingCollection) {
1664 if (rtype == space::RegionSpace::RegionType::kRegionTypeToSpace) {
1665 // Copied to to-space, set the bit so that the next GC can scan objects.
1666 region_space_bitmap_->Set(to_ref);
1667 }
1668 }
1669 if (kEnableGenerationalConcurrentCopyingCollection && young_gen_) {
1670 Scan<true>(to_ref);
1671 } else {
1672 Scan<false>(to_ref);
1673 }
Mathieu Chartierc381c362016-08-23 13:27:53 -07001674 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001675 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001676 DCHECK(to_ref->GetReadBarrierState() == ReadBarrier::GrayState())
1677 << " " << to_ref << " " << to_ref->GetReadBarrierState()
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001678 << " is_marked=" << IsMarked(to_ref);
1679 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001680#ifdef USE_BAKER_OR_BROOKS_READ_BARRIER
Hiroshi Yamauchi39c12d42016-12-06 16:46:37 -08001681 mirror::Object* referent = nullptr;
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001682 if (UNLIKELY((to_ref->GetClass<kVerifyNone, kWithoutReadBarrier>()->IsTypeOfReferenceClass() &&
Hiroshi Yamauchi39c12d42016-12-06 16:46:37 -08001683 (referent = to_ref->AsReference()->GetReferent<kWithoutReadBarrier>()) != nullptr &&
1684 !IsInToSpace(referent)))) {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001685 // Leave this reference gray in the queue so that GetReferent() will trigger a read barrier. We
Roland Levillain14e5a292018-06-28 12:00:56 +01001686 // will change it to non-gray later in ReferenceQueue::DisableReadBarrierForReference.
Roland Levillain2ae376f2018-01-30 11:35:11 +00001687 DCHECK(to_ref->AsReference()->GetPendingNext() != nullptr)
1688 << "Left unenqueued ref gray " << to_ref;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001689 } else {
Roland Levillain14e5a292018-06-28 12:00:56 +01001690 // We may occasionally leave a reference non-gray in the queue if its referent happens to be
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001691 // concurrently marked after the Scan() call above has enqueued the Reference, in which case the
Roland Levillain14e5a292018-06-28 12:00:56 +01001692 // above IsInToSpace() evaluates to true and we change the color from gray to non-gray here in
1693 // this else block.
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001694 if (kUseBakerReadBarrier) {
Mathieu Chartier42c2e502018-06-19 12:30:56 -07001695 bool success = to_ref->AtomicSetReadBarrierState<std::memory_order_release>(
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001696 ReadBarrier::GrayState(),
Roland Levillain14e5a292018-06-28 12:00:56 +01001697 ReadBarrier::NonGrayState());
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001698 DCHECK(success) << "Must succeed as we won the race.";
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001699 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001700 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001701#else
1702 DCHECK(!kUseBakerReadBarrier);
1703#endif
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001704
Mathieu Chartierc381c362016-08-23 13:27:53 -07001705 if (add_to_live_bytes) {
Roland Levillain2ae376f2018-01-30 11:35:11 +00001706 // Add to the live bytes per unevacuated from-space. Note this code is always run by the
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001707 // GC-running thread (no synchronization required).
1708 DCHECK(region_space_bitmap_->Test(to_ref));
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07001709 size_t obj_size = to_ref->SizeOf<kDefaultVerifyFlags>();
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001710 size_t alloc_size = RoundUp(obj_size, space::RegionSpace::kAlignment);
1711 region_space_->AddLiveBytes(to_ref, alloc_size);
1712 }
Andreas Gampee3ce7872017-02-22 13:36:21 -08001713 if (ReadBarrier::kEnableToSpaceInvariantChecks) {
Andreas Gampe0c183382017-07-13 22:26:24 -07001714 CHECK(to_ref != nullptr);
1715 space::RegionSpace* region_space = RegionSpace();
1716 CHECK(!region_space->IsInFromSpace(to_ref)) << "Scanning object " << to_ref << " in from space";
1717 AssertToSpaceInvariant(nullptr, MemberOffset(0), to_ref);
1718 AssertToSpaceInvariantFieldVisitor visitor(this);
1719 to_ref->VisitReferences</*kVisitNativeRoots*/true, kDefaultVerifyFlags, kWithoutReadBarrier>(
1720 visitor,
1721 visitor);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001722 }
1723}
1724
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001725class ConcurrentCopying::DisableWeakRefAccessCallback : public Closure {
1726 public:
1727 explicit DisableWeakRefAccessCallback(ConcurrentCopying* concurrent_copying)
1728 : concurrent_copying_(concurrent_copying) {
1729 }
1730
1731 void Run(Thread* self ATTRIBUTE_UNUSED) OVERRIDE REQUIRES(Locks::thread_list_lock_) {
1732 // This needs to run under the thread_list_lock_ critical section in ThreadList::RunCheckpoint()
1733 // to avoid a deadlock b/31500969.
1734 CHECK(concurrent_copying_->weak_ref_access_enabled_);
1735 concurrent_copying_->weak_ref_access_enabled_ = false;
1736 }
1737
1738 private:
1739 ConcurrentCopying* const concurrent_copying_;
1740};
1741
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001742void ConcurrentCopying::SwitchToSharedMarkStackMode() {
1743 Thread* self = Thread::Current();
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08001744 DCHECK(thread_running_gc_ != nullptr);
1745 DCHECK(self == thread_running_gc_);
1746 DCHECK(thread_running_gc_->GetThreadLocalMarkStack() == nullptr);
Orion Hodson88591fe2018-03-06 13:35:43 +00001747 MarkStackMode before_mark_stack_mode = mark_stack_mode_.load(std::memory_order_relaxed);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001748 CHECK_EQ(static_cast<uint32_t>(before_mark_stack_mode),
1749 static_cast<uint32_t>(kMarkStackModeThreadLocal));
Orion Hodson88591fe2018-03-06 13:35:43 +00001750 mark_stack_mode_.store(kMarkStackModeShared, std::memory_order_relaxed);
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001751 DisableWeakRefAccessCallback dwrac(this);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001752 // Process the thread local mark stacks one last time after switching to the shared mark stack
1753 // mode and disable weak ref accesses.
Roland Levillainaf290312018-02-27 20:02:17 +00001754 ProcessThreadLocalMarkStacks(/* disable_weak_ref_access */ true, &dwrac);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001755 if (kVerboseMode) {
1756 LOG(INFO) << "Switched to shared mark stack mode and disabled weak ref access";
1757 }
1758}
1759
1760void ConcurrentCopying::SwitchToGcExclusiveMarkStackMode() {
1761 Thread* self = Thread::Current();
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08001762 DCHECK(thread_running_gc_ != nullptr);
1763 DCHECK(self == thread_running_gc_);
1764 DCHECK(thread_running_gc_->GetThreadLocalMarkStack() == nullptr);
Orion Hodson88591fe2018-03-06 13:35:43 +00001765 MarkStackMode before_mark_stack_mode = mark_stack_mode_.load(std::memory_order_relaxed);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001766 CHECK_EQ(static_cast<uint32_t>(before_mark_stack_mode),
1767 static_cast<uint32_t>(kMarkStackModeShared));
Orion Hodson88591fe2018-03-06 13:35:43 +00001768 mark_stack_mode_.store(kMarkStackModeGcExclusive, std::memory_order_relaxed);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001769 QuasiAtomic::ThreadFenceForConstructor();
1770 if (kVerboseMode) {
1771 LOG(INFO) << "Switched to GC exclusive mark stack mode";
1772 }
1773}
1774
1775void ConcurrentCopying::CheckEmptyMarkStack() {
1776 Thread* self = Thread::Current();
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08001777 DCHECK(thread_running_gc_ != nullptr);
1778 DCHECK(self == thread_running_gc_);
1779 DCHECK(thread_running_gc_->GetThreadLocalMarkStack() == nullptr);
Orion Hodson88591fe2018-03-06 13:35:43 +00001780 MarkStackMode mark_stack_mode = mark_stack_mode_.load(std::memory_order_relaxed);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001781 if (mark_stack_mode == kMarkStackModeThreadLocal) {
1782 // Thread-local mark stack mode.
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001783 RevokeThreadLocalMarkStacks(false, nullptr);
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08001784 MutexLock mu(thread_running_gc_, mark_stack_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001785 if (!revoked_mark_stacks_.empty()) {
1786 for (accounting::AtomicStack<mirror::Object>* mark_stack : revoked_mark_stacks_) {
1787 while (!mark_stack->IsEmpty()) {
1788 mirror::Object* obj = mark_stack->PopBack();
1789 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001790 uint32_t rb_state = obj->GetReadBarrierState();
1791 LOG(INFO) << "On mark queue : " << obj << " " << obj->PrettyTypeOf() << " rb_state="
1792 << rb_state << " is_marked=" << IsMarked(obj);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001793 } else {
David Sehr709b0702016-10-13 09:12:37 -07001794 LOG(INFO) << "On mark queue : " << obj << " " << obj->PrettyTypeOf()
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001795 << " is_marked=" << IsMarked(obj);
1796 }
1797 }
1798 }
1799 LOG(FATAL) << "mark stack is not empty";
1800 }
1801 } else {
1802 // Shared, GC-exclusive, or off.
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08001803 MutexLock mu(thread_running_gc_, mark_stack_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001804 CHECK(gc_mark_stack_->IsEmpty());
1805 CHECK(revoked_mark_stacks_.empty());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001806 }
1807}
1808
1809void ConcurrentCopying::SweepSystemWeaks(Thread* self) {
1810 TimingLogger::ScopedTiming split("SweepSystemWeaks", GetTimings());
1811 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier97509952015-07-13 14:35:43 -07001812 Runtime::Current()->SweepSystemWeaks(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001813}
1814
1815void ConcurrentCopying::Sweep(bool swap_bitmaps) {
Roland Levillainb1e1dc32018-07-10 19:19:31 +01001816 if (kEnableGenerationalConcurrentCopyingCollection && young_gen_) {
1817 // Only sweep objects on the live stack.
1818 SweepArray(heap_->GetLiveStack(), /* swap_bitmaps */ false);
1819 } else {
1820 {
1821 TimingLogger::ScopedTiming t("MarkStackAsLive", GetTimings());
1822 accounting::ObjectStack* live_stack = heap_->GetLiveStack();
1823 if (kEnableFromSpaceAccountingCheck) {
1824 // Ensure that nobody inserted items in the live stack after we swapped the stacks.
1825 CHECK_GE(live_stack_freeze_size_, live_stack->Size());
1826 }
1827 heap_->MarkAllocStackAsLive(live_stack);
1828 live_stack->Reset();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001829 }
Roland Levillainb1e1dc32018-07-10 19:19:31 +01001830 CheckEmptyMarkStack();
1831 TimingLogger::ScopedTiming split("Sweep", GetTimings());
1832 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
1833 if (space->IsContinuousMemMapAllocSpace()) {
1834 space::ContinuousMemMapAllocSpace* alloc_space = space->AsContinuousMemMapAllocSpace();
1835 if (space == region_space_ || immune_spaces_.ContainsSpace(space)) {
1836 continue;
1837 }
1838 TimingLogger::ScopedTiming split2(
1839 alloc_space->IsZygoteSpace() ? "SweepZygoteSpace" : "SweepAllocSpace", GetTimings());
1840 RecordFree(alloc_space->Sweep(swap_bitmaps));
1841 }
1842 }
1843 SweepLargeObjects(swap_bitmaps);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001844 }
Roland Levillainb1e1dc32018-07-10 19:19:31 +01001845}
1846
1847// Copied and adapted from MarkSweep::SweepArray.
1848void ConcurrentCopying::SweepArray(accounting::ObjectStack* allocations, bool swap_bitmaps) {
1849 // This method is only used when Generational CC collection is enabled.
1850 DCHECK(kEnableGenerationalConcurrentCopyingCollection);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001851 CheckEmptyMarkStack();
Roland Levillainb1e1dc32018-07-10 19:19:31 +01001852 TimingLogger::ScopedTiming t("SweepArray", GetTimings());
1853 Thread* self = Thread::Current();
1854 mirror::Object** chunk_free_buffer = reinterpret_cast<mirror::Object**>(
1855 sweep_array_free_buffer_mem_map_.BaseBegin());
1856 size_t chunk_free_pos = 0;
1857 ObjectBytePair freed;
1858 ObjectBytePair freed_los;
1859 // How many objects are left in the array, modified after each space is swept.
1860 StackReference<mirror::Object>* objects = allocations->Begin();
1861 size_t count = allocations->Size();
1862 // Start by sweeping the continuous spaces.
1863 for (space::ContinuousSpace* space : heap_->GetContinuousSpaces()) {
1864 if (!space->IsAllocSpace() ||
1865 space == region_space_ ||
1866 immune_spaces_.ContainsSpace(space) ||
1867 space->GetLiveBitmap() == nullptr) {
1868 continue;
1869 }
1870 space::AllocSpace* alloc_space = space->AsAllocSpace();
1871 accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
1872 accounting::ContinuousSpaceBitmap* mark_bitmap = space->GetMarkBitmap();
1873 if (swap_bitmaps) {
1874 std::swap(live_bitmap, mark_bitmap);
1875 }
1876 StackReference<mirror::Object>* out = objects;
1877 for (size_t i = 0; i < count; ++i) {
1878 mirror::Object* const obj = objects[i].AsMirrorPtr();
1879 if (kUseThreadLocalAllocationStack && obj == nullptr) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001880 continue;
1881 }
Roland Levillainb1e1dc32018-07-10 19:19:31 +01001882 if (space->HasAddress(obj)) {
1883 // This object is in the space, remove it from the array and add it to the sweep buffer
1884 // if needed.
1885 if (!mark_bitmap->Test(obj)) {
1886 if (chunk_free_pos >= kSweepArrayChunkFreeSize) {
1887 TimingLogger::ScopedTiming t2("FreeList", GetTimings());
1888 freed.objects += chunk_free_pos;
1889 freed.bytes += alloc_space->FreeList(self, chunk_free_pos, chunk_free_buffer);
1890 chunk_free_pos = 0;
1891 }
1892 chunk_free_buffer[chunk_free_pos++] = obj;
1893 }
1894 } else {
1895 (out++)->Assign(obj);
1896 }
1897 }
1898 if (chunk_free_pos > 0) {
1899 TimingLogger::ScopedTiming t2("FreeList", GetTimings());
1900 freed.objects += chunk_free_pos;
1901 freed.bytes += alloc_space->FreeList(self, chunk_free_pos, chunk_free_buffer);
1902 chunk_free_pos = 0;
1903 }
1904 // All of the references which space contained are no longer in the allocation stack, update
1905 // the count.
1906 count = out - objects;
1907 }
1908 // Handle the large object space.
1909 space::LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
1910 if (large_object_space != nullptr) {
1911 accounting::LargeObjectBitmap* large_live_objects = large_object_space->GetLiveBitmap();
1912 accounting::LargeObjectBitmap* large_mark_objects = large_object_space->GetMarkBitmap();
1913 if (swap_bitmaps) {
1914 std::swap(large_live_objects, large_mark_objects);
1915 }
1916 for (size_t i = 0; i < count; ++i) {
1917 mirror::Object* const obj = objects[i].AsMirrorPtr();
1918 // Handle large objects.
1919 if (kUseThreadLocalAllocationStack && obj == nullptr) {
1920 continue;
1921 }
1922 if (!large_mark_objects->Test(obj)) {
1923 ++freed_los.objects;
1924 freed_los.bytes += large_object_space->Free(self, obj);
1925 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001926 }
1927 }
Roland Levillainb1e1dc32018-07-10 19:19:31 +01001928 {
1929 TimingLogger::ScopedTiming t2("RecordFree", GetTimings());
1930 RecordFree(freed);
1931 RecordFreeLOS(freed_los);
1932 t2.NewTiming("ResetStack");
1933 allocations->Reset();
1934 }
1935 sweep_array_free_buffer_mem_map_.MadviseDontNeedAndZero();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001936}
1937
Mathieu Chartier962cd7a2016-08-16 12:15:59 -07001938void ConcurrentCopying::MarkZygoteLargeObjects() {
1939 TimingLogger::ScopedTiming split(__FUNCTION__, GetTimings());
1940 Thread* const self = Thread::Current();
1941 WriterMutexLock rmu(self, *Locks::heap_bitmap_lock_);
1942 space::LargeObjectSpace* const los = heap_->GetLargeObjectsSpace();
Nicolas Geoffray7acddd82017-05-03 15:04:55 +01001943 if (los != nullptr) {
1944 // Pick the current live bitmap (mark bitmap if swapped).
1945 accounting::LargeObjectBitmap* const live_bitmap = los->GetLiveBitmap();
1946 accounting::LargeObjectBitmap* const mark_bitmap = los->GetMarkBitmap();
1947 // Walk through all of the objects and explicitly mark the zygote ones so they don't get swept.
1948 std::pair<uint8_t*, uint8_t*> range = los->GetBeginEndAtomic();
1949 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(range.first),
1950 reinterpret_cast<uintptr_t>(range.second),
1951 [mark_bitmap, los, self](mirror::Object* obj)
1952 REQUIRES(Locks::heap_bitmap_lock_)
1953 REQUIRES_SHARED(Locks::mutator_lock_) {
1954 if (los->IsZygoteLargeObject(self, obj)) {
1955 mark_bitmap->Set(obj);
1956 }
1957 });
1958 }
Mathieu Chartier962cd7a2016-08-16 12:15:59 -07001959}
1960
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001961void ConcurrentCopying::SweepLargeObjects(bool swap_bitmaps) {
1962 TimingLogger::ScopedTiming split("SweepLargeObjects", GetTimings());
Nicolas Geoffray7acddd82017-05-03 15:04:55 +01001963 if (heap_->GetLargeObjectsSpace() != nullptr) {
1964 RecordFreeLOS(heap_->GetLargeObjectsSpace()->Sweep(swap_bitmaps));
1965 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001966}
1967
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001968void ConcurrentCopying::ReclaimPhase() {
1969 TimingLogger::ScopedTiming split("ReclaimPhase", GetTimings());
1970 if (kVerboseMode) {
1971 LOG(INFO) << "GC ReclaimPhase";
1972 }
1973 Thread* self = Thread::Current();
1974
1975 {
1976 // Double-check that the mark stack is empty.
1977 // Note: need to set this after VerifyNoFromSpaceRef().
1978 is_asserting_to_space_invariant_ = false;
1979 QuasiAtomic::ThreadFenceForConstructor();
1980 if (kVerboseMode) {
1981 LOG(INFO) << "Issue an empty check point. ";
1982 }
1983 IssueEmptyCheckpoint();
1984 // Disable the check.
Orion Hodson88591fe2018-03-06 13:35:43 +00001985 is_mark_stack_push_disallowed_.store(0, std::memory_order_seq_cst);
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001986 if (kUseBakerReadBarrier) {
Orion Hodson88591fe2018-03-06 13:35:43 +00001987 updated_all_immune_objects_.store(false, std::memory_order_seq_cst);
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001988 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001989 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001990 }
1991
1992 {
1993 // Record freed objects.
1994 TimingLogger::ScopedTiming split2("RecordFree", GetTimings());
1995 // Don't include thread-locals that are in the to-space.
Mathieu Chartier371b0472017-02-27 16:37:21 -08001996 const uint64_t from_bytes = region_space_->GetBytesAllocatedInFromSpace();
1997 const uint64_t from_objects = region_space_->GetObjectsAllocatedInFromSpace();
1998 const uint64_t unevac_from_bytes = region_space_->GetBytesAllocatedInUnevacFromSpace();
1999 const uint64_t unevac_from_objects = region_space_->GetObjectsAllocatedInUnevacFromSpace();
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002000 uint64_t to_bytes = bytes_moved_.load(std::memory_order_seq_cst) + bytes_moved_gc_thread_;
Orion Hodson88591fe2018-03-06 13:35:43 +00002001 cumulative_bytes_moved_.fetch_add(to_bytes, std::memory_order_relaxed);
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002002 uint64_t to_objects = objects_moved_.load(std::memory_order_seq_cst) + objects_moved_gc_thread_;
Orion Hodson88591fe2018-03-06 13:35:43 +00002003 cumulative_objects_moved_.fetch_add(to_objects, std::memory_order_relaxed);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002004 if (kEnableFromSpaceAccountingCheck) {
2005 CHECK_EQ(from_space_num_objects_at_first_pause_, from_objects + unevac_from_objects);
2006 CHECK_EQ(from_space_num_bytes_at_first_pause_, from_bytes + unevac_from_bytes);
2007 }
2008 CHECK_LE(to_objects, from_objects);
2009 CHECK_LE(to_bytes, from_bytes);
Roland Levillain8f7ea9a2018-01-26 17:27:59 +00002010 // Cleared bytes and objects, populated by the call to RegionSpace::ClearFromSpace below.
Mathieu Chartier371b0472017-02-27 16:37:21 -08002011 uint64_t cleared_bytes;
2012 uint64_t cleared_objects;
2013 {
2014 TimingLogger::ScopedTiming split4("ClearFromSpace", GetTimings());
2015 region_space_->ClearFromSpace(&cleared_bytes, &cleared_objects);
Roland Levillain8f7ea9a2018-01-26 17:27:59 +00002016 // `cleared_bytes` and `cleared_objects` may be greater than the from space equivalents since
2017 // RegionSpace::ClearFromSpace may clear empty unevac regions.
Mathieu Chartier371b0472017-02-27 16:37:21 -08002018 CHECK_GE(cleared_bytes, from_bytes);
2019 CHECK_GE(cleared_objects, from_objects);
2020 }
2021 int64_t freed_bytes = cleared_bytes - to_bytes;
2022 int64_t freed_objects = cleared_objects - to_objects;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002023 if (kVerboseMode) {
2024 LOG(INFO) << "RecordFree:"
2025 << " from_bytes=" << from_bytes << " from_objects=" << from_objects
Roland Levillain2ae376f2018-01-30 11:35:11 +00002026 << " unevac_from_bytes=" << unevac_from_bytes
2027 << " unevac_from_objects=" << unevac_from_objects
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002028 << " to_bytes=" << to_bytes << " to_objects=" << to_objects
2029 << " freed_bytes=" << freed_bytes << " freed_objects=" << freed_objects
2030 << " from_space size=" << region_space_->FromSpaceSize()
2031 << " unevac_from_space size=" << region_space_->UnevacFromSpaceSize()
2032 << " to_space size=" << region_space_->ToSpaceSize();
Roland Levillain2ae376f2018-01-30 11:35:11 +00002033 LOG(INFO) << "(before) num_bytes_allocated="
Orion Hodson88591fe2018-03-06 13:35:43 +00002034 << heap_->num_bytes_allocated_.load(std::memory_order_seq_cst);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002035 }
2036 RecordFree(ObjectBytePair(freed_objects, freed_bytes));
2037 if (kVerboseMode) {
Roland Levillain2ae376f2018-01-30 11:35:11 +00002038 LOG(INFO) << "(after) num_bytes_allocated="
Orion Hodson88591fe2018-03-06 13:35:43 +00002039 << heap_->num_bytes_allocated_.load(std::memory_order_seq_cst);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002040 }
2041 }
2042
2043 {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002044 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Roland Levillainb1e1dc32018-07-10 19:19:31 +01002045 Sweep(/* swap_bitmaps */ false);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002046 SwapBitmaps();
2047 heap_->UnBindBitmaps();
2048
Mathieu Chartier7ec38dc2016-10-07 15:24:46 -07002049 // 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 -07002050 DCHECK(region_space_bitmap_ != nullptr);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002051 region_space_bitmap_ = nullptr;
2052 }
2053
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002054 CheckEmptyMarkStack();
2055
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002056 if (kVerboseMode) {
2057 LOG(INFO) << "GC end of ReclaimPhase";
2058 }
2059}
2060
Roland Levillain001eff92018-01-24 14:24:33 +00002061std::string ConcurrentCopying::DumpReferenceInfo(mirror::Object* ref,
2062 const char* ref_name,
Andreas Gampebc802de2018-06-20 17:24:11 -07002063 const char* indent) {
Roland Levillain001eff92018-01-24 14:24:33 +00002064 std::ostringstream oss;
2065 oss << indent << heap_->GetVerification()->DumpObjectInfo(ref, ref_name) << '\n';
2066 if (ref != nullptr) {
2067 if (kUseBakerReadBarrier) {
2068 oss << indent << ref_name << "->GetMarkBit()=" << ref->GetMarkBit() << '\n';
2069 oss << indent << ref_name << "->GetReadBarrierState()=" << ref->GetReadBarrierState() << '\n';
2070 }
2071 }
2072 if (region_space_->HasAddress(ref)) {
2073 oss << indent << "Region containing " << ref_name << ":" << '\n';
2074 region_space_->DumpRegionForObject(oss, ref);
2075 if (region_space_bitmap_ != nullptr) {
2076 oss << indent << "region_space_bitmap_->Test(" << ref_name << ")="
2077 << std::boolalpha << region_space_bitmap_->Test(ref) << std::noboolalpha;
2078 }
2079 }
2080 return oss.str();
2081}
2082
2083std::string ConcurrentCopying::DumpHeapReference(mirror::Object* obj,
2084 MemberOffset offset,
2085 mirror::Object* ref) {
2086 std::ostringstream oss;
Andreas Gampebc802de2018-06-20 17:24:11 -07002087 constexpr const char* kIndent = " ";
2088 oss << kIndent << "Invalid reference: ref=" << ref
Roland Levillain001eff92018-01-24 14:24:33 +00002089 << " referenced from: object=" << obj << " offset= " << offset << '\n';
2090 // Information about `obj`.
Andreas Gampebc802de2018-06-20 17:24:11 -07002091 oss << DumpReferenceInfo(obj, "obj", kIndent) << '\n';
Roland Levillain001eff92018-01-24 14:24:33 +00002092 // Information about `ref`.
Andreas Gampebc802de2018-06-20 17:24:11 -07002093 oss << DumpReferenceInfo(ref, "ref", kIndent);
Roland Levillain001eff92018-01-24 14:24:33 +00002094 return oss.str();
2095}
2096
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07002097void ConcurrentCopying::AssertToSpaceInvariant(mirror::Object* obj,
2098 MemberOffset offset,
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002099 mirror::Object* ref) {
Roland Levillain001eff92018-01-24 14:24:33 +00002100 CHECK_EQ(heap_->collector_type_, kCollectorTypeCC) << static_cast<size_t>(heap_->collector_type_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002101 if (is_asserting_to_space_invariant_) {
Roland Levillain001eff92018-01-24 14:24:33 +00002102 if (region_space_->HasAddress(ref)) {
2103 // Check to-space invariant in region space (moving space).
2104 using RegionType = space::RegionSpace::RegionType;
Roland Levillain2dd2e1e2018-02-28 16:24:51 +00002105 space::RegionSpace::RegionType type = region_space_->GetRegionTypeUnsafe(ref);
Roland Levillain001eff92018-01-24 14:24:33 +00002106 if (type == RegionType::kRegionTypeToSpace) {
2107 // OK.
2108 return;
2109 } else if (type == RegionType::kRegionTypeUnevacFromSpace) {
2110 if (!IsMarkedInUnevacFromSpace(ref)) {
2111 LOG(FATAL_WITHOUT_ABORT) << "Found unmarked reference in unevac from-space:";
Roland Levillainca3dded2018-08-10 15:35:17 +01002112 // Remove memory protection from the region space and log debugging information.
2113 region_space_->Unprotect();
Roland Levillain001eff92018-01-24 14:24:33 +00002114 LOG(FATAL_WITHOUT_ABORT) << DumpHeapReference(obj, offset, ref);
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002115 Thread::Current()->DumpJavaStack(LOG_STREAM(FATAL_WITHOUT_ABORT));
Roland Levillain001eff92018-01-24 14:24:33 +00002116 }
2117 CHECK(IsMarkedInUnevacFromSpace(ref)) << ref;
2118 } else {
2119 // Not OK: either a from-space ref or a reference in an unused region.
Roland Levillain001eff92018-01-24 14:24:33 +00002120 if (type == RegionType::kRegionTypeFromSpace) {
2121 LOG(FATAL_WITHOUT_ABORT) << "Found from-space reference:";
2122 } else {
2123 LOG(FATAL_WITHOUT_ABORT) << "Found reference in region with type " << type << ":";
2124 }
Roland Levillainca3dded2018-08-10 15:35:17 +01002125 // Remove memory protection from the region space and log debugging information.
2126 region_space_->Unprotect();
Roland Levillain001eff92018-01-24 14:24:33 +00002127 LOG(FATAL_WITHOUT_ABORT) << DumpHeapReference(obj, offset, ref);
2128 if (obj != nullptr) {
2129 LogFromSpaceRefHolder(obj, offset);
Roland Levillain57ce0542018-08-07 16:20:31 +01002130 LOG(FATAL_WITHOUT_ABORT) << "UNEVAC " << region_space_->IsInUnevacFromSpace(obj) << " "
2131 << obj << " " << obj->GetMarkBit();
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002132 if (region_space_->HasAddress(obj)) {
Roland Levillain57ce0542018-08-07 16:20:31 +01002133 region_space_->DumpRegionForObject(LOG_STREAM(FATAL_WITHOUT_ABORT), obj);
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002134 }
Roland Levillain57ce0542018-08-07 16:20:31 +01002135 LOG(FATAL_WITHOUT_ABORT) << "CARD " << static_cast<size_t>(
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002136 *Runtime::Current()->GetHeap()->GetCardTable()->CardFromAddr(
2137 reinterpret_cast<uint8_t*>(obj)));
Roland Levillain57ce0542018-08-07 16:20:31 +01002138 if (region_space_->HasAddress(obj)) {
2139 LOG(FATAL_WITHOUT_ABORT) << "BITMAP " << region_space_bitmap_->Test(obj);
2140 } else {
2141 accounting::ContinuousSpaceBitmap* mark_bitmap =
2142 heap_mark_bitmap_->GetContinuousSpaceBitmap(obj);
2143 if (mark_bitmap != nullptr) {
2144 LOG(FATAL_WITHOUT_ABORT) << "BITMAP " << mark_bitmap->Test(obj);
2145 } else {
2146 accounting::LargeObjectBitmap* los_bitmap =
2147 heap_mark_bitmap_->GetLargeObjectBitmap(obj);
2148 LOG(FATAL_WITHOUT_ABORT) << "BITMAP " << los_bitmap->Test(obj);
2149 }
2150 }
Roland Levillain001eff92018-01-24 14:24:33 +00002151 }
2152 ref->GetLockWord(false).Dump(LOG_STREAM(FATAL_WITHOUT_ABORT));
2153 LOG(FATAL_WITHOUT_ABORT) << "Non-free regions:";
2154 region_space_->DumpNonFreeRegions(LOG_STREAM(FATAL_WITHOUT_ABORT));
2155 PrintFileToLog("/proc/self/maps", LogSeverity::FATAL_WITHOUT_ABORT);
2156 MemMap::DumpMaps(LOG_STREAM(FATAL_WITHOUT_ABORT), true);
2157 LOG(FATAL) << "Invalid reference " << ref
2158 << " referenced from object " << obj << " at offset " << offset;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002159 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002160 } else {
Roland Levillain001eff92018-01-24 14:24:33 +00002161 // Check to-space invariant in non-moving space.
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002162 AssertToSpaceInvariantInNonMovingSpace(obj, ref);
2163 }
2164 }
2165}
2166
2167class RootPrinter {
2168 public:
2169 RootPrinter() { }
2170
2171 template <class MirrorType>
2172 ALWAYS_INLINE void VisitRootIfNonNull(mirror::CompressedReference<MirrorType>* root)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002173 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002174 if (!root->IsNull()) {
2175 VisitRoot(root);
2176 }
2177 }
2178
2179 template <class MirrorType>
2180 void VisitRoot(mirror::Object** root)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002181 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07002182 LOG(FATAL_WITHOUT_ABORT) << "root=" << root << " ref=" << *root;
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002183 }
2184
2185 template <class MirrorType>
2186 void VisitRoot(mirror::CompressedReference<MirrorType>* root)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002187 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07002188 LOG(FATAL_WITHOUT_ABORT) << "root=" << root << " ref=" << root->AsMirrorPtr();
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002189 }
2190};
2191
Roland Levillain001eff92018-01-24 14:24:33 +00002192std::string ConcurrentCopying::DumpGcRoot(mirror::Object* ref) {
2193 std::ostringstream oss;
Andreas Gampebc802de2018-06-20 17:24:11 -07002194 constexpr const char* kIndent = " ";
2195 oss << kIndent << "Invalid GC root: ref=" << ref << '\n';
Roland Levillain001eff92018-01-24 14:24:33 +00002196 // Information about `ref`.
Andreas Gampebc802de2018-06-20 17:24:11 -07002197 oss << DumpReferenceInfo(ref, "ref", kIndent);
Roland Levillain001eff92018-01-24 14:24:33 +00002198 return oss.str();
2199}
2200
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002201void ConcurrentCopying::AssertToSpaceInvariant(GcRootSource* gc_root_source,
2202 mirror::Object* ref) {
Roland Levillain001eff92018-01-24 14:24:33 +00002203 CHECK_EQ(heap_->collector_type_, kCollectorTypeCC) << static_cast<size_t>(heap_->collector_type_);
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002204 if (is_asserting_to_space_invariant_) {
Roland Levillain001eff92018-01-24 14:24:33 +00002205 if (region_space_->HasAddress(ref)) {
2206 // Check to-space invariant in region space (moving space).
2207 using RegionType = space::RegionSpace::RegionType;
Roland Levillain2dd2e1e2018-02-28 16:24:51 +00002208 space::RegionSpace::RegionType type = region_space_->GetRegionTypeUnsafe(ref);
Roland Levillain001eff92018-01-24 14:24:33 +00002209 if (type == RegionType::kRegionTypeToSpace) {
2210 // OK.
2211 return;
2212 } else if (type == RegionType::kRegionTypeUnevacFromSpace) {
2213 if (!IsMarkedInUnevacFromSpace(ref)) {
2214 LOG(FATAL_WITHOUT_ABORT) << "Found unmarked reference in unevac from-space:";
Roland Levillainca3dded2018-08-10 15:35:17 +01002215 // Remove memory protection from the region space and log debugging information.
2216 region_space_->Unprotect();
Roland Levillain001eff92018-01-24 14:24:33 +00002217 LOG(FATAL_WITHOUT_ABORT) << DumpGcRoot(ref);
2218 }
2219 CHECK(IsMarkedInUnevacFromSpace(ref)) << ref;
2220 } else {
2221 // Not OK: either a from-space ref or a reference in an unused region.
Roland Levillain001eff92018-01-24 14:24:33 +00002222 if (type == RegionType::kRegionTypeFromSpace) {
2223 LOG(FATAL_WITHOUT_ABORT) << "Found from-space reference:";
2224 } else {
2225 LOG(FATAL_WITHOUT_ABORT) << "Found reference in region with type " << type << ":";
2226 }
Roland Levillainca3dded2018-08-10 15:35:17 +01002227 // Remove memory protection from the region space and log debugging information.
2228 region_space_->Unprotect();
Roland Levillain001eff92018-01-24 14:24:33 +00002229 LOG(FATAL_WITHOUT_ABORT) << DumpGcRoot(ref);
2230 if (gc_root_source == nullptr) {
2231 // No info.
2232 } else if (gc_root_source->HasArtField()) {
2233 ArtField* field = gc_root_source->GetArtField();
2234 LOG(FATAL_WITHOUT_ABORT) << "gc root in field " << field << " "
2235 << ArtField::PrettyField(field);
2236 RootPrinter root_printer;
2237 field->VisitRoots(root_printer);
2238 } else if (gc_root_source->HasArtMethod()) {
2239 ArtMethod* method = gc_root_source->GetArtMethod();
2240 LOG(FATAL_WITHOUT_ABORT) << "gc root in method " << method << " "
2241 << ArtMethod::PrettyMethod(method);
2242 RootPrinter root_printer;
2243 method->VisitRoots(root_printer, kRuntimePointerSize);
2244 }
2245 ref->GetLockWord(false).Dump(LOG_STREAM(FATAL_WITHOUT_ABORT));
2246 LOG(FATAL_WITHOUT_ABORT) << "Non-free regions:";
2247 region_space_->DumpNonFreeRegions(LOG_STREAM(FATAL_WITHOUT_ABORT));
2248 PrintFileToLog("/proc/self/maps", LogSeverity::FATAL_WITHOUT_ABORT);
2249 MemMap::DumpMaps(LOG_STREAM(FATAL_WITHOUT_ABORT), true);
2250 LOG(FATAL) << "Invalid reference " << ref;
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002251 }
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002252 } else {
Roland Levillain001eff92018-01-24 14:24:33 +00002253 // Check to-space invariant in non-moving space.
2254 AssertToSpaceInvariantInNonMovingSpace(/* obj */ nullptr, ref);
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002255 }
2256 }
2257}
2258
2259void ConcurrentCopying::LogFromSpaceRefHolder(mirror::Object* obj, MemberOffset offset) {
2260 if (kUseBakerReadBarrier) {
David Sehr709b0702016-10-13 09:12:37 -07002261 LOG(INFO) << "holder=" << obj << " " << obj->PrettyTypeOf()
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002262 << " holder rb_state=" << obj->GetReadBarrierState();
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002263 } else {
David Sehr709b0702016-10-13 09:12:37 -07002264 LOG(INFO) << "holder=" << obj << " " << obj->PrettyTypeOf();
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002265 }
2266 if (region_space_->IsInFromSpace(obj)) {
2267 LOG(INFO) << "holder is in the from-space.";
2268 } else if (region_space_->IsInToSpace(obj)) {
2269 LOG(INFO) << "holder is in the to-space.";
2270 } else if (region_space_->IsInUnevacFromSpace(obj)) {
2271 LOG(INFO) << "holder is in the unevac from-space.";
Mathieu Chartierc381c362016-08-23 13:27:53 -07002272 if (IsMarkedInUnevacFromSpace(obj)) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002273 LOG(INFO) << "holder is marked in the region space bitmap.";
2274 } else {
2275 LOG(INFO) << "holder is not marked in the region space bitmap.";
2276 }
2277 } else {
2278 // In a non-moving space.
Mathieu Chartier763a31e2015-11-16 16:05:55 -08002279 if (immune_spaces_.ContainsObject(obj)) {
2280 LOG(INFO) << "holder is in an immune image or the zygote space.";
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002281 } else {
Mathieu Chartier763a31e2015-11-16 16:05:55 -08002282 LOG(INFO) << "holder is in a non-immune, non-moving (or main) space.";
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002283 accounting::ContinuousSpaceBitmap* mark_bitmap =
2284 heap_mark_bitmap_->GetContinuousSpaceBitmap(obj);
2285 accounting::LargeObjectBitmap* los_bitmap =
2286 heap_mark_bitmap_->GetLargeObjectBitmap(obj);
2287 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
2288 bool is_los = mark_bitmap == nullptr;
2289 if (!is_los && mark_bitmap->Test(obj)) {
2290 LOG(INFO) << "holder is marked in the mark bit map.";
2291 } else if (is_los && los_bitmap->Test(obj)) {
2292 LOG(INFO) << "holder is marked in the los bit map.";
2293 } else {
2294 // If ref is on the allocation stack, then it is considered
2295 // mark/alive (but not necessarily on the live stack.)
2296 if (IsOnAllocStack(obj)) {
2297 LOG(INFO) << "holder is on the alloc stack.";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002298 } else {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002299 LOG(INFO) << "holder is not marked or on the alloc stack.";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002300 }
2301 }
2302 }
2303 }
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002304 LOG(INFO) << "offset=" << offset.SizeValue();
2305}
2306
2307void ConcurrentCopying::AssertToSpaceInvariantInNonMovingSpace(mirror::Object* obj,
2308 mirror::Object* ref) {
Roland Levillain001eff92018-01-24 14:24:33 +00002309 CHECK(!region_space_->HasAddress(ref)) << "obj=" << obj << " ref=" << ref;
Roland Levillainef012222017-06-21 16:28:06 +01002310 // In a non-moving space. Check that the ref is marked.
Mathieu Chartier763a31e2015-11-16 16:05:55 -08002311 if (immune_spaces_.ContainsObject(ref)) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002312 if (kUseBakerReadBarrier) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002313 // Immune object may not be gray if called from the GC.
2314 if (Thread::Current() == thread_running_gc_ && !gc_grays_immune_objects_) {
2315 return;
2316 }
Orion Hodson88591fe2018-03-06 13:35:43 +00002317 bool updated_all_immune_objects = updated_all_immune_objects_.load(std::memory_order_seq_cst);
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002318 CHECK(updated_all_immune_objects || ref->GetReadBarrierState() == ReadBarrier::GrayState())
2319 << "Unmarked immune space ref. obj=" << obj << " rb_state="
2320 << (obj != nullptr ? obj->GetReadBarrierState() : 0U)
2321 << " ref=" << ref << " ref rb_state=" << ref->GetReadBarrierState()
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002322 << " updated_all_immune_objects=" << updated_all_immune_objects;
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002323 }
2324 } else {
2325 accounting::ContinuousSpaceBitmap* mark_bitmap =
2326 heap_mark_bitmap_->GetContinuousSpaceBitmap(ref);
2327 accounting::LargeObjectBitmap* los_bitmap =
2328 heap_mark_bitmap_->GetLargeObjectBitmap(ref);
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002329 bool is_los = mark_bitmap == nullptr;
2330 if ((!is_los && mark_bitmap->Test(ref)) ||
2331 (is_los && los_bitmap->Test(ref))) {
2332 // OK.
2333 } else {
Roland Levillain2ae376f2018-01-30 11:35:11 +00002334 // If `ref` is on the allocation stack, then it may not be
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002335 // marked live, but considered marked/alive (but not
2336 // necessarily on the live stack).
Roland Levillain2ae376f2018-01-30 11:35:11 +00002337 CHECK(IsOnAllocStack(ref)) << "Unmarked ref that's not on the allocation stack."
2338 << " obj=" << obj
2339 << " ref=" << ref
2340 << " is_los=" << std::boolalpha << is_los << std::noboolalpha;
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002341 }
2342 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002343}
2344
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002345// Used to scan ref fields of an object.
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002346template <bool kNoUnEvac>
Mathieu Chartiera07f5592016-06-16 11:44:28 -07002347class ConcurrentCopying::RefFieldsVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002348 public:
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002349 explicit RefFieldsVisitor(ConcurrentCopying* collector, Thread* const thread)
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002350 : collector_(collector), thread_(thread) {
2351 // Cannot have `kNoUnEvac` when Generational CC collection is disabled.
2352 DCHECK(kEnableGenerationalConcurrentCopyingCollection || !kNoUnEvac);
2353 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002354
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07002355 void operator()(mirror::Object* obj, MemberOffset offset, bool /* is_static */)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002356 const ALWAYS_INLINE REQUIRES_SHARED(Locks::mutator_lock_)
2357 REQUIRES_SHARED(Locks::heap_bitmap_lock_) {
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002358 collector_->Process<kNoUnEvac>(obj, offset);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002359 }
2360
Mathieu Chartier31e88222016-10-14 18:43:19 -07002361 void operator()(ObjPtr<mirror::Class> klass, ObjPtr<mirror::Reference> ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002362 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002363 CHECK(klass->IsTypeOfReferenceClass());
2364 collector_->DelayReferenceReferent(klass, ref);
2365 }
2366
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002367 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002368 ALWAYS_INLINE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002369 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002370 if (!root->IsNull()) {
2371 VisitRoot(root);
2372 }
2373 }
2374
2375 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002376 ALWAYS_INLINE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002377 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002378 collector_->MarkRoot</*kGrayImmuneObject*/false>(thread_, root);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002379 }
2380
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002381 private:
2382 ConcurrentCopying* const collector_;
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002383 Thread* const thread_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002384};
2385
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002386template <bool kNoUnEvac>
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002387inline void ConcurrentCopying::Scan(mirror::Object* to_ref) {
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002388 // Cannot have `kNoUnEvac` when Generational CC collection is disabled.
2389 DCHECK(kEnableGenerationalConcurrentCopyingCollection || !kNoUnEvac);
Hiroshi Yamauchi9b60d502017-02-03 15:09:26 -08002390 if (kDisallowReadBarrierDuringScan && !Runtime::Current()->IsActiveTransaction()) {
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07002391 // Avoid all read barriers during visit references to help performance.
Hiroshi Yamauchi9b60d502017-02-03 15:09:26 -08002392 // Don't do this in transaction mode because we may read the old value of an field which may
2393 // trigger read barriers.
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07002394 Thread::Current()->ModifyDebugDisallowReadBarrier(1);
2395 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002396 DCHECK(!region_space_->IsInFromSpace(to_ref));
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002397 DCHECK_EQ(Thread::Current(), thread_running_gc_);
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002398 RefFieldsVisitor<kNoUnEvac> visitor(this, thread_running_gc_);
Hiroshi Yamauchi5496f692016-02-17 13:29:59 -08002399 // Disable the read barrier for a performance reason.
2400 to_ref->VisitReferences</*kVisitNativeRoots*/true, kDefaultVerifyFlags, kWithoutReadBarrier>(
2401 visitor, visitor);
Hiroshi Yamauchi9b60d502017-02-03 15:09:26 -08002402 if (kDisallowReadBarrierDuringScan && !Runtime::Current()->IsActiveTransaction()) {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002403 thread_running_gc_->ModifyDebugDisallowReadBarrier(-1);
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07002404 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002405}
2406
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002407template <bool kNoUnEvac>
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002408inline void ConcurrentCopying::Process(mirror::Object* obj, MemberOffset offset) {
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002409 // Cannot have `kNoUnEvac` when Generational CC collection is disabled.
2410 DCHECK(kEnableGenerationalConcurrentCopyingCollection || !kNoUnEvac);
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002411 DCHECK_EQ(Thread::Current(), thread_running_gc_);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002412 mirror::Object* ref = obj->GetFieldObject<
2413 mirror::Object, kVerifyNone, kWithoutReadBarrier, false>(offset);
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002414 mirror::Object* to_ref = Mark</*kGrayImmuneObject*/false, kNoUnEvac, /*kFromGCThread*/true>(
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002415 thread_running_gc_,
Mathieu Chartier4ce0c762017-05-18 10:01:07 -07002416 ref,
2417 /*holder*/ obj,
2418 offset);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002419 if (to_ref == ref) {
2420 return;
2421 }
2422 // This may fail if the mutator writes to the field at the same time. But it's ok.
2423 mirror::Object* expected_ref = ref;
2424 mirror::Object* new_ref = to_ref;
2425 do {
2426 if (expected_ref !=
2427 obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier, false>(offset)) {
2428 // It was updated by the mutator.
2429 break;
2430 }
Roland Levillain2ae376f2018-01-30 11:35:11 +00002431 // Use release CAS to make sure threads reading the reference see contents of copied objects.
Mathieu Chartiera9746b92018-06-22 10:25:40 -07002432 } while (!obj->CasFieldObjectWithoutWriteBarrier<false, false, kVerifyNone>(
Mathieu Chartierfdd513d2017-06-01 11:26:50 -07002433 offset,
2434 expected_ref,
Mathieu Chartiera9746b92018-06-22 10:25:40 -07002435 new_ref,
2436 CASMode::kWeak,
2437 std::memory_order_release));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002438}
2439
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002440// Process some roots.
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002441inline void ConcurrentCopying::VisitRoots(
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002442 mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED) {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002443 Thread* const self = Thread::Current();
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002444 for (size_t i = 0; i < count; ++i) {
2445 mirror::Object** root = roots[i];
2446 mirror::Object* ref = *root;
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002447 mirror::Object* to_ref = Mark(self, ref);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002448 if (to_ref == ref) {
Mathieu Chartier4809d0a2015-04-07 10:39:04 -07002449 continue;
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002450 }
2451 Atomic<mirror::Object*>* addr = reinterpret_cast<Atomic<mirror::Object*>*>(root);
2452 mirror::Object* expected_ref = ref;
2453 mirror::Object* new_ref = to_ref;
2454 do {
Orion Hodson88591fe2018-03-06 13:35:43 +00002455 if (expected_ref != addr->load(std::memory_order_relaxed)) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002456 // It was updated by the mutator.
2457 break;
2458 }
Orion Hodson4557b382018-01-03 11:47:54 +00002459 } while (!addr->CompareAndSetWeakRelaxed(expected_ref, new_ref));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002460 }
2461}
2462
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002463template<bool kGrayImmuneObject>
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002464inline void ConcurrentCopying::MarkRoot(Thread* const self,
2465 mirror::CompressedReference<mirror::Object>* root) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002466 DCHECK(!root->IsNull());
2467 mirror::Object* const ref = root->AsMirrorPtr();
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002468 mirror::Object* to_ref = Mark<kGrayImmuneObject>(self, ref);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002469 if (to_ref != ref) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002470 auto* addr = reinterpret_cast<Atomic<mirror::CompressedReference<mirror::Object>>*>(root);
2471 auto expected_ref = mirror::CompressedReference<mirror::Object>::FromMirrorPtr(ref);
2472 auto new_ref = mirror::CompressedReference<mirror::Object>::FromMirrorPtr(to_ref);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002473 // If the cas fails, then it was updated by the mutator.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002474 do {
Orion Hodson88591fe2018-03-06 13:35:43 +00002475 if (ref != addr->load(std::memory_order_relaxed).AsMirrorPtr()) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002476 // It was updated by the mutator.
2477 break;
2478 }
Orion Hodson4557b382018-01-03 11:47:54 +00002479 } while (!addr->CompareAndSetWeakRelaxed(expected_ref, new_ref));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002480 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002481}
2482
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002483inline void ConcurrentCopying::VisitRoots(
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002484 mirror::CompressedReference<mirror::Object>** roots, size_t count,
2485 const RootInfo& info ATTRIBUTE_UNUSED) {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002486 Thread* const self = Thread::Current();
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002487 for (size_t i = 0; i < count; ++i) {
2488 mirror::CompressedReference<mirror::Object>* const root = roots[i];
2489 if (!root->IsNull()) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002490 // kGrayImmuneObject is true because this is used for the thread flip.
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002491 MarkRoot</*kGrayImmuneObject*/true>(self, root);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002492 }
2493 }
2494}
2495
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002496// Temporary set gc_grays_immune_objects_ to true in a scope if the current thread is GC.
2497class ConcurrentCopying::ScopedGcGraysImmuneObjects {
2498 public:
2499 explicit ScopedGcGraysImmuneObjects(ConcurrentCopying* collector)
2500 : collector_(collector), enabled_(false) {
2501 if (kUseBakerReadBarrier &&
2502 collector_->thread_running_gc_ == Thread::Current() &&
2503 !collector_->gc_grays_immune_objects_) {
2504 collector_->gc_grays_immune_objects_ = true;
2505 enabled_ = true;
2506 }
2507 }
2508
2509 ~ScopedGcGraysImmuneObjects() {
2510 if (kUseBakerReadBarrier &&
2511 collector_->thread_running_gc_ == Thread::Current() &&
2512 enabled_) {
2513 DCHECK(collector_->gc_grays_immune_objects_);
2514 collector_->gc_grays_immune_objects_ = false;
2515 }
2516 }
2517
2518 private:
2519 ConcurrentCopying* const collector_;
2520 bool enabled_;
2521};
2522
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002523// Fill the given memory block with a dummy object. Used to fill in a
2524// copy of objects that was lost in race.
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002525void ConcurrentCopying::FillWithDummyObject(Thread* const self,
2526 mirror::Object* dummy_obj,
2527 size_t byte_size) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002528 // GC doesn't gray immune objects while scanning immune objects. But we need to trigger the read
2529 // barriers here because we need the updated reference to the int array class, etc. Temporary set
2530 // gc_grays_immune_objects_ to true so that we won't cause a DCHECK failure in MarkImmuneSpace().
2531 ScopedGcGraysImmuneObjects scoped_gc_gray_immune_objects(this);
Roland Levillain14d90572015-07-16 10:52:26 +01002532 CHECK_ALIGNED(byte_size, kObjectAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002533 memset(dummy_obj, 0, byte_size);
Mathieu Chartierd6636d32016-07-28 11:02:38 -07002534 // Avoid going through read barrier for since kDisallowReadBarrierDuringScan may be enabled.
2535 // Explicitly mark to make sure to get an object in the to-space.
2536 mirror::Class* int_array_class = down_cast<mirror::Class*>(
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002537 Mark(self, GetClassRoot<mirror::IntArray, kWithoutReadBarrier>().Ptr()));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002538 CHECK(int_array_class != nullptr);
Andreas Gampe6c578712017-10-19 13:00:34 -07002539 if (ReadBarrier::kEnableToSpaceInvariantChecks) {
2540 AssertToSpaceInvariant(nullptr, MemberOffset(0), int_array_class);
2541 }
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07002542 size_t component_size = int_array_class->GetComponentSize<kWithoutReadBarrier>();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002543 CHECK_EQ(component_size, sizeof(int32_t));
2544 size_t data_offset = mirror::Array::DataOffset(component_size).SizeValue();
2545 if (data_offset > byte_size) {
2546 // An int array is too big. Use java.lang.Object.
Mathieu Chartier9aef9922017-04-23 13:53:50 -07002547 CHECK(java_lang_Object_ != nullptr);
Andreas Gampe6c578712017-10-19 13:00:34 -07002548 if (ReadBarrier::kEnableToSpaceInvariantChecks) {
2549 AssertToSpaceInvariant(nullptr, MemberOffset(0), java_lang_Object_);
2550 }
Mathieu Chartier3ed8ec12017-04-20 19:28:54 -07002551 CHECK_EQ(byte_size, (java_lang_Object_->GetObjectSize<kVerifyNone, kWithoutReadBarrier>()));
2552 dummy_obj->SetClass(java_lang_Object_);
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07002553 CHECK_EQ(byte_size, (dummy_obj->SizeOf<kVerifyNone>()));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002554 } else {
2555 // Use an int array.
2556 dummy_obj->SetClass(int_array_class);
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07002557 CHECK((dummy_obj->IsArrayInstance<kVerifyNone, kWithoutReadBarrier>()));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002558 int32_t length = (byte_size - data_offset) / component_size;
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07002559 mirror::Array* dummy_arr = dummy_obj->AsArray<kVerifyNone, kWithoutReadBarrier>();
2560 dummy_arr->SetLength(length);
2561 CHECK_EQ(dummy_arr->GetLength(), length)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002562 << "byte_size=" << byte_size << " length=" << length
2563 << " component_size=" << component_size << " data_offset=" << data_offset;
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07002564 CHECK_EQ(byte_size, (dummy_obj->SizeOf<kVerifyNone>()))
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002565 << "byte_size=" << byte_size << " length=" << length
2566 << " component_size=" << component_size << " data_offset=" << data_offset;
2567 }
2568}
2569
2570// Reuse the memory blocks that were copy of objects that were lost in race.
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002571mirror::Object* ConcurrentCopying::AllocateInSkippedBlock(Thread* const self, size_t alloc_size) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002572 // Try to reuse the blocks that were unused due to CAS failures.
Roland Levillain14d90572015-07-16 10:52:26 +01002573 CHECK_ALIGNED(alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002574 size_t min_object_size = RoundUp(sizeof(mirror::Object), space::RegionSpace::kAlignment);
Mathieu Chartierd6636d32016-07-28 11:02:38 -07002575 size_t byte_size;
2576 uint8_t* addr;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002577 {
Mathieu Chartierd6636d32016-07-28 11:02:38 -07002578 MutexLock mu(self, skipped_blocks_lock_);
2579 auto it = skipped_blocks_map_.lower_bound(alloc_size);
2580 if (it == skipped_blocks_map_.end()) {
2581 // Not found.
2582 return nullptr;
2583 }
2584 byte_size = it->first;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002585 CHECK_GE(byte_size, alloc_size);
2586 if (byte_size > alloc_size && byte_size - alloc_size < min_object_size) {
2587 // If remainder would be too small for a dummy object, retry with a larger request size.
2588 it = skipped_blocks_map_.lower_bound(alloc_size + min_object_size);
2589 if (it == skipped_blocks_map_.end()) {
2590 // Not found.
2591 return nullptr;
2592 }
Roland Levillain14d90572015-07-16 10:52:26 +01002593 CHECK_ALIGNED(it->first - alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002594 CHECK_GE(it->first - alloc_size, min_object_size)
2595 << "byte_size=" << byte_size << " it->first=" << it->first << " alloc_size=" << alloc_size;
2596 }
Mathieu Chartierd6636d32016-07-28 11:02:38 -07002597 // Found a block.
2598 CHECK(it != skipped_blocks_map_.end());
2599 byte_size = it->first;
2600 addr = it->second;
2601 CHECK_GE(byte_size, alloc_size);
2602 CHECK(region_space_->IsInToSpace(reinterpret_cast<mirror::Object*>(addr)));
2603 CHECK_ALIGNED(byte_size, space::RegionSpace::kAlignment);
2604 if (kVerboseMode) {
2605 LOG(INFO) << "Reusing skipped bytes : " << reinterpret_cast<void*>(addr) << ", " << byte_size;
2606 }
2607 skipped_blocks_map_.erase(it);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002608 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002609 memset(addr, 0, byte_size);
2610 if (byte_size > alloc_size) {
2611 // Return the remainder to the map.
Roland Levillain14d90572015-07-16 10:52:26 +01002612 CHECK_ALIGNED(byte_size - alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002613 CHECK_GE(byte_size - alloc_size, min_object_size);
Mathieu Chartierd6636d32016-07-28 11:02:38 -07002614 // FillWithDummyObject may mark an object, avoid holding skipped_blocks_lock_ to prevent lock
2615 // violation and possible deadlock. The deadlock case is a recursive case:
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002616 // FillWithDummyObject -> Mark(IntArray.class) -> Copy -> AllocateInSkippedBlock.
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002617 FillWithDummyObject(self,
2618 reinterpret_cast<mirror::Object*>(addr + alloc_size),
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002619 byte_size - alloc_size);
2620 CHECK(region_space_->IsInToSpace(reinterpret_cast<mirror::Object*>(addr + alloc_size)));
Mathieu Chartierd6636d32016-07-28 11:02:38 -07002621 {
2622 MutexLock mu(self, skipped_blocks_lock_);
2623 skipped_blocks_map_.insert(std::make_pair(byte_size - alloc_size, addr + alloc_size));
2624 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002625 }
2626 return reinterpret_cast<mirror::Object*>(addr);
2627}
2628
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002629mirror::Object* ConcurrentCopying::Copy(Thread* const self,
2630 mirror::Object* from_ref,
Mathieu Chartieref496d92017-04-28 18:58:59 -07002631 mirror::Object* holder,
2632 MemberOffset offset) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002633 DCHECK(region_space_->IsInFromSpace(from_ref));
Mathieu Chartieref496d92017-04-28 18:58:59 -07002634 // If the class pointer is null, the object is invalid. This could occur for a dangling pointer
2635 // from a previous GC that is either inside or outside the allocated region.
2636 mirror::Class* klass = from_ref->GetClass<kVerifyNone, kWithoutReadBarrier>();
2637 if (UNLIKELY(klass == nullptr)) {
Roland Levillainca3dded2018-08-10 15:35:17 +01002638 // Remove memory protection from the region space and log debugging information.
2639 region_space_->Unprotect();
Mathieu Chartieref496d92017-04-28 18:58:59 -07002640 heap_->GetVerification()->LogHeapCorruption(holder, offset, from_ref, /* fatal */ true);
2641 }
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07002642 // There must not be a read barrier to avoid nested RB that might violate the to-space invariant.
2643 // Note that from_ref is a from space ref so the SizeOf() call will access the from-space meta
2644 // objects, but it's ok and necessary.
2645 size_t obj_size = from_ref->SizeOf<kDefaultVerifyFlags>();
Nicolas Geoffray4b361a82017-07-06 15:30:10 +01002646 size_t region_space_alloc_size = (obj_size <= space::RegionSpace::kRegionSize)
2647 ? RoundUp(obj_size, space::RegionSpace::kAlignment)
2648 : RoundUp(obj_size, space::RegionSpace::kRegionSize);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002649 size_t region_space_bytes_allocated = 0U;
2650 size_t non_moving_space_bytes_allocated = 0U;
2651 size_t bytes_allocated = 0U;
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07002652 size_t dummy;
Lokesh Gidraf2a69312018-03-27 18:48:59 -07002653 bool fall_back_to_non_moving = false;
Lokesh Gidrab4f15412018-01-05 18:29:34 -08002654 mirror::Object* to_ref = region_space_->AllocNonvirtual</*kForEvac*/ true>(
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07002655 region_space_alloc_size, &region_space_bytes_allocated, nullptr, &dummy);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002656 bytes_allocated = region_space_bytes_allocated;
Lokesh Gidraf2a69312018-03-27 18:48:59 -07002657 if (LIKELY(to_ref != nullptr)) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002658 DCHECK_EQ(region_space_alloc_size, region_space_bytes_allocated);
Lokesh Gidraf2a69312018-03-27 18:48:59 -07002659 } else {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002660 // Failed to allocate in the region space. Try the skipped blocks.
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002661 to_ref = AllocateInSkippedBlock(self, region_space_alloc_size);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002662 if (to_ref != nullptr) {
2663 // Succeeded to allocate in a skipped block.
2664 if (heap_->use_tlab_) {
2665 // This is necessary for the tlab case as it's not accounted in the space.
2666 region_space_->RecordAlloc(to_ref);
2667 }
2668 bytes_allocated = region_space_alloc_size;
Lokesh Gidraf2a69312018-03-27 18:48:59 -07002669 heap_->num_bytes_allocated_.fetch_sub(bytes_allocated, std::memory_order_seq_cst);
2670 to_space_bytes_skipped_.fetch_sub(bytes_allocated, std::memory_order_seq_cst);
2671 to_space_objects_skipped_.fetch_sub(1, std::memory_order_seq_cst);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002672 } else {
2673 // Fall back to the non-moving space.
2674 fall_back_to_non_moving = true;
2675 if (kVerboseMode) {
2676 LOG(INFO) << "Out of memory in the to-space. Fall back to non-moving. skipped_bytes="
Orion Hodson88591fe2018-03-06 13:35:43 +00002677 << to_space_bytes_skipped_.load(std::memory_order_seq_cst)
2678 << " skipped_objects="
2679 << to_space_objects_skipped_.load(std::memory_order_seq_cst);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002680 }
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002681 to_ref = heap_->non_moving_space_->Alloc(self, obj_size,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07002682 &non_moving_space_bytes_allocated, nullptr, &dummy);
Mathieu Chartierb01335c2017-03-22 13:15:01 -07002683 if (UNLIKELY(to_ref == nullptr)) {
2684 LOG(FATAL_WITHOUT_ABORT) << "Fall-back non-moving space allocation failed for a "
2685 << obj_size << " byte object in region type "
2686 << region_space_->GetRegionType(from_ref);
2687 LOG(FATAL) << "Object address=" << from_ref << " type=" << from_ref->PrettyTypeOf();
2688 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002689 bytes_allocated = non_moving_space_bytes_allocated;
2690 // Mark it in the mark bitmap.
2691 accounting::ContinuousSpaceBitmap* mark_bitmap =
2692 heap_mark_bitmap_->GetContinuousSpaceBitmap(to_ref);
2693 CHECK(mark_bitmap != nullptr);
Roland Levillain5c54d862018-01-17 14:46:24 +00002694 bool previously_marked_in_bitmap = mark_bitmap->AtomicTestAndSet(to_ref);
2695 CHECK(!previously_marked_in_bitmap);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002696 }
2697 }
2698 DCHECK(to_ref != nullptr);
2699
Mathieu Chartierd818adb2016-09-15 13:12:47 -07002700 // Copy the object excluding the lock word since that is handled in the loop.
Mathieu Chartieref496d92017-04-28 18:58:59 -07002701 to_ref->SetClass(klass);
Mathieu Chartierd818adb2016-09-15 13:12:47 -07002702 const size_t kObjectHeaderSize = sizeof(mirror::Object);
2703 DCHECK_GE(obj_size, kObjectHeaderSize);
2704 static_assert(kObjectHeaderSize == sizeof(mirror::HeapReference<mirror::Class>) +
2705 sizeof(LockWord),
2706 "Object header size does not match");
2707 // Memcpy can tear for words since it may do byte copy. It is only safe to do this since the
2708 // object in the from space is immutable other than the lock word. b/31423258
2709 memcpy(reinterpret_cast<uint8_t*>(to_ref) + kObjectHeaderSize,
2710 reinterpret_cast<const uint8_t*>(from_ref) + kObjectHeaderSize,
2711 obj_size - kObjectHeaderSize);
2712
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002713 // Attempt to install the forward pointer. This is in a loop as the
2714 // lock word atomic write can fail.
2715 while (true) {
Mathieu Chartierd818adb2016-09-15 13:12:47 -07002716 LockWord old_lock_word = from_ref->GetLockWord(false);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002717
2718 if (old_lock_word.GetState() == LockWord::kForwardingAddress) {
2719 // Lost the race. Another thread (either GC or mutator) stored
2720 // the forwarding pointer first. Make the lost copy (to_ref)
2721 // look like a valid but dead (dummy) object and keep it for
2722 // future reuse.
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002723 FillWithDummyObject(self, to_ref, bytes_allocated);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002724 if (!fall_back_to_non_moving) {
2725 DCHECK(region_space_->IsInToSpace(to_ref));
2726 if (bytes_allocated > space::RegionSpace::kRegionSize) {
2727 // Free the large alloc.
Lokesh Gidrab4f15412018-01-05 18:29:34 -08002728 region_space_->FreeLarge</*kForEvac*/ true>(to_ref, bytes_allocated);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002729 } else {
2730 // Record the lost copy for later reuse.
Orion Hodson88591fe2018-03-06 13:35:43 +00002731 heap_->num_bytes_allocated_.fetch_add(bytes_allocated, std::memory_order_seq_cst);
2732 to_space_bytes_skipped_.fetch_add(bytes_allocated, std::memory_order_seq_cst);
2733 to_space_objects_skipped_.fetch_add(1, std::memory_order_seq_cst);
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002734 MutexLock mu(self, skipped_blocks_lock_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002735 skipped_blocks_map_.insert(std::make_pair(bytes_allocated,
2736 reinterpret_cast<uint8_t*>(to_ref)));
2737 }
2738 } else {
2739 DCHECK(heap_->non_moving_space_->HasAddress(to_ref));
2740 DCHECK_EQ(bytes_allocated, non_moving_space_bytes_allocated);
2741 // Free the non-moving-space chunk.
2742 accounting::ContinuousSpaceBitmap* mark_bitmap =
2743 heap_mark_bitmap_->GetContinuousSpaceBitmap(to_ref);
2744 CHECK(mark_bitmap != nullptr);
2745 CHECK(mark_bitmap->Clear(to_ref));
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002746 heap_->non_moving_space_->Free(self, to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002747 }
2748
2749 // Get the winner's forward ptr.
2750 mirror::Object* lost_fwd_ptr = to_ref;
2751 to_ref = reinterpret_cast<mirror::Object*>(old_lock_word.ForwardingAddress());
2752 CHECK(to_ref != nullptr);
2753 CHECK_NE(to_ref, lost_fwd_ptr);
Mathieu Chartierdfcd6f42016-09-13 10:02:48 -07002754 CHECK(region_space_->IsInToSpace(to_ref) || heap_->non_moving_space_->HasAddress(to_ref))
2755 << "to_ref=" << to_ref << " " << heap_->DumpSpaces();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002756 CHECK_NE(to_ref->GetLockWord(false).GetState(), LockWord::kForwardingAddress);
2757 return to_ref;
2758 }
2759
Mathieu Chartierd818adb2016-09-15 13:12:47 -07002760 // Copy the old lock word over since we did not copy it yet.
2761 to_ref->SetLockWord(old_lock_word, false);
Hiroshi Yamauchi60f63f52015-04-23 16:12:40 -07002762 // Set the gray ptr.
2763 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002764 to_ref->SetReadBarrierState(ReadBarrier::GrayState());
Hiroshi Yamauchi60f63f52015-04-23 16:12:40 -07002765 }
2766
Mathieu Chartiera8131262016-11-29 17:55:19 -08002767 // Do a fence to prevent the field CAS in ConcurrentCopying::Process from possibly reordering
2768 // before the object copy.
Orion Hodson27b96762018-03-13 16:06:57 +00002769 std::atomic_thread_fence(std::memory_order_release);
Mathieu Chartiera8131262016-11-29 17:55:19 -08002770
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002771 LockWord new_lock_word = LockWord::FromForwardingAddress(reinterpret_cast<size_t>(to_ref));
2772
2773 // Try to atomically write the fwd ptr.
Mathieu Chartier42c2e502018-06-19 12:30:56 -07002774 bool success = from_ref->CasLockWord(old_lock_word,
2775 new_lock_word,
2776 CASMode::kWeak,
2777 std::memory_order_relaxed);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002778 if (LIKELY(success)) {
2779 // The CAS succeeded.
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002780 DCHECK(thread_running_gc_ != nullptr);
2781 if (LIKELY(self == thread_running_gc_)) {
2782 objects_moved_gc_thread_ += 1;
2783 bytes_moved_gc_thread_ += region_space_alloc_size;
2784 } else {
2785 objects_moved_.fetch_add(1, std::memory_order_relaxed);
2786 bytes_moved_.fetch_add(region_space_alloc_size, std::memory_order_relaxed);
2787 }
2788
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002789 if (LIKELY(!fall_back_to_non_moving)) {
2790 DCHECK(region_space_->IsInToSpace(to_ref));
2791 } else {
2792 DCHECK(heap_->non_moving_space_->HasAddress(to_ref));
2793 DCHECK_EQ(bytes_allocated, non_moving_space_bytes_allocated);
2794 }
2795 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002796 DCHECK(to_ref->GetReadBarrierState() == ReadBarrier::GrayState());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002797 }
2798 DCHECK(GetFwdPtr(from_ref) == to_ref);
2799 CHECK_NE(to_ref->GetLockWord(false).GetState(), LockWord::kForwardingAddress);
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002800 PushOntoMarkStack(self, to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002801 return to_ref;
2802 } else {
2803 // The CAS failed. It may have lost the race or may have failed
2804 // due to monitor/hashcode ops. Either way, retry.
2805 }
2806 }
2807}
2808
2809mirror::Object* ConcurrentCopying::IsMarked(mirror::Object* from_ref) {
2810 DCHECK(from_ref != nullptr);
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08002811 space::RegionSpace::RegionType rtype = region_space_->GetRegionType(from_ref);
2812 if (rtype == space::RegionSpace::RegionType::kRegionTypeToSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002813 // It's already marked.
2814 return from_ref;
2815 }
2816 mirror::Object* to_ref;
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08002817 if (rtype == space::RegionSpace::RegionType::kRegionTypeFromSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002818 to_ref = GetFwdPtr(from_ref);
2819 DCHECK(to_ref == nullptr || region_space_->IsInToSpace(to_ref) ||
2820 heap_->non_moving_space_->HasAddress(to_ref))
2821 << "from_ref=" << from_ref << " to_ref=" << to_ref;
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08002822 } else if (rtype == space::RegionSpace::RegionType::kRegionTypeUnevacFromSpace) {
Mathieu Chartierc381c362016-08-23 13:27:53 -07002823 if (IsMarkedInUnevacFromSpace(from_ref)) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002824 to_ref = from_ref;
2825 } else {
2826 to_ref = nullptr;
2827 }
2828 } else {
Roland Levillain001eff92018-01-24 14:24:33 +00002829 // At this point, `from_ref` should not be in the region space
2830 // (i.e. within an "unused" region).
2831 DCHECK(!region_space_->HasAddress(from_ref)) << from_ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002832 // from_ref is in a non-moving space.
Mathieu Chartier763a31e2015-11-16 16:05:55 -08002833 if (immune_spaces_.ContainsObject(from_ref)) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002834 // An immune object is alive.
2835 to_ref = from_ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002836 } else {
2837 // Non-immune non-moving space. Use the mark bitmap.
2838 accounting::ContinuousSpaceBitmap* mark_bitmap =
2839 heap_mark_bitmap_->GetContinuousSpaceBitmap(from_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002840 bool is_los = mark_bitmap == nullptr;
2841 if (!is_los && mark_bitmap->Test(from_ref)) {
2842 // Already marked.
2843 to_ref = from_ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002844 } else {
Mathieu Chartier47863bb2017-08-04 11:30:27 -07002845 accounting::LargeObjectBitmap* los_bitmap =
2846 heap_mark_bitmap_->GetLargeObjectBitmap(from_ref);
2847 // We may not have a large object space for dex2oat, don't assume it exists.
2848 if (los_bitmap == nullptr) {
2849 CHECK(heap_->GetLargeObjectsSpace() == nullptr)
2850 << "LOS bitmap covers the entire address range " << from_ref
2851 << " " << heap_->DumpSpaces();
2852 }
2853 if (los_bitmap != nullptr && is_los && los_bitmap->Test(from_ref)) {
2854 // Already marked in LOS.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002855 to_ref = from_ref;
2856 } else {
2857 // Not marked.
Mathieu Chartier47863bb2017-08-04 11:30:27 -07002858 if (IsOnAllocStack(from_ref)) {
2859 // If on the allocation stack, it's considered marked.
2860 to_ref = from_ref;
2861 } else {
2862 // Not marked.
2863 to_ref = nullptr;
2864 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002865 }
2866 }
2867 }
2868 }
2869 return to_ref;
2870}
2871
2872bool ConcurrentCopying::IsOnAllocStack(mirror::Object* ref) {
Hans Boehmcc55e1d2017-07-27 15:28:07 -07002873 // TODO: Explain why this is here. What release operation does it pair with?
Orion Hodson27b96762018-03-13 16:06:57 +00002874 std::atomic_thread_fence(std::memory_order_acquire);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002875 accounting::ObjectStack* alloc_stack = GetAllocationStack();
Mathieu Chartiercb535da2015-01-23 13:50:03 -08002876 return alloc_stack->Contains(ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002877}
2878
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002879mirror::Object* ConcurrentCopying::MarkNonMoving(Thread* const self,
2880 mirror::Object* ref,
Mathieu Chartier1ca68902017-04-18 11:26:22 -07002881 mirror::Object* holder,
2882 MemberOffset offset) {
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002883 // ref is in a non-moving space (from_ref == to_ref).
2884 DCHECK(!region_space_->HasAddress(ref)) << ref;
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002885 DCHECK(!immune_spaces_.ContainsObject(ref));
2886 // Use the mark bitmap.
2887 accounting::ContinuousSpaceBitmap* mark_bitmap =
2888 heap_mark_bitmap_->GetContinuousSpaceBitmap(ref);
2889 accounting::LargeObjectBitmap* los_bitmap =
2890 heap_mark_bitmap_->GetLargeObjectBitmap(ref);
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002891 bool is_los = mark_bitmap == nullptr;
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002892 if (kEnableGenerationalConcurrentCopyingCollection && young_gen_) {
Roland Levillainade74a62018-08-08 15:55:42 +01002893 // The sticky-bit CC collector is only compatible with Baker-style read barriers.
2894 DCHECK(kUseBakerReadBarrier);
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002895 // Not done scanning, use AtomicSetReadBarrierPointer.
2896 if (!done_scanning_) {
2897 // 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 +01002898 // mutator may see references to the from space. Instead, use the Baker pointer itself as
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002899 // the mark bit.
2900 if (ref->AtomicSetReadBarrierState(ReadBarrier::NonGrayState(), ReadBarrier::GrayState())) {
2901 // TODO: We don't actually need to scan this object later, we just need to clear the gray
2902 // bit.
2903 // Also make sure the object is marked.
2904 if (is_los) {
2905 los_bitmap->AtomicTestAndSet(ref);
2906 } else {
2907 mark_bitmap->AtomicTestAndSet(ref);
2908 }
2909 PushOntoMarkStack(self, ref);
2910 }
2911 return ref;
2912 }
2913 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002914 if (!is_los && mark_bitmap->Test(ref)) {
2915 // Already marked.
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002916 } else if (is_los && los_bitmap->Test(ref)) {
2917 // Already marked in LOS.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002918 } else {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002919 // Not marked.
2920 if (IsOnAllocStack(ref)) {
Roland Levillain14e5a292018-06-28 12:00:56 +01002921 // If it's on the allocation stack, it's considered marked. Keep it white (non-gray).
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002922 // Objects on the allocation stack need not be marked.
2923 if (!is_los) {
2924 DCHECK(!mark_bitmap->Test(ref));
2925 } else {
2926 DCHECK(!los_bitmap->Test(ref));
Nicolas Geoffrayddeb1722016-06-28 08:25:59 +00002927 }
Nicolas Geoffrayddeb1722016-06-28 08:25:59 +00002928 if (kUseBakerReadBarrier) {
Roland Levillain14e5a292018-06-28 12:00:56 +01002929 DCHECK_EQ(ref->GetReadBarrierState(), ReadBarrier::NonGrayState());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002930 }
2931 } else {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002932 // For the baker-style RB, we need to handle 'false-gray' cases. See the
2933 // kRegionTypeUnevacFromSpace-case comment in Mark().
2934 if (kUseBakerReadBarrier) {
2935 // Test the bitmap first to reduce the chance of false gray cases.
2936 if ((!is_los && mark_bitmap->Test(ref)) ||
2937 (is_los && los_bitmap->Test(ref))) {
2938 return ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002939 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002940 }
Mathieu Chartier1ca68902017-04-18 11:26:22 -07002941 if (is_los && !IsAligned<kPageSize>(ref)) {
Roland Levillainca3dded2018-08-10 15:35:17 +01002942 // Ref is a large object that is not aligned, it must be heap
2943 // corruption. Remove memory protection and dump data before
2944 // AtomicSetReadBarrierState since it will fault if the address is not
2945 // valid.
2946 region_space_->Unprotect();
Mathieu Chartieref496d92017-04-28 18:58:59 -07002947 heap_->GetVerification()->LogHeapCorruption(holder, offset, ref, /* fatal */ true);
Mathieu Chartier1ca68902017-04-18 11:26:22 -07002948 }
Roland Levillain14e5a292018-06-28 12:00:56 +01002949 // Not marked nor on the allocation stack. Try to mark it.
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002950 // This may or may not succeed, which is ok.
2951 bool cas_success = false;
2952 if (kUseBakerReadBarrier) {
Roland Levillain14e5a292018-06-28 12:00:56 +01002953 cas_success = ref->AtomicSetReadBarrierState(ReadBarrier::NonGrayState(),
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002954 ReadBarrier::GrayState());
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002955 }
2956 if (!is_los && mark_bitmap->AtomicTestAndSet(ref)) {
2957 // Already marked.
Roland Levillain14e5a292018-06-28 12:00:56 +01002958 if (kUseBakerReadBarrier &&
2959 cas_success &&
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002960 ref->GetReadBarrierState() == ReadBarrier::GrayState()) {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002961 PushOntoFalseGrayStack(self, ref);
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002962 }
2963 } else if (is_los && los_bitmap->AtomicTestAndSet(ref)) {
2964 // Already marked in LOS.
Roland Levillain14e5a292018-06-28 12:00:56 +01002965 if (kUseBakerReadBarrier &&
2966 cas_success &&
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002967 ref->GetReadBarrierState() == ReadBarrier::GrayState()) {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002968 PushOntoFalseGrayStack(self, ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002969 }
2970 } else {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002971 // Newly marked.
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08002972 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002973 DCHECK_EQ(ref->GetReadBarrierState(), ReadBarrier::GrayState());
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08002974 }
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002975 PushOntoMarkStack(self, ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002976 }
2977 }
2978 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002979 return ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002980}
2981
2982void ConcurrentCopying::FinishPhase() {
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -08002983 Thread* const self = Thread::Current();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002984 {
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -08002985 MutexLock mu(self, mark_stack_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002986 CHECK_EQ(pooled_mark_stacks_.size(), kMarkStackPoolSize);
2987 }
Mathieu Chartiera1467d02017-02-22 09:22:50 -08002988 // kVerifyNoMissingCardMarks relies on the region space cards not being cleared to avoid false
2989 // positives.
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002990 if (!kEnableGenerationalConcurrentCopyingCollection && !kVerifyNoMissingCardMarks) {
Mathieu Chartier6e6078a2016-10-24 15:45:41 -07002991 TimingLogger::ScopedTiming split("ClearRegionSpaceCards", GetTimings());
2992 // We do not currently use the region space cards at all, madvise them away to save ram.
2993 heap_->GetCardTable()->ClearCardRange(region_space_->Begin(), region_space_->Limit());
Mathieu Chartier6e6078a2016-10-24 15:45:41 -07002994 }
2995 {
2996 MutexLock mu(self, skipped_blocks_lock_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002997 skipped_blocks_map_.clear();
2998 }
Mathieu Chartier56fe2582016-07-14 13:30:03 -07002999 {
3000 ReaderMutexLock mu(self, *Locks::mutator_lock_);
Mathieu Chartier21328a12016-07-22 10:47:45 -07003001 {
3002 WriterMutexLock mu2(self, *Locks::heap_bitmap_lock_);
3003 heap_->ClearMarkedObjects();
3004 }
3005 if (kUseBakerReadBarrier && kFilterModUnionCards) {
3006 TimingLogger::ScopedTiming split("FilterModUnionCards", GetTimings());
3007 ReaderMutexLock mu2(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier21328a12016-07-22 10:47:45 -07003008 for (space::ContinuousSpace* space : immune_spaces_.GetSpaces()) {
3009 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
Mathieu Chartier6e6078a2016-10-24 15:45:41 -07003010 accounting::ModUnionTable* table = heap_->FindModUnionTableFromSpace(space);
Mathieu Chartier21328a12016-07-22 10:47:45 -07003011 // Filter out cards that don't need to be set.
3012 if (table != nullptr) {
3013 table->FilterCards();
3014 }
3015 }
3016 }
Mathieu Chartier36a270a2016-07-28 18:08:51 -07003017 if (kUseBakerReadBarrier) {
3018 TimingLogger::ScopedTiming split("EmptyRBMarkBitStack", GetTimings());
Mathieu Chartier6e6078a2016-10-24 15:45:41 -07003019 DCHECK(rb_mark_bit_stack_ != nullptr);
Mathieu Chartier36a270a2016-07-28 18:08:51 -07003020 const auto* limit = rb_mark_bit_stack_->End();
3021 for (StackReference<mirror::Object>* it = rb_mark_bit_stack_->Begin(); it != limit; ++it) {
Roland Levillain001eff92018-01-24 14:24:33 +00003022 CHECK(it->AsMirrorPtr()->AtomicSetMarkBit(1, 0))
3023 << "rb_mark_bit_stack_->Begin()" << rb_mark_bit_stack_->Begin() << '\n'
3024 << "rb_mark_bit_stack_->End()" << rb_mark_bit_stack_->End() << '\n'
3025 << "rb_mark_bit_stack_->IsFull()"
3026 << std::boolalpha << rb_mark_bit_stack_->IsFull() << std::noboolalpha << '\n'
3027 << DumpReferenceInfo(it->AsMirrorPtr(), "*it");
Mathieu Chartier36a270a2016-07-28 18:08:51 -07003028 }
3029 rb_mark_bit_stack_->Reset();
3030 }
Mathieu Chartier56fe2582016-07-14 13:30:03 -07003031 }
3032 if (measure_read_barrier_slow_path_) {
3033 MutexLock mu(self, rb_slow_path_histogram_lock_);
Orion Hodson88591fe2018-03-06 13:35:43 +00003034 rb_slow_path_time_histogram_.AdjustAndAddValue(
3035 rb_slow_path_ns_.load(std::memory_order_relaxed));
3036 rb_slow_path_count_total_ += rb_slow_path_count_.load(std::memory_order_relaxed);
3037 rb_slow_path_count_gc_total_ += rb_slow_path_count_gc_.load(std::memory_order_relaxed);
Mathieu Chartier56fe2582016-07-14 13:30:03 -07003038 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003039}
3040
Hiroshi Yamauchi65f5f242016-12-19 11:44:47 -08003041bool ConcurrentCopying::IsNullOrMarkedHeapReference(mirror::HeapReference<mirror::Object>* field,
3042 bool do_atomic_update) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003043 mirror::Object* from_ref = field->AsMirrorPtr();
Hiroshi Yamauchi65f5f242016-12-19 11:44:47 -08003044 if (from_ref == nullptr) {
3045 return true;
3046 }
Mathieu Chartier97509952015-07-13 14:35:43 -07003047 mirror::Object* to_ref = IsMarked(from_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003048 if (to_ref == nullptr) {
3049 return false;
3050 }
3051 if (from_ref != to_ref) {
Hiroshi Yamauchi65f5f242016-12-19 11:44:47 -08003052 if (do_atomic_update) {
3053 do {
3054 if (field->AsMirrorPtr() != from_ref) {
3055 // Concurrently overwritten by a mutator.
3056 break;
3057 }
3058 } while (!field->CasWeakRelaxed(from_ref, to_ref));
3059 } else {
Hans Boehmcc55e1d2017-07-27 15:28:07 -07003060 // TODO: Why is this seq_cst when the above is relaxed? Document memory ordering.
3061 field->Assign</* kIsVolatile */ true>(to_ref);
Hiroshi Yamauchi65f5f242016-12-19 11:44:47 -08003062 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003063 }
3064 return true;
3065}
3066
Mathieu Chartier97509952015-07-13 14:35:43 -07003067mirror::Object* ConcurrentCopying::MarkObject(mirror::Object* from_ref) {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08003068 return Mark(Thread::Current(), from_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003069}
3070
Mathieu Chartier31e88222016-10-14 18:43:19 -07003071void ConcurrentCopying::DelayReferenceReferent(ObjPtr<mirror::Class> klass,
3072 ObjPtr<mirror::Reference> reference) {
Mathieu Chartier97509952015-07-13 14:35:43 -07003073 heap_->GetReferenceProcessor()->DelayReferenceReferent(klass, reference, this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003074}
3075
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07003076void ConcurrentCopying::ProcessReferences(Thread* self) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003077 TimingLogger::ScopedTiming split("ProcessReferences", GetTimings());
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07003078 // 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 -08003079 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
3080 GetHeap()->GetReferenceProcessor()->ProcessReferences(
Mathieu Chartier97509952015-07-13 14:35:43 -07003081 true /*concurrent*/, GetTimings(), GetCurrentIteration()->GetClearSoftReferences(), this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003082}
3083
3084void ConcurrentCopying::RevokeAllThreadLocalBuffers() {
3085 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
3086 region_space_->RevokeAllThreadLocalBuffers();
3087}
3088
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08003089mirror::Object* ConcurrentCopying::MarkFromReadBarrierWithMeasurements(Thread* const self,
3090 mirror::Object* from_ref) {
3091 if (self != thread_running_gc_) {
Orion Hodson88591fe2018-03-06 13:35:43 +00003092 rb_slow_path_count_.fetch_add(1u, std::memory_order_relaxed);
Mathieu Chartier56fe2582016-07-14 13:30:03 -07003093 } else {
Orion Hodson88591fe2018-03-06 13:35:43 +00003094 rb_slow_path_count_gc_.fetch_add(1u, std::memory_order_relaxed);
Mathieu Chartier56fe2582016-07-14 13:30:03 -07003095 }
3096 ScopedTrace tr(__FUNCTION__);
3097 const uint64_t start_time = measure_read_barrier_slow_path_ ? NanoTime() : 0u;
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07003098 mirror::Object* ret =
3099 Mark</*kGrayImmuneObject*/true, /*kNoUnEvac*/false, /*kFromGCThread*/false>(self, from_ref);
Mathieu Chartier56fe2582016-07-14 13:30:03 -07003100 if (measure_read_barrier_slow_path_) {
Orion Hodson88591fe2018-03-06 13:35:43 +00003101 rb_slow_path_ns_.fetch_add(NanoTime() - start_time, std::memory_order_relaxed);
Mathieu Chartier56fe2582016-07-14 13:30:03 -07003102 }
3103 return ret;
3104}
3105
3106void ConcurrentCopying::DumpPerformanceInfo(std::ostream& os) {
3107 GarbageCollector::DumpPerformanceInfo(os);
3108 MutexLock mu(Thread::Current(), rb_slow_path_histogram_lock_);
3109 if (rb_slow_path_time_histogram_.SampleSize() > 0) {
3110 Histogram<uint64_t>::CumulativeData cumulative_data;
3111 rb_slow_path_time_histogram_.CreateHistogram(&cumulative_data);
3112 rb_slow_path_time_histogram_.PrintConfidenceIntervals(os, 0.99, cumulative_data);
3113 }
3114 if (rb_slow_path_count_total_ > 0) {
3115 os << "Slow path count " << rb_slow_path_count_total_ << "\n";
3116 }
3117 if (rb_slow_path_count_gc_total_ > 0) {
3118 os << "GC slow path count " << rb_slow_path_count_gc_total_ << "\n";
3119 }
Orion Hodson88591fe2018-03-06 13:35:43 +00003120 os << "Cumulative bytes moved "
3121 << cumulative_bytes_moved_.load(std::memory_order_relaxed) << "\n";
3122 os << "Cumulative objects moved "
3123 << cumulative_objects_moved_.load(std::memory_order_relaxed) << "\n";
Lokesh Gidra29895822017-12-15 15:37:40 -08003124
3125 os << "Peak regions allocated "
Lokesh Gidrab4f15412018-01-05 18:29:34 -08003126 << region_space_->GetMaxPeakNumNonFreeRegions() << " ("
3127 << PrettySize(region_space_->GetMaxPeakNumNonFreeRegions() * space::RegionSpace::kRegionSize)
3128 << ") / " << region_space_->GetNumRegions() / 2 << " ("
3129 << PrettySize(region_space_->GetNumRegions() * space::RegionSpace::kRegionSize / 2)
Lokesh Gidra29895822017-12-15 15:37:40 -08003130 << ")\n";
Mathieu Chartier56fe2582016-07-14 13:30:03 -07003131}
3132
Hiroshi Yamauchid5307ec2014-03-27 21:07:51 -07003133} // namespace collector
3134} // namespace gc
3135} // namespace art