blob: d91cc2437d1bdc27a2b6684a06d5a286db2183ff [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,
Roland Levillainb1e1dc32018-07-10 19:19:31 +0100142 &error_msg);
143 CHECK(sweep_array_free_buffer_mem_map_.IsValid())
144 << "Couldn't allocate sweep array free buffer: " << error_msg;
145 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800146}
147
Hiroshi Yamauchi057d9772017-02-17 15:33:23 -0800148void ConcurrentCopying::MarkHeapReference(mirror::HeapReference<mirror::Object>* field,
149 bool do_atomic_update) {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -0800150 Thread* const self = Thread::Current();
Hiroshi Yamauchi057d9772017-02-17 15:33:23 -0800151 if (UNLIKELY(do_atomic_update)) {
152 // Used to mark the referent in DelayReferenceReferent in transaction mode.
153 mirror::Object* from_ref = field->AsMirrorPtr();
154 if (from_ref == nullptr) {
155 return;
156 }
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -0800157 mirror::Object* to_ref = Mark(self, from_ref);
Hiroshi Yamauchi057d9772017-02-17 15:33:23 -0800158 if (from_ref != to_ref) {
159 do {
160 if (field->AsMirrorPtr() != from_ref) {
161 // Concurrently overwritten by a mutator.
162 break;
163 }
164 } while (!field->CasWeakRelaxed(from_ref, to_ref));
165 }
166 } else {
167 // Used for preserving soft references, should be OK to not have a CAS here since there should be
168 // no other threads which can trigger read barriers on the same referent during reference
169 // processing.
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -0800170 field->Assign(Mark(self, field->AsMirrorPtr()));
Hiroshi Yamauchi057d9772017-02-17 15:33:23 -0800171 }
Mathieu Chartier97509952015-07-13 14:35:43 -0700172}
173
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800174ConcurrentCopying::~ConcurrentCopying() {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700175 STLDeleteElements(&pooled_mark_stacks_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800176}
177
178void ConcurrentCopying::RunPhases() {
179 CHECK(kUseBakerReadBarrier || kUseTableLookupReadBarrier);
180 CHECK(!is_active_);
181 is_active_ = true;
182 Thread* self = Thread::Current();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700183 thread_running_gc_ = self;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800184 Locks::mutator_lock_->AssertNotHeld(self);
185 {
186 ReaderMutexLock mu(self, *Locks::mutator_lock_);
187 InitializePhase();
188 }
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700189 if (kUseBakerReadBarrier && kGrayDirtyImmuneObjects) {
190 // Switch to read barrier mark entrypoints before we gray the objects. This is required in case
Roland Levillain97c46462017-05-11 14:04:03 +0100191 // a mutator sees a gray bit and dispatches on the entrypoint. (b/37876887).
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700192 ActivateReadBarrierEntrypoints();
193 // Gray dirty immune objects concurrently to reduce GC pause times. We re-process gray cards in
194 // the pause.
195 ReaderMutexLock mu(self, *Locks::mutator_lock_);
196 GrayAllDirtyImmuneObjects();
197 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800198 FlipThreadRoots();
199 {
200 ReaderMutexLock mu(self, *Locks::mutator_lock_);
201 MarkingPhase();
202 }
203 // Verify no from space refs. This causes a pause.
Andreas Gampee3ce7872017-02-22 13:36:21 -0800204 if (kEnableNoFromSpaceRefsVerification) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800205 TimingLogger::ScopedTiming split("(Paused)VerifyNoFromSpaceReferences", GetTimings());
Andreas Gampe4934eb12017-01-30 13:15:26 -0800206 ScopedPause pause(this, false);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700207 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800208 if (kVerboseMode) {
209 LOG(INFO) << "Verifying no from-space refs";
210 }
211 VerifyNoFromSpaceReferences();
Mathieu Chartier720e71a2015-04-06 17:10:58 -0700212 if (kVerboseMode) {
213 LOG(INFO) << "Done verifying no from-space refs";
214 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700215 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800216 }
217 {
218 ReaderMutexLock mu(self, *Locks::mutator_lock_);
219 ReclaimPhase();
220 }
221 FinishPhase();
222 CHECK(is_active_);
223 is_active_ = false;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700224 thread_running_gc_ = nullptr;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800225}
226
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700227class ConcurrentCopying::ActivateReadBarrierEntrypointsCheckpoint : public Closure {
228 public:
229 explicit ActivateReadBarrierEntrypointsCheckpoint(ConcurrentCopying* concurrent_copying)
230 : concurrent_copying_(concurrent_copying) {}
231
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100232 void Run(Thread* thread) override NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700233 // Note: self is not necessarily equal to thread since thread may be suspended.
234 Thread* self = Thread::Current();
235 DCHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
236 << thread->GetState() << " thread " << thread << " self " << self;
237 // Switch to the read barrier entrypoints.
238 thread->SetReadBarrierEntrypoints();
239 // If thread is a running mutator, then act on behalf of the garbage collector.
240 // See the code in ThreadList::RunCheckpoint.
241 concurrent_copying_->GetBarrier().Pass(self);
242 }
243
244 private:
245 ConcurrentCopying* const concurrent_copying_;
246};
247
248class ConcurrentCopying::ActivateReadBarrierEntrypointsCallback : public Closure {
249 public:
250 explicit ActivateReadBarrierEntrypointsCallback(ConcurrentCopying* concurrent_copying)
251 : concurrent_copying_(concurrent_copying) {}
252
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100253 void Run(Thread* self ATTRIBUTE_UNUSED) override REQUIRES(Locks::thread_list_lock_) {
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700254 // This needs to run under the thread_list_lock_ critical section in ThreadList::RunCheckpoint()
255 // to avoid a race with ThreadList::Register().
256 CHECK(!concurrent_copying_->is_using_read_barrier_entrypoints_);
257 concurrent_copying_->is_using_read_barrier_entrypoints_ = true;
258 }
259
260 private:
261 ConcurrentCopying* const concurrent_copying_;
262};
263
264void ConcurrentCopying::ActivateReadBarrierEntrypoints() {
265 Thread* const self = Thread::Current();
266 ActivateReadBarrierEntrypointsCheckpoint checkpoint(this);
267 ThreadList* thread_list = Runtime::Current()->GetThreadList();
268 gc_barrier_->Init(self, 0);
269 ActivateReadBarrierEntrypointsCallback callback(this);
270 const size_t barrier_count = thread_list->RunCheckpoint(&checkpoint, &callback);
271 // If there are no threads to wait which implies that all the checkpoint functions are finished,
272 // then no need to release the mutator lock.
273 if (barrier_count == 0) {
274 return;
275 }
276 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
277 gc_barrier_->Increment(self, barrier_count);
278}
279
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800280void ConcurrentCopying::BindBitmaps() {
281 Thread* self = Thread::Current();
282 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
283 // Mark all of the spaces we never collect as immune.
284 for (const auto& space : heap_->GetContinuousSpaces()) {
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800285 if (space->GetGcRetentionPolicy() == space::kGcRetentionPolicyNeverCollect ||
286 space->GetGcRetentionPolicy() == space::kGcRetentionPolicyFullCollect) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800287 CHECK(space->IsZygoteSpace() || space->IsImageSpace());
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800288 immune_spaces_.AddSpace(space);
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700289 } else {
290 CHECK(!space->IsZygoteSpace());
291 CHECK(!space->IsImageSpace());
292 if (kEnableGenerationalConcurrentCopyingCollection) {
293 if (space == region_space_) {
294 region_space_bitmap_ = region_space_->GetMarkBitmap();
295 } else if (young_gen_ && space->IsContinuousMemMapAllocSpace()) {
296 DCHECK_EQ(space->GetGcRetentionPolicy(), space::kGcRetentionPolicyAlwaysCollect);
297 space->AsContinuousMemMapAllocSpace()->BindLiveToMarkBitmap();
298 }
299 // Age all of the cards for the region space so that we know which evac regions to scan.
300 Runtime::Current()->GetHeap()->GetCardTable()->ModifyCardsAtomic(
301 space->Begin(),
302 space->End(),
303 AgeCardVisitor(),
304 VoidFunctor());
305 } else {
306 if (space == region_space_) {
307 // It is OK to clear the bitmap with mutators running since the only place it is read is
308 // VisitObjects which has exclusion with CC.
309 region_space_bitmap_ = region_space_->GetMarkBitmap();
310 region_space_bitmap_->Clear();
311 }
312 }
313 }
314 }
315 if (kEnableGenerationalConcurrentCopyingCollection && young_gen_) {
316 for (const auto& space : GetHeap()->GetDiscontinuousSpaces()) {
317 CHECK(space->IsLargeObjectSpace());
318 space->AsLargeObjectSpace()->CopyLiveToMarked();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800319 }
320 }
321}
322
323void ConcurrentCopying::InitializePhase() {
324 TimingLogger::ScopedTiming split("InitializePhase", GetTimings());
325 if (kVerboseMode) {
326 LOG(INFO) << "GC InitializePhase";
327 LOG(INFO) << "Region-space : " << reinterpret_cast<void*>(region_space_->Begin()) << "-"
328 << reinterpret_cast<void*>(region_space_->Limit());
329 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700330 CheckEmptyMarkStack();
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800331 if (kIsDebugBuild) {
332 MutexLock mu(Thread::Current(), mark_stack_lock_);
333 CHECK(false_gray_stack_.empty());
334 }
Mathieu Chartier56fe2582016-07-14 13:30:03 -0700335
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700336 rb_mark_bit_stack_full_ = false;
Mathieu Chartier56fe2582016-07-14 13:30:03 -0700337 mark_from_read_barrier_measurements_ = measure_read_barrier_slow_path_;
338 if (measure_read_barrier_slow_path_) {
Orion Hodson88591fe2018-03-06 13:35:43 +0000339 rb_slow_path_ns_.store(0, std::memory_order_relaxed);
340 rb_slow_path_count_.store(0, std::memory_order_relaxed);
341 rb_slow_path_count_gc_.store(0, std::memory_order_relaxed);
Mathieu Chartier56fe2582016-07-14 13:30:03 -0700342 }
343
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800344 immune_spaces_.Reset();
Orion Hodson88591fe2018-03-06 13:35:43 +0000345 bytes_moved_.store(0, std::memory_order_relaxed);
346 objects_moved_.store(0, std::memory_order_relaxed);
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -0800347 bytes_moved_gc_thread_ = 0;
348 objects_moved_gc_thread_ = 0;
Hiroshi Yamauchi60985b72016-08-24 13:53:12 -0700349 GcCause gc_cause = GetCurrentIteration()->GetGcCause();
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700350
351 force_evacuate_all_ = false;
352 if (!kEnableGenerationalConcurrentCopyingCollection || !young_gen_) {
353 if (gc_cause == kGcCauseExplicit ||
354 gc_cause == kGcCauseCollectorTransition ||
355 GetCurrentIteration()->GetClearSoftReferences()) {
356 force_evacuate_all_ = true;
357 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800358 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700359 if (kUseBakerReadBarrier) {
Orion Hodson88591fe2018-03-06 13:35:43 +0000360 updated_all_immune_objects_.store(false, std::memory_order_relaxed);
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700361 // GC may gray immune objects in the thread flip.
362 gc_grays_immune_objects_ = true;
363 if (kIsDebugBuild) {
364 MutexLock mu(Thread::Current(), immune_gray_stack_lock_);
365 DCHECK(immune_gray_stack_.empty());
366 }
367 }
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700368 if (kEnableGenerationalConcurrentCopyingCollection) {
Roland Levillain2d94e292018-08-15 16:46:30 +0100369 done_scanning_.store(false, std::memory_order_release);
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700370 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800371 BindBitmaps();
372 if (kVerboseMode) {
Roland Levillain57ce0542018-08-07 16:20:31 +0100373 LOG(INFO) << "young_gen=" << std::boolalpha << young_gen_ << std::noboolalpha;
374 LOG(INFO) << "force_evacuate_all=" << std::boolalpha << force_evacuate_all_ << std::noboolalpha;
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800375 LOG(INFO) << "Largest immune region: " << immune_spaces_.GetLargestImmuneRegion().Begin()
376 << "-" << immune_spaces_.GetLargestImmuneRegion().End();
377 for (space::ContinuousSpace* space : immune_spaces_.GetSpaces()) {
378 LOG(INFO) << "Immune space: " << *space;
379 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800380 LOG(INFO) << "GC end of InitializePhase";
381 }
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700382 if (kEnableGenerationalConcurrentCopyingCollection && !young_gen_) {
383 region_space_bitmap_->Clear();
384 }
Mathieu Chartier962cd7a2016-08-16 12:15:59 -0700385 // Mark all of the zygote large objects without graying them.
386 MarkZygoteLargeObjects();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800387}
388
389// Used to switch the thread roots of a thread from from-space refs to to-space refs.
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700390class ConcurrentCopying::ThreadFlipVisitor : public Closure, public RootVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800391 public:
Roland Levillain3887c462015-08-12 18:15:42 +0100392 ThreadFlipVisitor(ConcurrentCopying* concurrent_copying, bool use_tlab)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800393 : concurrent_copying_(concurrent_copying), use_tlab_(use_tlab) {
394 }
395
Roland Levillainf73caca2018-08-24 17:19:07 +0100396 void Run(Thread* thread) override REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800397 // Note: self is not necessarily equal to thread since thread may be suspended.
398 Thread* self = Thread::Current();
399 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
400 << thread->GetState() << " thread " << thread << " self " << self;
Mathieu Chartierfe814e82016-11-09 14:32:49 -0800401 thread->SetIsGcMarkingAndUpdateEntrypoints(true);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800402 if (use_tlab_ && thread->HasTlab()) {
403 if (ConcurrentCopying::kEnableFromSpaceAccountingCheck) {
404 // This must come before the revoke.
405 size_t thread_local_objects = thread->GetThreadLocalObjectsAllocated();
406 concurrent_copying_->region_space_->RevokeThreadLocalBuffers(thread);
Roland Levillain2ae376f2018-01-30 11:35:11 +0000407 reinterpret_cast<Atomic<size_t>*>(
408 &concurrent_copying_->from_space_num_objects_at_first_pause_)->
Orion Hodson88591fe2018-03-06 13:35:43 +0000409 fetch_add(thread_local_objects, std::memory_order_seq_cst);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800410 } else {
411 concurrent_copying_->region_space_->RevokeThreadLocalBuffers(thread);
412 }
413 }
414 if (kUseThreadLocalAllocationStack) {
415 thread->RevokeThreadLocalAllocationStack();
416 }
417 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700418 // We can use the non-CAS VisitRoots functions below because we update thread-local GC roots
419 // only.
Andreas Gampe513061a2017-06-01 09:17:34 -0700420 thread->VisitRoots(this, kVisitRootFlagAllRoots);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800421 concurrent_copying_->GetBarrier().Pass(self);
422 }
423
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700424 void VisitRoots(mirror::Object*** roots,
425 size_t count,
Andreas Gampefa6a1b02018-09-07 08:11:55 -0700426 const RootInfo& info ATTRIBUTE_UNUSED) override
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700427 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -0800428 Thread* self = Thread::Current();
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700429 for (size_t i = 0; i < count; ++i) {
430 mirror::Object** root = roots[i];
431 mirror::Object* ref = *root;
432 if (ref != nullptr) {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -0800433 mirror::Object* to_ref = concurrent_copying_->Mark(self, ref);
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700434 if (to_ref != ref) {
435 *root = to_ref;
436 }
437 }
438 }
439 }
440
441 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots,
442 size_t count,
Andreas Gampefa6a1b02018-09-07 08:11:55 -0700443 const RootInfo& info ATTRIBUTE_UNUSED) override
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700444 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -0800445 Thread* self = Thread::Current();
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700446 for (size_t i = 0; i < count; ++i) {
447 mirror::CompressedReference<mirror::Object>* const root = roots[i];
448 if (!root->IsNull()) {
449 mirror::Object* ref = root->AsMirrorPtr();
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -0800450 mirror::Object* to_ref = concurrent_copying_->Mark(self, ref);
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700451 if (to_ref != ref) {
452 root->Assign(to_ref);
453 }
454 }
455 }
456 }
457
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800458 private:
459 ConcurrentCopying* const concurrent_copying_;
460 const bool use_tlab_;
461};
462
463// Called back from Runtime::FlipThreadRoots() during a pause.
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700464class ConcurrentCopying::FlipCallback : public Closure {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800465 public:
466 explicit FlipCallback(ConcurrentCopying* concurrent_copying)
467 : concurrent_copying_(concurrent_copying) {
468 }
469
Roland Levillainf73caca2018-08-24 17:19:07 +0100470 void Run(Thread* thread) override REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800471 ConcurrentCopying* cc = concurrent_copying_;
472 TimingLogger::ScopedTiming split("(Paused)FlipCallback", cc->GetTimings());
473 // Note: self is not necessarily equal to thread since thread may be suspended.
474 Thread* self = Thread::Current();
Mathieu Chartiera1467d02017-02-22 09:22:50 -0800475 if (kVerifyNoMissingCardMarks) {
476 cc->VerifyNoMissingCardMarks();
477 }
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700478 CHECK_EQ(thread, self);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800479 Locks::mutator_lock_->AssertExclusiveHeld(self);
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700480 space::RegionSpace::EvacMode evac_mode = space::RegionSpace::kEvacModeLivePercentNewlyAllocated;
481 if (cc->young_gen_) {
482 CHECK(!cc->force_evacuate_all_);
483 evac_mode = space::RegionSpace::kEvacModeNewlyAllocated;
484 } else if (cc->force_evacuate_all_) {
485 evac_mode = space::RegionSpace::kEvacModeForceAll;
486 }
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700487 {
488 TimingLogger::ScopedTiming split2("(Paused)SetFromSpace", cc->GetTimings());
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700489 // Only change live bytes for full CC.
490 cc->region_space_->SetFromSpace(
491 cc->rb_table_, evac_mode, /*clear_live_bytes*/ !cc->young_gen_);
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700492 }
Mathieu Chartiera4f6af92015-08-11 17:35:25 -0700493 cc->SwapStacks();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800494 if (ConcurrentCopying::kEnableFromSpaceAccountingCheck) {
495 cc->RecordLiveStackFreezeSize(self);
496 cc->from_space_num_objects_at_first_pause_ = cc->region_space_->GetObjectsAllocated();
497 cc->from_space_num_bytes_at_first_pause_ = cc->region_space_->GetBytesAllocated();
498 }
499 cc->is_marking_ = true;
Orion Hodson88591fe2018-03-06 13:35:43 +0000500 cc->mark_stack_mode_.store(ConcurrentCopying::kMarkStackModeThreadLocal,
501 std::memory_order_relaxed);
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700502 if (kIsDebugBuild && !cc->young_gen_) {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800503 cc->region_space_->AssertAllRegionLiveBytesZeroOrCleared();
504 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800505 if (UNLIKELY(Runtime::Current()->IsActiveTransaction())) {
Mathieu Chartier184c9dc2015-03-05 13:20:54 -0800506 CHECK(Runtime::Current()->IsAotCompiler());
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700507 TimingLogger::ScopedTiming split3("(Paused)VisitTransactionRoots", cc->GetTimings());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700508 Runtime::Current()->VisitTransactionRoots(cc);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800509 }
Mathieu Chartier21328a12016-07-22 10:47:45 -0700510 if (kUseBakerReadBarrier && kGrayDirtyImmuneObjects) {
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700511 cc->GrayAllNewlyDirtyImmuneObjects();
Mathieu Chartier21328a12016-07-22 10:47:45 -0700512 if (kIsDebugBuild) {
Roland Levillain001eff92018-01-24 14:24:33 +0000513 // Check that all non-gray immune objects only reference immune objects.
Mathieu Chartier21328a12016-07-22 10:47:45 -0700514 cc->VerifyGrayImmuneObjects();
515 }
516 }
Mathieu Chartier9aef9922017-04-23 13:53:50 -0700517 // May be null during runtime creation, in this case leave java_lang_Object null.
518 // This is safe since single threaded behavior should mean FillDummyObject does not
519 // happen when java_lang_Object_ is null.
520 if (WellKnownClasses::java_lang_Object != nullptr) {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -0800521 cc->java_lang_Object_ = down_cast<mirror::Class*>(cc->Mark(thread,
Mathieu Chartier9aef9922017-04-23 13:53:50 -0700522 WellKnownClasses::ToClass(WellKnownClasses::java_lang_Object).Ptr()));
523 } else {
524 cc->java_lang_Object_ = nullptr;
525 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800526 }
527
528 private:
529 ConcurrentCopying* const concurrent_copying_;
530};
531
Mathieu Chartier21328a12016-07-22 10:47:45 -0700532class ConcurrentCopying::VerifyGrayImmuneObjectsVisitor {
533 public:
534 explicit VerifyGrayImmuneObjectsVisitor(ConcurrentCopying* collector)
535 : collector_(collector) {}
536
Mathieu Chartier31e88222016-10-14 18:43:19 -0700537 void operator()(ObjPtr<mirror::Object> obj, MemberOffset offset, bool /* is_static */)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700538 const ALWAYS_INLINE REQUIRES_SHARED(Locks::mutator_lock_)
539 REQUIRES_SHARED(Locks::heap_bitmap_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700540 CheckReference(obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(offset),
541 obj, offset);
542 }
543
Mathieu Chartier31e88222016-10-14 18:43:19 -0700544 void operator()(ObjPtr<mirror::Class> klass, ObjPtr<mirror::Reference> ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700545 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700546 CHECK(klass->IsTypeOfReferenceClass());
547 CheckReference(ref->GetReferent<kWithoutReadBarrier>(),
548 ref,
549 mirror::Reference::ReferentOffset());
550 }
551
552 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
553 ALWAYS_INLINE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700554 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700555 if (!root->IsNull()) {
556 VisitRoot(root);
557 }
558 }
559
560 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
561 ALWAYS_INLINE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700562 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700563 CheckReference(root->AsMirrorPtr(), nullptr, MemberOffset(0));
564 }
565
566 private:
567 ConcurrentCopying* const collector_;
568
Mathieu Chartier31e88222016-10-14 18:43:19 -0700569 void CheckReference(ObjPtr<mirror::Object> ref,
570 ObjPtr<mirror::Object> holder,
571 MemberOffset offset) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700572 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700573 if (ref != nullptr) {
Mathieu Chartier31e88222016-10-14 18:43:19 -0700574 if (!collector_->immune_spaces_.ContainsObject(ref.Ptr())) {
Mathieu Chartier962cd7a2016-08-16 12:15:59 -0700575 // Not immune, must be a zygote large object.
576 CHECK(Runtime::Current()->GetHeap()->GetLargeObjectsSpace()->IsZygoteLargeObject(
Mathieu Chartier31e88222016-10-14 18:43:19 -0700577 Thread::Current(), ref.Ptr()))
Mathieu Chartier962cd7a2016-08-16 12:15:59 -0700578 << "Non gray object references non immune, non zygote large object "<< ref << " "
David Sehr709b0702016-10-13 09:12:37 -0700579 << mirror::Object::PrettyTypeOf(ref) << " in holder " << holder << " "
580 << mirror::Object::PrettyTypeOf(holder) << " offset=" << offset.Uint32Value();
Mathieu Chartier962cd7a2016-08-16 12:15:59 -0700581 } else {
582 // Make sure the large object class is immune since we will never scan the large object.
583 CHECK(collector_->immune_spaces_.ContainsObject(
584 ref->GetClass<kVerifyNone, kWithoutReadBarrier>()));
585 }
Mathieu Chartier21328a12016-07-22 10:47:45 -0700586 }
587 }
588};
589
590void ConcurrentCopying::VerifyGrayImmuneObjects() {
591 TimingLogger::ScopedTiming split(__FUNCTION__, GetTimings());
592 for (auto& space : immune_spaces_.GetSpaces()) {
593 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
594 accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
595 VerifyGrayImmuneObjectsVisitor visitor(this);
596 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()),
597 reinterpret_cast<uintptr_t>(space->Limit()),
598 [&visitor](mirror::Object* obj)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700599 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700600 // If an object is not gray, it should only have references to things in the immune spaces.
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700601 if (obj->GetReadBarrierState() != ReadBarrier::GrayState()) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700602 obj->VisitReferences</*kVisitNativeRoots*/true,
603 kDefaultVerifyFlags,
604 kWithoutReadBarrier>(visitor, visitor);
605 }
606 });
607 }
608}
609
Mathieu Chartiera1467d02017-02-22 09:22:50 -0800610class ConcurrentCopying::VerifyNoMissingCardMarkVisitor {
611 public:
612 VerifyNoMissingCardMarkVisitor(ConcurrentCopying* cc, ObjPtr<mirror::Object> holder)
613 : cc_(cc),
614 holder_(holder) {}
615
616 void operator()(ObjPtr<mirror::Object> obj,
617 MemberOffset offset,
618 bool is_static ATTRIBUTE_UNUSED) const
619 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
620 if (offset.Uint32Value() != mirror::Object::ClassOffset().Uint32Value()) {
621 CheckReference(obj->GetFieldObject<mirror::Object, kDefaultVerifyFlags, kWithoutReadBarrier>(
622 offset), offset.Uint32Value());
623 }
624 }
625 void operator()(ObjPtr<mirror::Class> klass,
626 ObjPtr<mirror::Reference> ref) const
627 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
628 CHECK(klass->IsTypeOfReferenceClass());
629 this->operator()(ref, mirror::Reference::ReferentOffset(), false);
630 }
631
632 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
633 REQUIRES_SHARED(Locks::mutator_lock_) {
634 if (!root->IsNull()) {
635 VisitRoot(root);
636 }
637 }
638
639 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
640 REQUIRES_SHARED(Locks::mutator_lock_) {
641 CheckReference(root->AsMirrorPtr());
642 }
643
644 void CheckReference(mirror::Object* ref, int32_t offset = -1) const
645 REQUIRES_SHARED(Locks::mutator_lock_) {
Roland Levillainb9c68342018-09-04 18:56:31 +0100646 if (ref != nullptr && cc_->region_space_->IsInNewlyAllocatedRegion(ref)) {
647 LOG(FATAL_WITHOUT_ABORT)
Mathieu Chartiera1467d02017-02-22 09:22:50 -0800648 << holder_->PrettyTypeOf() << "(" << holder_.Ptr() << ") references object "
649 << ref->PrettyTypeOf() << "(" << ref << ") in newly allocated region at offset=" << offset;
Roland Levillainb9c68342018-09-04 18:56:31 +0100650 LOG(FATAL_WITHOUT_ABORT) << "time=" << cc_->region_space_->Time();
651 constexpr const char* kIndent = " ";
652 LOG(FATAL_WITHOUT_ABORT) << cc_->DumpReferenceInfo(holder_.Ptr(), "holder_", kIndent);
653 LOG(FATAL_WITHOUT_ABORT) << cc_->DumpReferenceInfo(ref, "ref", kIndent);
654 LOG(FATAL) << "Unexpected reference to newly allocated region.";
655 }
Mathieu Chartiera1467d02017-02-22 09:22:50 -0800656 }
657
658 private:
659 ConcurrentCopying* const cc_;
660 ObjPtr<mirror::Object> const holder_;
661};
662
Mathieu Chartiera1467d02017-02-22 09:22:50 -0800663void ConcurrentCopying::VerifyNoMissingCardMarks() {
Andreas Gampe0c183382017-07-13 22:26:24 -0700664 auto visitor = [&](mirror::Object* obj)
665 REQUIRES(Locks::mutator_lock_)
666 REQUIRES(!mark_stack_lock_) {
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700667 // Objects on clean cards should never have references to newly allocated regions. Note
668 // that aged cards are also not clean.
Andreas Gampe0c183382017-07-13 22:26:24 -0700669 if (heap_->GetCardTable()->GetCard(obj) == gc::accounting::CardTable::kCardClean) {
670 VerifyNoMissingCardMarkVisitor internal_visitor(this, /*holder*/ obj);
671 obj->VisitReferences</*kVisitNativeRoots*/true, kVerifyNone, kWithoutReadBarrier>(
672 internal_visitor, internal_visitor);
673 }
674 };
Mathieu Chartiera1467d02017-02-22 09:22:50 -0800675 TimingLogger::ScopedTiming split(__FUNCTION__, GetTimings());
Andreas Gampe0c183382017-07-13 22:26:24 -0700676 region_space_->Walk(visitor);
Mathieu Chartiera1467d02017-02-22 09:22:50 -0800677 {
678 ReaderMutexLock rmu(Thread::Current(), *Locks::heap_bitmap_lock_);
Andreas Gampe0c183382017-07-13 22:26:24 -0700679 heap_->GetLiveBitmap()->Visit(visitor);
Mathieu Chartiera1467d02017-02-22 09:22:50 -0800680 }
681}
682
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800683// Switch threads that from from-space to to-space refs. Forward/mark the thread roots.
684void ConcurrentCopying::FlipThreadRoots() {
685 TimingLogger::ScopedTiming split("FlipThreadRoots", GetTimings());
686 if (kVerboseMode) {
687 LOG(INFO) << "time=" << region_space_->Time();
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700688 region_space_->DumpNonFreeRegions(LOG_STREAM(INFO));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800689 }
690 Thread* self = Thread::Current();
691 Locks::mutator_lock_->AssertNotHeld(self);
692 gc_barrier_->Init(self, 0);
693 ThreadFlipVisitor thread_flip_visitor(this, heap_->use_tlab_);
694 FlipCallback flip_callback(this);
Andreas Gampe4934eb12017-01-30 13:15:26 -0800695
Andreas Gampe6e644452017-05-09 16:30:27 -0700696 size_t barrier_count = Runtime::Current()->GetThreadList()->FlipThreadRoots(
697 &thread_flip_visitor, &flip_callback, this, GetHeap()->GetGcPauseListener());
Andreas Gampe4934eb12017-01-30 13:15:26 -0800698
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800699 {
700 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
701 gc_barrier_->Increment(self, barrier_count);
702 }
703 is_asserting_to_space_invariant_ = true;
704 QuasiAtomic::ThreadFenceForConstructor();
705 if (kVerboseMode) {
706 LOG(INFO) << "time=" << region_space_->Time();
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700707 region_space_->DumpNonFreeRegions(LOG_STREAM(INFO));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800708 LOG(INFO) << "GC end of FlipThreadRoots";
709 }
710}
711
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700712template <bool kConcurrent>
Mathieu Chartier21328a12016-07-22 10:47:45 -0700713class ConcurrentCopying::GrayImmuneObjectVisitor {
714 public:
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700715 explicit GrayImmuneObjectVisitor(Thread* self) : self_(self) {}
Mathieu Chartier21328a12016-07-22 10:47:45 -0700716
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700717 ALWAYS_INLINE void operator()(mirror::Object* obj) const REQUIRES_SHARED(Locks::mutator_lock_) {
Roland Levillain14e5a292018-06-28 12:00:56 +0100718 if (kUseBakerReadBarrier && obj->GetReadBarrierState() == ReadBarrier::NonGrayState()) {
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700719 if (kConcurrent) {
720 Locks::mutator_lock_->AssertSharedHeld(self_);
Roland Levillain14e5a292018-06-28 12:00:56 +0100721 obj->AtomicSetReadBarrierState(ReadBarrier::NonGrayState(), ReadBarrier::GrayState());
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700722 // Mod union table VisitObjects may visit the same object multiple times so we can't check
723 // the result of the atomic set.
724 } else {
725 Locks::mutator_lock_->AssertExclusiveHeld(self_);
726 obj->SetReadBarrierState(ReadBarrier::GrayState());
Mathieu Chartier21328a12016-07-22 10:47:45 -0700727 }
Mathieu Chartier21328a12016-07-22 10:47:45 -0700728 }
729 }
730
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700731 static void Callback(mirror::Object* obj, void* arg) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700732 reinterpret_cast<GrayImmuneObjectVisitor<kConcurrent>*>(arg)->operator()(obj);
Mathieu Chartier21328a12016-07-22 10:47:45 -0700733 }
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700734
735 private:
736 Thread* const self_;
Mathieu Chartier21328a12016-07-22 10:47:45 -0700737};
738
739void ConcurrentCopying::GrayAllDirtyImmuneObjects() {
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700740 TimingLogger::ScopedTiming split("GrayAllDirtyImmuneObjects", GetTimings());
741 accounting::CardTable* const card_table = heap_->GetCardTable();
742 Thread* const self = Thread::Current();
743 using VisitorType = GrayImmuneObjectVisitor</* kIsConcurrent */ true>;
744 VisitorType visitor(self);
745 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier21328a12016-07-22 10:47:45 -0700746 for (space::ContinuousSpace* space : immune_spaces_.GetSpaces()) {
747 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700748 accounting::ModUnionTable* table = heap_->FindModUnionTableFromSpace(space);
Mathieu Chartier21328a12016-07-22 10:47:45 -0700749 // Mark all the objects on dirty cards since these may point to objects in other space.
750 // Once these are marked, the GC will eventually clear them later.
751 // Table is non null for boot image and zygote spaces. It is only null for application image
752 // spaces.
753 if (table != nullptr) {
Mathieu Chartier6e6078a2016-10-24 15:45:41 -0700754 table->ProcessCards();
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700755 table->VisitObjects(&VisitorType::Callback, &visitor);
756 // Don't clear cards here since we need to rescan in the pause. If we cleared the cards here,
757 // there would be races with the mutator marking new cards.
758 } else {
759 // Keep cards aged if we don't have a mod-union table since we may need to scan them in future
760 // GCs. This case is for app images.
761 card_table->ModifyCardsAtomic(
762 space->Begin(),
763 space->End(),
764 [](uint8_t card) {
765 return (card != gc::accounting::CardTable::kCardClean)
766 ? gc::accounting::CardTable::kCardAged
767 : card;
768 },
769 /* card modified visitor */ VoidFunctor());
770 card_table->Scan</* kClearCard */ false>(space->GetMarkBitmap(),
771 space->Begin(),
772 space->End(),
773 visitor,
774 gc::accounting::CardTable::kCardAged);
775 }
776 }
777}
778
779void ConcurrentCopying::GrayAllNewlyDirtyImmuneObjects() {
780 TimingLogger::ScopedTiming split("(Paused)GrayAllNewlyDirtyImmuneObjects", GetTimings());
781 accounting::CardTable* const card_table = heap_->GetCardTable();
782 using VisitorType = GrayImmuneObjectVisitor</* kIsConcurrent */ false>;
783 Thread* const self = Thread::Current();
784 VisitorType visitor(self);
785 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
786 for (space::ContinuousSpace* space : immune_spaces_.GetSpaces()) {
787 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
788 accounting::ModUnionTable* table = heap_->FindModUnionTableFromSpace(space);
789
790 // Don't need to scan aged cards since we did these before the pause. Note that scanning cards
791 // also handles the mod-union table cards.
792 card_table->Scan</* kClearCard */ false>(space->GetMarkBitmap(),
793 space->Begin(),
794 space->End(),
795 visitor,
796 gc::accounting::CardTable::kCardDirty);
797 if (table != nullptr) {
798 // Add the cards to the mod-union table so that we can clear cards to save RAM.
799 table->ProcessCards();
Mathieu Chartier6e6078a2016-10-24 15:45:41 -0700800 TimingLogger::ScopedTiming split2("(Paused)ClearCards", GetTimings());
801 card_table->ClearCardRange(space->Begin(),
802 AlignDown(space->End(), accounting::CardTable::kCardSize));
Mathieu Chartier21328a12016-07-22 10:47:45 -0700803 }
804 }
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700805 // 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 -0700806 // barriers in the immune spaces.
Orion Hodson88591fe2018-03-06 13:35:43 +0000807 updated_all_immune_objects_.store(true, std::memory_order_relaxed);
Mathieu Chartier21328a12016-07-22 10:47:45 -0700808}
809
Mathieu Chartiera4f6af92015-08-11 17:35:25 -0700810void ConcurrentCopying::SwapStacks() {
811 heap_->SwapStacks();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800812}
813
814void ConcurrentCopying::RecordLiveStackFreezeSize(Thread* self) {
815 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
816 live_stack_freeze_size_ = heap_->GetLiveStack()->Size();
817}
818
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700819// Used to visit objects in the immune spaces.
820inline void ConcurrentCopying::ScanImmuneObject(mirror::Object* obj) {
821 DCHECK(obj != nullptr);
822 DCHECK(immune_spaces_.ContainsObject(obj));
823 // Update the fields without graying it or pushing it onto the mark stack.
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700824 if (kEnableGenerationalConcurrentCopyingCollection && young_gen_) {
825 // Young GC does not care about references to unevac space. It is safe to not gray these as
826 // long as scan immune objects happens after scanning the dirty cards.
827 Scan<true>(obj);
828 } else {
829 Scan<false>(obj);
830 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700831}
832
833class ConcurrentCopying::ImmuneSpaceScanObjVisitor {
834 public:
835 explicit ImmuneSpaceScanObjVisitor(ConcurrentCopying* cc)
836 : collector_(cc) {}
837
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700838 ALWAYS_INLINE void operator()(mirror::Object* obj) const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700839 if (kUseBakerReadBarrier && kGrayDirtyImmuneObjects) {
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700840 // Only need to scan gray objects.
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700841 if (obj->GetReadBarrierState() == ReadBarrier::GrayState()) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700842 collector_->ScanImmuneObject(obj);
Roland Levillain14e5a292018-06-28 12:00:56 +0100843 // Done scanning the object, go back to black (non-gray).
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700844 bool success = obj->AtomicSetReadBarrierState(ReadBarrier::GrayState(),
Roland Levillain14e5a292018-06-28 12:00:56 +0100845 ReadBarrier::NonGrayState());
Mathieu Chartier2af7a3e2017-12-14 18:36:05 -0800846 CHECK(success)
847 << Runtime::Current()->GetHeap()->GetVerification()->DumpObjectInfo(obj, "failed CAS");
Mathieu Chartier21328a12016-07-22 10:47:45 -0700848 }
849 } else {
850 collector_->ScanImmuneObject(obj);
851 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700852 }
853
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700854 static void Callback(mirror::Object* obj, void* arg) REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi5408f232016-07-29 15:07:05 -0700855 reinterpret_cast<ImmuneSpaceScanObjVisitor*>(arg)->operator()(obj);
856 }
857
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700858 private:
859 ConcurrentCopying* const collector_;
860};
861
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800862// Concurrently mark roots that are guarded by read barriers and process the mark stack.
863void ConcurrentCopying::MarkingPhase() {
864 TimingLogger::ScopedTiming split("MarkingPhase", GetTimings());
865 if (kVerboseMode) {
866 LOG(INFO) << "GC MarkingPhase";
867 }
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -0700868 Thread* self = Thread::Current();
869 if (kIsDebugBuild) {
870 MutexLock mu(self, *Locks::thread_list_lock_);
871 CHECK(weak_ref_access_enabled_);
872 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700873
874 // Scan immune spaces.
875 // Update all the fields in the immune spaces first without graying the objects so that we
876 // minimize dirty pages in the immune spaces. Note mutators can concurrently access and gray some
877 // of the objects.
878 if (kUseBakerReadBarrier) {
879 gc_grays_immune_objects_ = false;
Hiroshi Yamauchi16292fc2016-06-20 20:23:34 -0700880 }
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700881 if (kEnableGenerationalConcurrentCopyingCollection && young_gen_) {
Roland Levillain57ce0542018-08-07 16:20:31 +0100882 if (kVerboseMode) {
883 LOG(INFO) << "GC ScanCardsForSpace";
884 }
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700885 TimingLogger::ScopedTiming split2("ScanCardsForSpace", GetTimings());
886 WriterMutexLock rmu(Thread::Current(), *Locks::heap_bitmap_lock_);
Roland Levillain2d94e292018-08-15 16:46:30 +0100887 CHECK(!done_scanning_.load(std::memory_order_relaxed));
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700888 if (kIsDebugBuild) {
889 // Leave some time for mutators to race ahead to try and find races between the GC card
890 // scanning and mutators reading references.
891 usleep(10 * 1000);
892 }
893 for (space::ContinuousSpace* space : GetHeap()->GetContinuousSpaces()) {
894 if (space->IsImageSpace() || space->IsZygoteSpace()) {
895 // Image and zygote spaces are already handled since we gray the objects in the pause.
896 continue;
897 }
898 // Scan all of the objects on dirty cards in unevac from space, and non moving space. These
899 // are from previous GCs and may reference things in the from space.
Roland Levillain4ba92462018-08-15 19:16:24 +0100900 //
901 // Note that we do not need to process the large-object space (the only discontinuous space)
902 // as it contains only large string objects and large primitive array objects, that have no
903 // reference to other objects, except their class. There is no need to scan these large
904 // objects, as the String class and the primitive array classes are expected to never move
905 // during a minor (young-generation) collection:
906 // - In the case where we run with a boot image, these classes are part of the image space,
907 // which is an immune space.
Roland Levillain0e840272018-08-23 19:55:30 +0100908 // - In the case where we run without a boot image, these classes are allocated in the
909 // non-moving space (see art::ClassLinker::InitWithoutImage).
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700910 Runtime::Current()->GetHeap()->GetCardTable()->Scan<false>(
911 space->GetMarkBitmap(),
912 space->Begin(),
913 space->End(),
914 [this, space](mirror::Object* obj)
915 REQUIRES(Locks::heap_bitmap_lock_)
916 REQUIRES_SHARED(Locks::mutator_lock_) {
917 // Don't push or gray unevac refs.
918 if (kIsDebugBuild && space == region_space_) {
919 // We may get unevac large objects.
920 if (!region_space_->IsInUnevacFromSpace(obj)) {
921 CHECK(region_space_bitmap_->Test(obj));
922 region_space_->DumpRegionForObject(LOG_STREAM(FATAL_WITHOUT_ABORT), obj);
923 LOG(FATAL) << "Scanning " << obj << " not in unevac space";
924 }
925 }
926 Scan<true>(obj);
927 },
928 accounting::CardTable::kCardDirty - 1);
929 }
930 // Done scanning unevac space.
Roland Levillain2d94e292018-08-15 16:46:30 +0100931 done_scanning_.store(true, std::memory_order_release);
Roland Levillain57ce0542018-08-07 16:20:31 +0100932 if (kVerboseMode) {
933 LOG(INFO) << "GC end of ScanCardsForSpace";
934 }
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700935 }
Mathieu Chartier21328a12016-07-22 10:47:45 -0700936 {
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700937 // For a sticky-bit collection, this phase needs to be after the card scanning since the
938 // mutator may read an unevac space object out of an image object. If the image object is no
939 // longer gray it will trigger a read barrier for the unevac space object.
Mathieu Chartier21328a12016-07-22 10:47:45 -0700940 TimingLogger::ScopedTiming split2("ScanImmuneSpaces", GetTimings());
941 for (auto& space : immune_spaces_.GetSpaces()) {
942 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
943 accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
Hiroshi Yamauchi5408f232016-07-29 15:07:05 -0700944 accounting::ModUnionTable* table = heap_->FindModUnionTableFromSpace(space);
Mathieu Chartier21328a12016-07-22 10:47:45 -0700945 ImmuneSpaceScanObjVisitor visitor(this);
Hiroshi Yamauchi5408f232016-07-29 15:07:05 -0700946 if (kUseBakerReadBarrier && kGrayDirtyImmuneObjects && table != nullptr) {
947 table->VisitObjects(ImmuneSpaceScanObjVisitor::Callback, &visitor);
948 } else {
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700949 // TODO: Scan only the aged cards.
Hiroshi Yamauchi5408f232016-07-29 15:07:05 -0700950 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()),
951 reinterpret_cast<uintptr_t>(space->Limit()),
952 visitor);
953 }
Mathieu Chartier21328a12016-07-22 10:47:45 -0700954 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700955 }
956 if (kUseBakerReadBarrier) {
957 // This release fence makes the field updates in the above loop visible before allowing mutator
958 // getting access to immune objects without graying it first.
Orion Hodson88591fe2018-03-06 13:35:43 +0000959 updated_all_immune_objects_.store(true, std::memory_order_release);
Roland Levillain14e5a292018-06-28 12:00:56 +0100960 // Now "un-gray" (conceptually blacken) immune objects concurrently accessed and grayed by
961 // mutators. We can't do this in the above loop because we would incorrectly disable the read
962 // barrier by un-graying (conceptually blackening) an object which may point to an unscanned,
963 // white object, breaking the to-space invariant (a mutator shall never observe a from-space
964 // (white) object).
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700965 //
Roland Levillain14e5a292018-06-28 12:00:56 +0100966 // Make sure no mutators are in the middle of marking an immune object before un-graying
967 // (blackening) immune objects.
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700968 IssueEmptyCheckpoint();
969 MutexLock mu(Thread::Current(), immune_gray_stack_lock_);
970 if (kVerboseMode) {
971 LOG(INFO) << "immune gray stack size=" << immune_gray_stack_.size();
972 }
973 for (mirror::Object* obj : immune_gray_stack_) {
Roland Levillain14e5a292018-06-28 12:00:56 +0100974 DCHECK_EQ(obj->GetReadBarrierState(), ReadBarrier::GrayState());
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700975 bool success = obj->AtomicSetReadBarrierState(ReadBarrier::GrayState(),
Roland Levillain14e5a292018-06-28 12:00:56 +0100976 ReadBarrier::NonGrayState());
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700977 DCHECK(success);
978 }
979 immune_gray_stack_.clear();
980 }
981
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800982 {
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -0700983 TimingLogger::ScopedTiming split2("VisitConcurrentRoots", GetTimings());
984 Runtime::Current()->VisitConcurrentRoots(this, kVisitRootFlagAllRoots);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800985 }
986 {
987 // TODO: don't visit the transaction roots if it's not active.
988 TimingLogger::ScopedTiming split5("VisitNonThreadRoots", GetTimings());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700989 Runtime::Current()->VisitNonThreadRoots(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800990 }
991
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800992 {
Mathieu Chartiera6b1ead2015-10-06 10:32:38 -0700993 TimingLogger::ScopedTiming split7("ProcessMarkStack", GetTimings());
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700994 // We transition through three mark stack modes (thread-local, shared, GC-exclusive). The
995 // primary reasons are the fact that we need to use a checkpoint to process thread-local mark
996 // stacks, but after we disable weak refs accesses, we can't use a checkpoint due to a deadlock
997 // issue because running threads potentially blocking at WaitHoldingLocks, and that once we
998 // reach the point where we process weak references, we can avoid using a lock when accessing
999 // the GC mark stack, which makes mark stack processing more efficient.
1000
1001 // Process the mark stack once in the thread local stack mode. This marks most of the live
1002 // objects, aside from weak ref accesses with read barriers (Reference::GetReferent() and system
1003 // weaks) that may happen concurrently while we processing the mark stack and newly mark/gray
1004 // objects and push refs on the mark stack.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001005 ProcessMarkStack();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001006 // Switch to the shared mark stack mode. That is, revoke and process thread-local mark stacks
1007 // for the last time before transitioning to the shared mark stack mode, which would process new
1008 // refs that may have been concurrently pushed onto the mark stack during the ProcessMarkStack()
1009 // call above. At the same time, disable weak ref accesses using a per-thread flag. It's
1010 // important to do these together in a single checkpoint so that we can ensure that mutators
1011 // won't newly gray objects and push new refs onto the mark stack due to weak ref accesses and
1012 // mutators safely transition to the shared mark stack mode (without leaving unprocessed refs on
1013 // the thread-local mark stacks), without a race. This is why we use a thread-local weak ref
1014 // access flag Thread::tls32_.weak_ref_access_enabled_ instead of the global ones.
1015 SwitchToSharedMarkStackMode();
1016 CHECK(!self->GetWeakRefAccessEnabled());
1017 // Now that weak refs accesses are disabled, once we exhaust the shared mark stack again here
1018 // (which may be non-empty if there were refs found on thread-local mark stacks during the above
1019 // SwitchToSharedMarkStackMode() call), we won't have new refs to process, that is, mutators
1020 // (via read barriers) have no way to produce any more refs to process. Marking converges once
1021 // before we process weak refs below.
1022 ProcessMarkStack();
1023 CheckEmptyMarkStack();
1024 // Switch to the GC exclusive mark stack mode so that we can process the mark stack without a
1025 // lock from this point on.
1026 SwitchToGcExclusiveMarkStackMode();
1027 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001028 if (kVerboseMode) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001029 LOG(INFO) << "ProcessReferences";
1030 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001031 // Process weak references. This may produce new refs to process and have them processed via
Mathieu Chartier97509952015-07-13 14:35:43 -07001032 // ProcessMarkStack (in the GC exclusive mark stack mode).
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001033 ProcessReferences(self);
1034 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001035 if (kVerboseMode) {
1036 LOG(INFO) << "SweepSystemWeaks";
1037 }
1038 SweepSystemWeaks(self);
1039 if (kVerboseMode) {
1040 LOG(INFO) << "SweepSystemWeaks done";
1041 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001042 // Process the mark stack here one last time because the above SweepSystemWeaks() call may have
1043 // marked some objects (strings alive) as hash_set::Erase() can call the hash function for
1044 // arbitrary elements in the weak intern table in InternTable::Table::SweepWeaks().
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001045 ProcessMarkStack();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001046 CheckEmptyMarkStack();
1047 // Re-enable weak ref accesses.
1048 ReenableWeakRefAccess(self);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07001049 // Free data for class loaders that we unloaded.
1050 Runtime::Current()->GetClassLinker()->CleanupClassLoaders();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001051 // Marking is done. Disable marking.
Hiroshi Yamauchi00370822015-08-18 14:47:25 -07001052 DisableMarking();
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001053 if (kUseBakerReadBarrier) {
1054 ProcessFalseGrayStack();
1055 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001056 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001057 }
1058
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001059 if (kIsDebugBuild) {
1060 MutexLock mu(self, *Locks::thread_list_lock_);
1061 CHECK(weak_ref_access_enabled_);
1062 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001063 if (kVerboseMode) {
1064 LOG(INFO) << "GC end of MarkingPhase";
1065 }
1066}
1067
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001068void ConcurrentCopying::ReenableWeakRefAccess(Thread* self) {
1069 if (kVerboseMode) {
1070 LOG(INFO) << "ReenableWeakRefAccess";
1071 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001072 // Iterate all threads (don't need to or can't use a checkpoint) and re-enable weak ref access.
1073 {
1074 MutexLock mu(self, *Locks::thread_list_lock_);
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001075 weak_ref_access_enabled_ = true; // This is for new threads.
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001076 std::list<Thread*> thread_list = Runtime::Current()->GetThreadList()->GetList();
1077 for (Thread* thread : thread_list) {
1078 thread->SetWeakRefAccessEnabled(true);
1079 }
1080 }
1081 // Unblock blocking threads.
1082 GetHeap()->GetReferenceProcessor()->BroadcastForSlowPath(self);
1083 Runtime::Current()->BroadcastForNewSystemWeaks();
1084}
1085
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001086class ConcurrentCopying::DisableMarkingCheckpoint : public Closure {
Hiroshi Yamauchi00370822015-08-18 14:47:25 -07001087 public:
1088 explicit DisableMarkingCheckpoint(ConcurrentCopying* concurrent_copying)
1089 : concurrent_copying_(concurrent_copying) {
1090 }
1091
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001092 void Run(Thread* thread) override NO_THREAD_SAFETY_ANALYSIS {
Hiroshi Yamauchi00370822015-08-18 14:47:25 -07001093 // Note: self is not necessarily equal to thread since thread may be suspended.
1094 Thread* self = Thread::Current();
1095 DCHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
1096 << thread->GetState() << " thread " << thread << " self " << self;
1097 // Disable the thread-local is_gc_marking flag.
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -07001098 // Note a thread that has just started right before this checkpoint may have already this flag
1099 // set to false, which is ok.
Mathieu Chartierfe814e82016-11-09 14:32:49 -08001100 thread->SetIsGcMarkingAndUpdateEntrypoints(false);
Hiroshi Yamauchi00370822015-08-18 14:47:25 -07001101 // If thread is a running mutator, then act on behalf of the garbage collector.
1102 // See the code in ThreadList::RunCheckpoint.
Mathieu Chartier10d25082015-10-28 18:36:09 -07001103 concurrent_copying_->GetBarrier().Pass(self);
Hiroshi Yamauchi00370822015-08-18 14:47:25 -07001104 }
1105
1106 private:
1107 ConcurrentCopying* const concurrent_copying_;
1108};
1109
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001110class ConcurrentCopying::DisableMarkingCallback : public Closure {
1111 public:
1112 explicit DisableMarkingCallback(ConcurrentCopying* concurrent_copying)
1113 : concurrent_copying_(concurrent_copying) {
1114 }
1115
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001116 void Run(Thread* self ATTRIBUTE_UNUSED) override REQUIRES(Locks::thread_list_lock_) {
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001117 // This needs to run under the thread_list_lock_ critical section in ThreadList::RunCheckpoint()
1118 // to avoid a race with ThreadList::Register().
1119 CHECK(concurrent_copying_->is_marking_);
1120 concurrent_copying_->is_marking_ = false;
Mathieu Chartiera9a4f5f2017-05-03 18:19:13 -07001121 if (kUseBakerReadBarrier && kGrayDirtyImmuneObjects) {
1122 CHECK(concurrent_copying_->is_using_read_barrier_entrypoints_);
1123 concurrent_copying_->is_using_read_barrier_entrypoints_ = false;
1124 } else {
1125 CHECK(!concurrent_copying_->is_using_read_barrier_entrypoints_);
1126 }
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001127 }
1128
1129 private:
1130 ConcurrentCopying* const concurrent_copying_;
1131};
1132
Hiroshi Yamauchi00370822015-08-18 14:47:25 -07001133void ConcurrentCopying::IssueDisableMarkingCheckpoint() {
1134 Thread* self = Thread::Current();
1135 DisableMarkingCheckpoint check_point(this);
1136 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1137 gc_barrier_->Init(self, 0);
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001138 DisableMarkingCallback dmc(this);
1139 size_t barrier_count = thread_list->RunCheckpoint(&check_point, &dmc);
Hiroshi Yamauchi00370822015-08-18 14:47:25 -07001140 // If there are no threads to wait which implies that all the checkpoint functions are finished,
1141 // then no need to release the mutator lock.
1142 if (barrier_count == 0) {
1143 return;
1144 }
1145 // Release locks then wait for all mutator threads to pass the barrier.
1146 Locks::mutator_lock_->SharedUnlock(self);
1147 {
1148 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
1149 gc_barrier_->Increment(self, barrier_count);
1150 }
1151 Locks::mutator_lock_->SharedLock(self);
1152}
1153
1154void ConcurrentCopying::DisableMarking() {
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001155 // Use a checkpoint to turn off the global is_marking and the thread-local is_gc_marking flags and
1156 // to ensure no threads are still in the middle of a read barrier which may have a from-space ref
1157 // cached in a local variable.
Hiroshi Yamauchi00370822015-08-18 14:47:25 -07001158 IssueDisableMarkingCheckpoint();
1159 if (kUseTableLookupReadBarrier) {
1160 heap_->rb_table_->ClearAll();
1161 DCHECK(heap_->rb_table_->IsAllCleared());
1162 }
Orion Hodson88591fe2018-03-06 13:35:43 +00001163 is_mark_stack_push_disallowed_.store(1, std::memory_order_seq_cst);
1164 mark_stack_mode_.store(kMarkStackModeOff, std::memory_order_seq_cst);
Hiroshi Yamauchi00370822015-08-18 14:47:25 -07001165}
1166
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08001167void ConcurrentCopying::PushOntoFalseGrayStack(Thread* const self, mirror::Object* ref) {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001168 CHECK(kUseBakerReadBarrier);
1169 DCHECK(ref != nullptr);
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08001170 MutexLock mu(self, mark_stack_lock_);
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001171 false_gray_stack_.push_back(ref);
1172}
1173
1174void ConcurrentCopying::ProcessFalseGrayStack() {
1175 CHECK(kUseBakerReadBarrier);
Roland Levillain14e5a292018-06-28 12:00:56 +01001176 // Change the objects on the false gray stack from gray to non-gray (conceptually black).
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001177 MutexLock mu(Thread::Current(), mark_stack_lock_);
1178 for (mirror::Object* obj : false_gray_stack_) {
1179 DCHECK(IsMarked(obj));
Roland Levillain14e5a292018-06-28 12:00:56 +01001180 // The object could be non-gray (conceptually black) here if a thread got preempted after a
1181 // success at the AtomicSetReadBarrierState in MarkNonMoving(), GC started marking through it
1182 // (but not finished so still gray), the thread ran to register it onto the false gray stack,
1183 // and then GC eventually marked it black (non-gray) after it finished scanning it.
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001184 if (obj->GetReadBarrierState() == ReadBarrier::GrayState()) {
1185 bool success = obj->AtomicSetReadBarrierState(ReadBarrier::GrayState(),
Roland Levillain14e5a292018-06-28 12:00:56 +01001186 ReadBarrier::NonGrayState());
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001187 DCHECK(success);
1188 }
1189 }
1190 false_gray_stack_.clear();
1191}
1192
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001193void ConcurrentCopying::IssueEmptyCheckpoint() {
1194 Thread* self = Thread::Current();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001195 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001196 // Release locks then wait for all mutator threads to pass the barrier.
1197 Locks::mutator_lock_->SharedUnlock(self);
Hiroshi Yamauchia2224042017-02-08 16:35:45 -08001198 thread_list->RunEmptyCheckpoint();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001199 Locks::mutator_lock_->SharedLock(self);
1200}
1201
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -07001202void ConcurrentCopying::ExpandGcMarkStack() {
1203 DCHECK(gc_mark_stack_->IsFull());
1204 const size_t new_size = gc_mark_stack_->Capacity() * 2;
1205 std::vector<StackReference<mirror::Object>> temp(gc_mark_stack_->Begin(),
1206 gc_mark_stack_->End());
1207 gc_mark_stack_->Resize(new_size);
1208 for (auto& ref : temp) {
1209 gc_mark_stack_->PushBack(ref.AsMirrorPtr());
1210 }
1211 DCHECK(!gc_mark_stack_->IsFull());
1212}
1213
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08001214void ConcurrentCopying::PushOntoMarkStack(Thread* const self, mirror::Object* to_ref) {
Orion Hodson88591fe2018-03-06 13:35:43 +00001215 CHECK_EQ(is_mark_stack_push_disallowed_.load(std::memory_order_relaxed), 0)
David Sehr709b0702016-10-13 09:12:37 -07001216 << " " << to_ref << " " << mirror::Object::PrettyTypeOf(to_ref);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001217 CHECK(thread_running_gc_ != nullptr);
Orion Hodson88591fe2018-03-06 13:35:43 +00001218 MarkStackMode mark_stack_mode = mark_stack_mode_.load(std::memory_order_relaxed);
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001219 if (LIKELY(mark_stack_mode == kMarkStackModeThreadLocal)) {
1220 if (LIKELY(self == thread_running_gc_)) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001221 // If GC-running thread, use the GC mark stack instead of a thread-local mark stack.
1222 CHECK(self->GetThreadLocalMarkStack() == nullptr);
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -07001223 if (UNLIKELY(gc_mark_stack_->IsFull())) {
1224 ExpandGcMarkStack();
1225 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001226 gc_mark_stack_->PushBack(to_ref);
1227 } else {
1228 // Otherwise, use a thread-local mark stack.
1229 accounting::AtomicStack<mirror::Object>* tl_mark_stack = self->GetThreadLocalMarkStack();
1230 if (UNLIKELY(tl_mark_stack == nullptr || tl_mark_stack->IsFull())) {
1231 MutexLock mu(self, mark_stack_lock_);
1232 // Get a new thread local mark stack.
1233 accounting::AtomicStack<mirror::Object>* new_tl_mark_stack;
1234 if (!pooled_mark_stacks_.empty()) {
1235 // Use a pooled mark stack.
1236 new_tl_mark_stack = pooled_mark_stacks_.back();
1237 pooled_mark_stacks_.pop_back();
1238 } else {
1239 // None pooled. Create a new one.
1240 new_tl_mark_stack =
1241 accounting::AtomicStack<mirror::Object>::Create(
1242 "thread local mark stack", 4 * KB, 4 * KB);
1243 }
1244 DCHECK(new_tl_mark_stack != nullptr);
1245 DCHECK(new_tl_mark_stack->IsEmpty());
1246 new_tl_mark_stack->PushBack(to_ref);
1247 self->SetThreadLocalMarkStack(new_tl_mark_stack);
1248 if (tl_mark_stack != nullptr) {
1249 // Store the old full stack into a vector.
1250 revoked_mark_stacks_.push_back(tl_mark_stack);
1251 }
1252 } else {
1253 tl_mark_stack->PushBack(to_ref);
1254 }
1255 }
1256 } else if (mark_stack_mode == kMarkStackModeShared) {
1257 // Access the shared GC mark stack with a lock.
1258 MutexLock mu(self, mark_stack_lock_);
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -07001259 if (UNLIKELY(gc_mark_stack_->IsFull())) {
1260 ExpandGcMarkStack();
1261 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001262 gc_mark_stack_->PushBack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001263 } else {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001264 CHECK_EQ(static_cast<uint32_t>(mark_stack_mode),
Hiroshi Yamauchifa755182015-09-30 20:12:11 -07001265 static_cast<uint32_t>(kMarkStackModeGcExclusive))
1266 << "ref=" << to_ref
1267 << " self->gc_marking=" << self->GetIsGcMarking()
1268 << " cc->is_marking=" << is_marking_;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001269 CHECK(self == thread_running_gc_)
1270 << "Only GC-running thread should access the mark stack "
1271 << "in the GC exclusive mark stack mode";
1272 // Access the GC mark stack without a lock.
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -07001273 if (UNLIKELY(gc_mark_stack_->IsFull())) {
1274 ExpandGcMarkStack();
1275 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001276 gc_mark_stack_->PushBack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001277 }
1278}
1279
1280accounting::ObjectStack* ConcurrentCopying::GetAllocationStack() {
1281 return heap_->allocation_stack_.get();
1282}
1283
1284accounting::ObjectStack* ConcurrentCopying::GetLiveStack() {
1285 return heap_->live_stack_.get();
1286}
1287
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001288// The following visitors are used to verify that there's no references to the from-space left after
1289// marking.
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001290class ConcurrentCopying::VerifyNoFromSpaceRefsVisitor : public SingleRootVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001291 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001292 explicit VerifyNoFromSpaceRefsVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001293 : collector_(collector) {}
1294
Mathieu Chartierbc632f02017-04-20 13:31:39 -07001295 void operator()(mirror::Object* ref,
1296 MemberOffset offset = MemberOffset(0),
1297 mirror::Object* holder = nullptr) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001298 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001299 if (ref == nullptr) {
1300 // OK.
1301 return;
1302 }
Mathieu Chartierbc632f02017-04-20 13:31:39 -07001303 collector_->AssertToSpaceInvariant(holder, offset, ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001304 if (kUseBakerReadBarrier) {
Roland Levillain14e5a292018-06-28 12:00:56 +01001305 CHECK_EQ(ref->GetReadBarrierState(), ReadBarrier::NonGrayState())
1306 << "Ref " << ref << " " << ref->PrettyTypeOf() << " has gray rb_state";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001307 }
1308 }
1309
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001310 void VisitRoot(mirror::Object* root, const RootInfo& info ATTRIBUTE_UNUSED)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001311 override REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001312 DCHECK(root != nullptr);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001313 operator()(root);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001314 }
1315
1316 private:
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001317 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001318};
1319
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001320class ConcurrentCopying::VerifyNoFromSpaceRefsFieldVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001321 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001322 explicit VerifyNoFromSpaceRefsFieldVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001323 : collector_(collector) {}
1324
Mathieu Chartier31e88222016-10-14 18:43:19 -07001325 void operator()(ObjPtr<mirror::Object> obj,
1326 MemberOffset offset,
1327 bool is_static ATTRIBUTE_UNUSED) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001328 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001329 mirror::Object* ref =
1330 obj->GetFieldObject<mirror::Object, kDefaultVerifyFlags, kWithoutReadBarrier>(offset);
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001331 VerifyNoFromSpaceRefsVisitor visitor(collector_);
Mathieu Chartierbc632f02017-04-20 13:31:39 -07001332 visitor(ref, offset, obj.Ptr());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001333 }
Mathieu Chartier31e88222016-10-14 18:43:19 -07001334 void operator()(ObjPtr<mirror::Class> klass,
1335 ObjPtr<mirror::Reference> ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001336 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001337 CHECK(klass->IsTypeOfReferenceClass());
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07001338 this->operator()(ObjPtr<mirror::Object>(ref), mirror::Reference::ReferentOffset(), false);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001339 }
1340
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001341 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001342 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001343 if (!root->IsNull()) {
1344 VisitRoot(root);
1345 }
1346 }
1347
1348 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001349 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001350 VerifyNoFromSpaceRefsVisitor visitor(collector_);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001351 visitor(root->AsMirrorPtr());
1352 }
1353
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001354 private:
Mathieu Chartier97509952015-07-13 14:35:43 -07001355 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001356};
1357
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001358// Verify there's no from-space references left after the marking phase.
1359void ConcurrentCopying::VerifyNoFromSpaceReferences() {
1360 Thread* self = Thread::Current();
1361 DCHECK(Locks::mutator_lock_->IsExclusiveHeld(self));
Hiroshi Yamauchi00370822015-08-18 14:47:25 -07001362 // Verify all threads have is_gc_marking to be false
1363 {
1364 MutexLock mu(self, *Locks::thread_list_lock_);
1365 std::list<Thread*> thread_list = Runtime::Current()->GetThreadList()->GetList();
1366 for (Thread* thread : thread_list) {
1367 CHECK(!thread->GetIsGcMarking());
1368 }
1369 }
Andreas Gampe0c183382017-07-13 22:26:24 -07001370
1371 auto verify_no_from_space_refs_visitor = [&](mirror::Object* obj)
1372 REQUIRES_SHARED(Locks::mutator_lock_) {
1373 CHECK(obj != nullptr);
1374 space::RegionSpace* region_space = RegionSpace();
1375 CHECK(!region_space->IsInFromSpace(obj)) << "Scanning object " << obj << " in from space";
1376 VerifyNoFromSpaceRefsFieldVisitor visitor(this);
1377 obj->VisitReferences</*kVisitNativeRoots*/true, kDefaultVerifyFlags, kWithoutReadBarrier>(
1378 visitor,
1379 visitor);
1380 if (kUseBakerReadBarrier) {
Roland Levillain14e5a292018-06-28 12:00:56 +01001381 CHECK_EQ(obj->GetReadBarrierState(), ReadBarrier::NonGrayState())
1382 << "obj=" << obj << " has gray rb_state " << obj->GetReadBarrierState();
Andreas Gampe0c183382017-07-13 22:26:24 -07001383 }
1384 };
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001385 // Roots.
1386 {
1387 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001388 VerifyNoFromSpaceRefsVisitor ref_visitor(this);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001389 Runtime::Current()->VisitRoots(&ref_visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001390 }
1391 // The to-space.
Andreas Gampe0c183382017-07-13 22:26:24 -07001392 region_space_->WalkToSpace(verify_no_from_space_refs_visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001393 // Non-moving spaces.
1394 {
1395 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Andreas Gampe0c183382017-07-13 22:26:24 -07001396 heap_->GetMarkBitmap()->Visit(verify_no_from_space_refs_visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001397 }
1398 // The alloc stack.
1399 {
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001400 VerifyNoFromSpaceRefsVisitor ref_visitor(this);
Mathieu Chartiercb535da2015-01-23 13:50:03 -08001401 for (auto* it = heap_->allocation_stack_->Begin(), *end = heap_->allocation_stack_->End();
1402 it < end; ++it) {
1403 mirror::Object* const obj = it->AsMirrorPtr();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001404 if (obj != nullptr && obj->GetClass() != nullptr) {
1405 // TODO: need to call this only if obj is alive?
1406 ref_visitor(obj);
Andreas Gampe0c183382017-07-13 22:26:24 -07001407 verify_no_from_space_refs_visitor(obj);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001408 }
1409 }
1410 }
1411 // TODO: LOS. But only refs in LOS are classes.
1412}
1413
1414// The following visitors are used to assert the to-space invariant.
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001415class ConcurrentCopying::AssertToSpaceInvariantRefsVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001416 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001417 explicit AssertToSpaceInvariantRefsVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001418 : collector_(collector) {}
1419
1420 void operator()(mirror::Object* ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001421 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001422 if (ref == nullptr) {
1423 // OK.
1424 return;
1425 }
1426 collector_->AssertToSpaceInvariant(nullptr, MemberOffset(0), ref);
1427 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001428
1429 private:
Mathieu Chartier97509952015-07-13 14:35:43 -07001430 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001431};
1432
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001433class ConcurrentCopying::AssertToSpaceInvariantFieldVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001434 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001435 explicit AssertToSpaceInvariantFieldVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001436 : collector_(collector) {}
1437
Mathieu Chartier31e88222016-10-14 18:43:19 -07001438 void operator()(ObjPtr<mirror::Object> obj,
1439 MemberOffset offset,
1440 bool is_static ATTRIBUTE_UNUSED) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001441 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001442 mirror::Object* ref =
1443 obj->GetFieldObject<mirror::Object, kDefaultVerifyFlags, kWithoutReadBarrier>(offset);
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001444 AssertToSpaceInvariantRefsVisitor visitor(collector_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001445 visitor(ref);
1446 }
Mathieu Chartier31e88222016-10-14 18:43:19 -07001447 void operator()(ObjPtr<mirror::Class> klass, ObjPtr<mirror::Reference> ref ATTRIBUTE_UNUSED) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001448 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001449 CHECK(klass->IsTypeOfReferenceClass());
1450 }
1451
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001452 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001453 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001454 if (!root->IsNull()) {
1455 VisitRoot(root);
1456 }
1457 }
1458
1459 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001460 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001461 AssertToSpaceInvariantRefsVisitor visitor(collector_);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001462 visitor(root->AsMirrorPtr());
1463 }
1464
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001465 private:
Mathieu Chartier97509952015-07-13 14:35:43 -07001466 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001467};
1468
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001469class ConcurrentCopying::RevokeThreadLocalMarkStackCheckpoint : public Closure {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001470 public:
Roland Levillain3887c462015-08-12 18:15:42 +01001471 RevokeThreadLocalMarkStackCheckpoint(ConcurrentCopying* concurrent_copying,
1472 bool disable_weak_ref_access)
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001473 : concurrent_copying_(concurrent_copying),
1474 disable_weak_ref_access_(disable_weak_ref_access) {
1475 }
1476
Roland Levillainf73caca2018-08-24 17:19:07 +01001477 void Run(Thread* thread) override NO_THREAD_SAFETY_ANALYSIS {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001478 // Note: self is not necessarily equal to thread since thread may be suspended.
1479 Thread* self = Thread::Current();
1480 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
1481 << thread->GetState() << " thread " << thread << " self " << self;
1482 // Revoke thread local mark stacks.
1483 accounting::AtomicStack<mirror::Object>* tl_mark_stack = thread->GetThreadLocalMarkStack();
1484 if (tl_mark_stack != nullptr) {
1485 MutexLock mu(self, concurrent_copying_->mark_stack_lock_);
1486 concurrent_copying_->revoked_mark_stacks_.push_back(tl_mark_stack);
1487 thread->SetThreadLocalMarkStack(nullptr);
1488 }
1489 // Disable weak ref access.
1490 if (disable_weak_ref_access_) {
1491 thread->SetWeakRefAccessEnabled(false);
1492 }
1493 // If thread is a running mutator, then act on behalf of the garbage collector.
1494 // See the code in ThreadList::RunCheckpoint.
Mathieu Chartier10d25082015-10-28 18:36:09 -07001495 concurrent_copying_->GetBarrier().Pass(self);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001496 }
1497
1498 private:
1499 ConcurrentCopying* const concurrent_copying_;
1500 const bool disable_weak_ref_access_;
1501};
1502
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001503void ConcurrentCopying::RevokeThreadLocalMarkStacks(bool disable_weak_ref_access,
1504 Closure* checkpoint_callback) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001505 Thread* self = Thread::Current();
1506 RevokeThreadLocalMarkStackCheckpoint check_point(this, disable_weak_ref_access);
1507 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1508 gc_barrier_->Init(self, 0);
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001509 size_t barrier_count = thread_list->RunCheckpoint(&check_point, checkpoint_callback);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001510 // If there are no threads to wait which implys that all the checkpoint functions are finished,
1511 // then no need to release the mutator lock.
1512 if (barrier_count == 0) {
1513 return;
1514 }
1515 Locks::mutator_lock_->SharedUnlock(self);
1516 {
1517 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
1518 gc_barrier_->Increment(self, barrier_count);
1519 }
1520 Locks::mutator_lock_->SharedLock(self);
1521}
1522
1523void ConcurrentCopying::RevokeThreadLocalMarkStack(Thread* thread) {
1524 Thread* self = Thread::Current();
1525 CHECK_EQ(self, thread);
1526 accounting::AtomicStack<mirror::Object>* tl_mark_stack = thread->GetThreadLocalMarkStack();
1527 if (tl_mark_stack != nullptr) {
1528 CHECK(is_marking_);
1529 MutexLock mu(self, mark_stack_lock_);
1530 revoked_mark_stacks_.push_back(tl_mark_stack);
1531 thread->SetThreadLocalMarkStack(nullptr);
1532 }
1533}
1534
1535void ConcurrentCopying::ProcessMarkStack() {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001536 if (kVerboseMode) {
1537 LOG(INFO) << "ProcessMarkStack. ";
1538 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001539 bool empty_prev = false;
1540 while (true) {
1541 bool empty = ProcessMarkStackOnce();
1542 if (empty_prev && empty) {
1543 // Saw empty mark stack for a second time, done.
1544 break;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001545 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001546 empty_prev = empty;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001547 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001548}
1549
1550bool ConcurrentCopying::ProcessMarkStackOnce() {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08001551 DCHECK(thread_running_gc_ != nullptr);
1552 Thread* const self = Thread::Current();
1553 DCHECK(self == thread_running_gc_);
1554 DCHECK(thread_running_gc_->GetThreadLocalMarkStack() == nullptr);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001555 size_t count = 0;
Orion Hodson88591fe2018-03-06 13:35:43 +00001556 MarkStackMode mark_stack_mode = mark_stack_mode_.load(std::memory_order_relaxed);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001557 if (mark_stack_mode == kMarkStackModeThreadLocal) {
1558 // Process the thread-local mark stacks and the GC mark stack.
Roland Levillainaf290312018-02-27 20:02:17 +00001559 count += ProcessThreadLocalMarkStacks(/* disable_weak_ref_access */ false,
1560 /* checkpoint_callback */ nullptr);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001561 while (!gc_mark_stack_->IsEmpty()) {
1562 mirror::Object* to_ref = gc_mark_stack_->PopBack();
1563 ProcessMarkStackRef(to_ref);
1564 ++count;
1565 }
1566 gc_mark_stack_->Reset();
1567 } else if (mark_stack_mode == kMarkStackModeShared) {
Hiroshi Yamauchi30493242016-11-03 13:06:52 -07001568 // Do an empty checkpoint to avoid a race with a mutator preempted in the middle of a read
1569 // barrier but before pushing onto the mark stack. b/32508093. Note the weak ref access is
1570 // disabled at this point.
1571 IssueEmptyCheckpoint();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001572 // Process the shared GC mark stack with a lock.
1573 {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08001574 MutexLock mu(thread_running_gc_, mark_stack_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001575 CHECK(revoked_mark_stacks_.empty());
1576 }
1577 while (true) {
1578 std::vector<mirror::Object*> refs;
1579 {
1580 // Copy refs with lock. Note the number of refs should be small.
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08001581 MutexLock mu(thread_running_gc_, mark_stack_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001582 if (gc_mark_stack_->IsEmpty()) {
1583 break;
1584 }
1585 for (StackReference<mirror::Object>* p = gc_mark_stack_->Begin();
1586 p != gc_mark_stack_->End(); ++p) {
1587 refs.push_back(p->AsMirrorPtr());
1588 }
1589 gc_mark_stack_->Reset();
1590 }
1591 for (mirror::Object* ref : refs) {
1592 ProcessMarkStackRef(ref);
1593 ++count;
1594 }
1595 }
1596 } else {
1597 CHECK_EQ(static_cast<uint32_t>(mark_stack_mode),
1598 static_cast<uint32_t>(kMarkStackModeGcExclusive));
1599 {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08001600 MutexLock mu(thread_running_gc_, mark_stack_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001601 CHECK(revoked_mark_stacks_.empty());
1602 }
1603 // Process the GC mark stack in the exclusive mode. No need to take the lock.
1604 while (!gc_mark_stack_->IsEmpty()) {
1605 mirror::Object* to_ref = gc_mark_stack_->PopBack();
1606 ProcessMarkStackRef(to_ref);
1607 ++count;
1608 }
1609 gc_mark_stack_->Reset();
1610 }
1611
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001612 // Return true if the stack was empty.
1613 return count == 0;
1614}
1615
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001616size_t ConcurrentCopying::ProcessThreadLocalMarkStacks(bool disable_weak_ref_access,
1617 Closure* checkpoint_callback) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001618 // Run a checkpoint to collect all thread local mark stacks and iterate over them all.
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001619 RevokeThreadLocalMarkStacks(disable_weak_ref_access, checkpoint_callback);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001620 size_t count = 0;
1621 std::vector<accounting::AtomicStack<mirror::Object>*> mark_stacks;
1622 {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08001623 MutexLock mu(thread_running_gc_, mark_stack_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001624 // Make a copy of the mark stack vector.
1625 mark_stacks = revoked_mark_stacks_;
1626 revoked_mark_stacks_.clear();
1627 }
1628 for (accounting::AtomicStack<mirror::Object>* mark_stack : mark_stacks) {
1629 for (StackReference<mirror::Object>* p = mark_stack->Begin(); p != mark_stack->End(); ++p) {
1630 mirror::Object* to_ref = p->AsMirrorPtr();
1631 ProcessMarkStackRef(to_ref);
1632 ++count;
1633 }
1634 {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08001635 MutexLock mu(thread_running_gc_, mark_stack_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001636 if (pooled_mark_stacks_.size() >= kMarkStackPoolSize) {
1637 // The pool has enough. Delete it.
1638 delete mark_stack;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001639 } else {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001640 // Otherwise, put it into the pool for later reuse.
1641 mark_stack->Reset();
1642 pooled_mark_stacks_.push_back(mark_stack);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001643 }
1644 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001645 }
1646 return count;
1647}
1648
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001649inline void ConcurrentCopying::ProcessMarkStackRef(mirror::Object* to_ref) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001650 DCHECK(!region_space_->IsInFromSpace(to_ref));
1651 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001652 DCHECK(to_ref->GetReadBarrierState() == ReadBarrier::GrayState())
1653 << " " << to_ref << " " << to_ref->GetReadBarrierState()
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001654 << " is_marked=" << IsMarked(to_ref);
1655 }
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07001656 space::RegionSpace::RegionType rtype = region_space_->GetRegionType(to_ref);
Mathieu Chartierc381c362016-08-23 13:27:53 -07001657 bool add_to_live_bytes = false;
Roland Levillain4e751132018-01-15 11:52:58 +00001658 // Invariant: There should be no object from a newly-allocated
1659 // region (either large or non-large) on the mark stack.
1660 DCHECK(!region_space_->IsInNewlyAllocatedRegion(to_ref)) << to_ref;
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07001661 if (rtype == space::RegionSpace::RegionType::kRegionTypeUnevacFromSpace) {
Mathieu Chartierc381c362016-08-23 13:27:53 -07001662 // Mark the bitmap only in the GC thread here so that we don't need a CAS.
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07001663 if (!kUseBakerReadBarrier ||
1664 !region_space_bitmap_->Set(to_ref)) {
Mathieu Chartierc381c362016-08-23 13:27:53 -07001665 // It may be already marked if we accidentally pushed the same object twice due to the racy
1666 // bitmap read in MarkUnevacFromSpaceRegion.
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07001667 if (kEnableGenerationalConcurrentCopyingCollection && young_gen_) {
1668 CHECK(region_space_->IsLargeObject(to_ref));
1669 region_space_->ZeroLiveBytesForLargeObject(to_ref);
1670 Scan<true>(to_ref);
1671 } else {
1672 Scan<false>(to_ref);
1673 }
1674 // Only add to the live bytes if the object was not already marked and we are not the young
1675 // GC.
Mathieu Chartierc381c362016-08-23 13:27:53 -07001676 add_to_live_bytes = true;
1677 }
1678 } else {
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07001679 if (kEnableGenerationalConcurrentCopyingCollection) {
1680 if (rtype == space::RegionSpace::RegionType::kRegionTypeToSpace) {
1681 // Copied to to-space, set the bit so that the next GC can scan objects.
1682 region_space_bitmap_->Set(to_ref);
1683 }
1684 }
1685 if (kEnableGenerationalConcurrentCopyingCollection && young_gen_) {
1686 Scan<true>(to_ref);
1687 } else {
1688 Scan<false>(to_ref);
1689 }
Mathieu Chartierc381c362016-08-23 13:27:53 -07001690 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001691 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001692 DCHECK(to_ref->GetReadBarrierState() == ReadBarrier::GrayState())
1693 << " " << to_ref << " " << to_ref->GetReadBarrierState()
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001694 << " is_marked=" << IsMarked(to_ref);
1695 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001696#ifdef USE_BAKER_OR_BROOKS_READ_BARRIER
Hiroshi Yamauchi39c12d42016-12-06 16:46:37 -08001697 mirror::Object* referent = nullptr;
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001698 if (UNLIKELY((to_ref->GetClass<kVerifyNone, kWithoutReadBarrier>()->IsTypeOfReferenceClass() &&
Hiroshi Yamauchi39c12d42016-12-06 16:46:37 -08001699 (referent = to_ref->AsReference()->GetReferent<kWithoutReadBarrier>()) != nullptr &&
1700 !IsInToSpace(referent)))) {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001701 // Leave this reference gray in the queue so that GetReferent() will trigger a read barrier. We
Roland Levillain14e5a292018-06-28 12:00:56 +01001702 // will change it to non-gray later in ReferenceQueue::DisableReadBarrierForReference.
Roland Levillain2ae376f2018-01-30 11:35:11 +00001703 DCHECK(to_ref->AsReference()->GetPendingNext() != nullptr)
1704 << "Left unenqueued ref gray " << to_ref;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001705 } else {
Roland Levillain14e5a292018-06-28 12:00:56 +01001706 // We may occasionally leave a reference non-gray in the queue if its referent happens to be
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001707 // concurrently marked after the Scan() call above has enqueued the Reference, in which case the
Roland Levillain14e5a292018-06-28 12:00:56 +01001708 // above IsInToSpace() evaluates to true and we change the color from gray to non-gray here in
1709 // this else block.
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001710 if (kUseBakerReadBarrier) {
Mathieu Chartier42c2e502018-06-19 12:30:56 -07001711 bool success = to_ref->AtomicSetReadBarrierState<std::memory_order_release>(
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001712 ReadBarrier::GrayState(),
Roland Levillain14e5a292018-06-28 12:00:56 +01001713 ReadBarrier::NonGrayState());
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001714 DCHECK(success) << "Must succeed as we won the race.";
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001715 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001716 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001717#else
1718 DCHECK(!kUseBakerReadBarrier);
1719#endif
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001720
Mathieu Chartierc381c362016-08-23 13:27:53 -07001721 if (add_to_live_bytes) {
Roland Levillain2ae376f2018-01-30 11:35:11 +00001722 // Add to the live bytes per unevacuated from-space. Note this code is always run by the
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001723 // GC-running thread (no synchronization required).
1724 DCHECK(region_space_bitmap_->Test(to_ref));
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07001725 size_t obj_size = to_ref->SizeOf<kDefaultVerifyFlags>();
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001726 size_t alloc_size = RoundUp(obj_size, space::RegionSpace::kAlignment);
1727 region_space_->AddLiveBytes(to_ref, alloc_size);
1728 }
Andreas Gampee3ce7872017-02-22 13:36:21 -08001729 if (ReadBarrier::kEnableToSpaceInvariantChecks) {
Andreas Gampe0c183382017-07-13 22:26:24 -07001730 CHECK(to_ref != nullptr);
1731 space::RegionSpace* region_space = RegionSpace();
1732 CHECK(!region_space->IsInFromSpace(to_ref)) << "Scanning object " << to_ref << " in from space";
1733 AssertToSpaceInvariant(nullptr, MemberOffset(0), to_ref);
1734 AssertToSpaceInvariantFieldVisitor visitor(this);
1735 to_ref->VisitReferences</*kVisitNativeRoots*/true, kDefaultVerifyFlags, kWithoutReadBarrier>(
1736 visitor,
1737 visitor);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001738 }
1739}
1740
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001741class ConcurrentCopying::DisableWeakRefAccessCallback : public Closure {
1742 public:
1743 explicit DisableWeakRefAccessCallback(ConcurrentCopying* concurrent_copying)
1744 : concurrent_copying_(concurrent_copying) {
1745 }
1746
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001747 void Run(Thread* self ATTRIBUTE_UNUSED) override REQUIRES(Locks::thread_list_lock_) {
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001748 // This needs to run under the thread_list_lock_ critical section in ThreadList::RunCheckpoint()
1749 // to avoid a deadlock b/31500969.
1750 CHECK(concurrent_copying_->weak_ref_access_enabled_);
1751 concurrent_copying_->weak_ref_access_enabled_ = false;
1752 }
1753
1754 private:
1755 ConcurrentCopying* const concurrent_copying_;
1756};
1757
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001758void ConcurrentCopying::SwitchToSharedMarkStackMode() {
1759 Thread* self = Thread::Current();
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08001760 DCHECK(thread_running_gc_ != nullptr);
1761 DCHECK(self == thread_running_gc_);
1762 DCHECK(thread_running_gc_->GetThreadLocalMarkStack() == nullptr);
Orion Hodson88591fe2018-03-06 13:35:43 +00001763 MarkStackMode before_mark_stack_mode = mark_stack_mode_.load(std::memory_order_relaxed);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001764 CHECK_EQ(static_cast<uint32_t>(before_mark_stack_mode),
1765 static_cast<uint32_t>(kMarkStackModeThreadLocal));
Orion Hodson88591fe2018-03-06 13:35:43 +00001766 mark_stack_mode_.store(kMarkStackModeShared, std::memory_order_relaxed);
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001767 DisableWeakRefAccessCallback dwrac(this);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001768 // Process the thread local mark stacks one last time after switching to the shared mark stack
1769 // mode and disable weak ref accesses.
Roland Levillainaf290312018-02-27 20:02:17 +00001770 ProcessThreadLocalMarkStacks(/* disable_weak_ref_access */ true, &dwrac);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001771 if (kVerboseMode) {
1772 LOG(INFO) << "Switched to shared mark stack mode and disabled weak ref access";
1773 }
1774}
1775
1776void ConcurrentCopying::SwitchToGcExclusiveMarkStackMode() {
1777 Thread* self = Thread::Current();
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08001778 DCHECK(thread_running_gc_ != nullptr);
1779 DCHECK(self == thread_running_gc_);
1780 DCHECK(thread_running_gc_->GetThreadLocalMarkStack() == nullptr);
Orion Hodson88591fe2018-03-06 13:35:43 +00001781 MarkStackMode before_mark_stack_mode = mark_stack_mode_.load(std::memory_order_relaxed);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001782 CHECK_EQ(static_cast<uint32_t>(before_mark_stack_mode),
1783 static_cast<uint32_t>(kMarkStackModeShared));
Orion Hodson88591fe2018-03-06 13:35:43 +00001784 mark_stack_mode_.store(kMarkStackModeGcExclusive, std::memory_order_relaxed);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001785 QuasiAtomic::ThreadFenceForConstructor();
1786 if (kVerboseMode) {
1787 LOG(INFO) << "Switched to GC exclusive mark stack mode";
1788 }
1789}
1790
1791void ConcurrentCopying::CheckEmptyMarkStack() {
1792 Thread* self = Thread::Current();
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08001793 DCHECK(thread_running_gc_ != nullptr);
1794 DCHECK(self == thread_running_gc_);
1795 DCHECK(thread_running_gc_->GetThreadLocalMarkStack() == nullptr);
Orion Hodson88591fe2018-03-06 13:35:43 +00001796 MarkStackMode mark_stack_mode = mark_stack_mode_.load(std::memory_order_relaxed);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001797 if (mark_stack_mode == kMarkStackModeThreadLocal) {
1798 // Thread-local mark stack mode.
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001799 RevokeThreadLocalMarkStacks(false, nullptr);
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08001800 MutexLock mu(thread_running_gc_, mark_stack_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001801 if (!revoked_mark_stacks_.empty()) {
1802 for (accounting::AtomicStack<mirror::Object>* mark_stack : revoked_mark_stacks_) {
1803 while (!mark_stack->IsEmpty()) {
1804 mirror::Object* obj = mark_stack->PopBack();
1805 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001806 uint32_t rb_state = obj->GetReadBarrierState();
1807 LOG(INFO) << "On mark queue : " << obj << " " << obj->PrettyTypeOf() << " rb_state="
1808 << rb_state << " is_marked=" << IsMarked(obj);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001809 } else {
David Sehr709b0702016-10-13 09:12:37 -07001810 LOG(INFO) << "On mark queue : " << obj << " " << obj->PrettyTypeOf()
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001811 << " is_marked=" << IsMarked(obj);
1812 }
1813 }
1814 }
1815 LOG(FATAL) << "mark stack is not empty";
1816 }
1817 } else {
1818 // Shared, GC-exclusive, or off.
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08001819 MutexLock mu(thread_running_gc_, mark_stack_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001820 CHECK(gc_mark_stack_->IsEmpty());
1821 CHECK(revoked_mark_stacks_.empty());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001822 }
1823}
1824
1825void ConcurrentCopying::SweepSystemWeaks(Thread* self) {
1826 TimingLogger::ScopedTiming split("SweepSystemWeaks", GetTimings());
1827 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier97509952015-07-13 14:35:43 -07001828 Runtime::Current()->SweepSystemWeaks(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001829}
1830
1831void ConcurrentCopying::Sweep(bool swap_bitmaps) {
Roland Levillainb1e1dc32018-07-10 19:19:31 +01001832 if (kEnableGenerationalConcurrentCopyingCollection && young_gen_) {
1833 // Only sweep objects on the live stack.
1834 SweepArray(heap_->GetLiveStack(), /* swap_bitmaps */ false);
1835 } else {
1836 {
1837 TimingLogger::ScopedTiming t("MarkStackAsLive", GetTimings());
1838 accounting::ObjectStack* live_stack = heap_->GetLiveStack();
1839 if (kEnableFromSpaceAccountingCheck) {
1840 // Ensure that nobody inserted items in the live stack after we swapped the stacks.
1841 CHECK_GE(live_stack_freeze_size_, live_stack->Size());
1842 }
1843 heap_->MarkAllocStackAsLive(live_stack);
1844 live_stack->Reset();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001845 }
Roland Levillainb1e1dc32018-07-10 19:19:31 +01001846 CheckEmptyMarkStack();
1847 TimingLogger::ScopedTiming split("Sweep", GetTimings());
1848 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
1849 if (space->IsContinuousMemMapAllocSpace()) {
1850 space::ContinuousMemMapAllocSpace* alloc_space = space->AsContinuousMemMapAllocSpace();
1851 if (space == region_space_ || immune_spaces_.ContainsSpace(space)) {
1852 continue;
1853 }
1854 TimingLogger::ScopedTiming split2(
1855 alloc_space->IsZygoteSpace() ? "SweepZygoteSpace" : "SweepAllocSpace", GetTimings());
1856 RecordFree(alloc_space->Sweep(swap_bitmaps));
1857 }
1858 }
1859 SweepLargeObjects(swap_bitmaps);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001860 }
Roland Levillainb1e1dc32018-07-10 19:19:31 +01001861}
1862
1863// Copied and adapted from MarkSweep::SweepArray.
1864void ConcurrentCopying::SweepArray(accounting::ObjectStack* allocations, bool swap_bitmaps) {
1865 // This method is only used when Generational CC collection is enabled.
1866 DCHECK(kEnableGenerationalConcurrentCopyingCollection);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001867 CheckEmptyMarkStack();
Roland Levillainb1e1dc32018-07-10 19:19:31 +01001868 TimingLogger::ScopedTiming t("SweepArray", GetTimings());
1869 Thread* self = Thread::Current();
1870 mirror::Object** chunk_free_buffer = reinterpret_cast<mirror::Object**>(
1871 sweep_array_free_buffer_mem_map_.BaseBegin());
1872 size_t chunk_free_pos = 0;
1873 ObjectBytePair freed;
1874 ObjectBytePair freed_los;
1875 // How many objects are left in the array, modified after each space is swept.
1876 StackReference<mirror::Object>* objects = allocations->Begin();
1877 size_t count = allocations->Size();
1878 // Start by sweeping the continuous spaces.
1879 for (space::ContinuousSpace* space : heap_->GetContinuousSpaces()) {
1880 if (!space->IsAllocSpace() ||
1881 space == region_space_ ||
1882 immune_spaces_.ContainsSpace(space) ||
1883 space->GetLiveBitmap() == nullptr) {
1884 continue;
1885 }
1886 space::AllocSpace* alloc_space = space->AsAllocSpace();
1887 accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
1888 accounting::ContinuousSpaceBitmap* mark_bitmap = space->GetMarkBitmap();
1889 if (swap_bitmaps) {
1890 std::swap(live_bitmap, mark_bitmap);
1891 }
1892 StackReference<mirror::Object>* out = objects;
1893 for (size_t i = 0; i < count; ++i) {
1894 mirror::Object* const obj = objects[i].AsMirrorPtr();
1895 if (kUseThreadLocalAllocationStack && obj == nullptr) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001896 continue;
1897 }
Roland Levillainb1e1dc32018-07-10 19:19:31 +01001898 if (space->HasAddress(obj)) {
1899 // This object is in the space, remove it from the array and add it to the sweep buffer
1900 // if needed.
1901 if (!mark_bitmap->Test(obj)) {
1902 if (chunk_free_pos >= kSweepArrayChunkFreeSize) {
1903 TimingLogger::ScopedTiming t2("FreeList", GetTimings());
1904 freed.objects += chunk_free_pos;
1905 freed.bytes += alloc_space->FreeList(self, chunk_free_pos, chunk_free_buffer);
1906 chunk_free_pos = 0;
1907 }
1908 chunk_free_buffer[chunk_free_pos++] = obj;
1909 }
1910 } else {
1911 (out++)->Assign(obj);
1912 }
1913 }
1914 if (chunk_free_pos > 0) {
1915 TimingLogger::ScopedTiming t2("FreeList", GetTimings());
1916 freed.objects += chunk_free_pos;
1917 freed.bytes += alloc_space->FreeList(self, chunk_free_pos, chunk_free_buffer);
1918 chunk_free_pos = 0;
1919 }
1920 // All of the references which space contained are no longer in the allocation stack, update
1921 // the count.
1922 count = out - objects;
1923 }
1924 // Handle the large object space.
1925 space::LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
1926 if (large_object_space != nullptr) {
1927 accounting::LargeObjectBitmap* large_live_objects = large_object_space->GetLiveBitmap();
1928 accounting::LargeObjectBitmap* large_mark_objects = large_object_space->GetMarkBitmap();
1929 if (swap_bitmaps) {
1930 std::swap(large_live_objects, large_mark_objects);
1931 }
1932 for (size_t i = 0; i < count; ++i) {
1933 mirror::Object* const obj = objects[i].AsMirrorPtr();
1934 // Handle large objects.
1935 if (kUseThreadLocalAllocationStack && obj == nullptr) {
1936 continue;
1937 }
1938 if (!large_mark_objects->Test(obj)) {
1939 ++freed_los.objects;
1940 freed_los.bytes += large_object_space->Free(self, obj);
1941 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001942 }
1943 }
Roland Levillainb1e1dc32018-07-10 19:19:31 +01001944 {
1945 TimingLogger::ScopedTiming t2("RecordFree", GetTimings());
1946 RecordFree(freed);
1947 RecordFreeLOS(freed_los);
1948 t2.NewTiming("ResetStack");
1949 allocations->Reset();
1950 }
1951 sweep_array_free_buffer_mem_map_.MadviseDontNeedAndZero();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001952}
1953
Mathieu Chartier962cd7a2016-08-16 12:15:59 -07001954void ConcurrentCopying::MarkZygoteLargeObjects() {
1955 TimingLogger::ScopedTiming split(__FUNCTION__, GetTimings());
1956 Thread* const self = Thread::Current();
1957 WriterMutexLock rmu(self, *Locks::heap_bitmap_lock_);
1958 space::LargeObjectSpace* const los = heap_->GetLargeObjectsSpace();
Nicolas Geoffray7acddd82017-05-03 15:04:55 +01001959 if (los != nullptr) {
1960 // Pick the current live bitmap (mark bitmap if swapped).
1961 accounting::LargeObjectBitmap* const live_bitmap = los->GetLiveBitmap();
1962 accounting::LargeObjectBitmap* const mark_bitmap = los->GetMarkBitmap();
1963 // Walk through all of the objects and explicitly mark the zygote ones so they don't get swept.
1964 std::pair<uint8_t*, uint8_t*> range = los->GetBeginEndAtomic();
1965 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(range.first),
1966 reinterpret_cast<uintptr_t>(range.second),
1967 [mark_bitmap, los, self](mirror::Object* obj)
1968 REQUIRES(Locks::heap_bitmap_lock_)
1969 REQUIRES_SHARED(Locks::mutator_lock_) {
1970 if (los->IsZygoteLargeObject(self, obj)) {
1971 mark_bitmap->Set(obj);
1972 }
1973 });
1974 }
Mathieu Chartier962cd7a2016-08-16 12:15:59 -07001975}
1976
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001977void ConcurrentCopying::SweepLargeObjects(bool swap_bitmaps) {
1978 TimingLogger::ScopedTiming split("SweepLargeObjects", GetTimings());
Nicolas Geoffray7acddd82017-05-03 15:04:55 +01001979 if (heap_->GetLargeObjectsSpace() != nullptr) {
1980 RecordFreeLOS(heap_->GetLargeObjectsSpace()->Sweep(swap_bitmaps));
1981 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001982}
1983
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001984void ConcurrentCopying::ReclaimPhase() {
1985 TimingLogger::ScopedTiming split("ReclaimPhase", GetTimings());
1986 if (kVerboseMode) {
1987 LOG(INFO) << "GC ReclaimPhase";
1988 }
1989 Thread* self = Thread::Current();
1990
1991 {
1992 // Double-check that the mark stack is empty.
1993 // Note: need to set this after VerifyNoFromSpaceRef().
1994 is_asserting_to_space_invariant_ = false;
1995 QuasiAtomic::ThreadFenceForConstructor();
1996 if (kVerboseMode) {
1997 LOG(INFO) << "Issue an empty check point. ";
1998 }
1999 IssueEmptyCheckpoint();
2000 // Disable the check.
Orion Hodson88591fe2018-03-06 13:35:43 +00002001 is_mark_stack_push_disallowed_.store(0, std::memory_order_seq_cst);
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002002 if (kUseBakerReadBarrier) {
Orion Hodson88591fe2018-03-06 13:35:43 +00002003 updated_all_immune_objects_.store(false, std::memory_order_seq_cst);
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002004 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002005 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002006 }
2007
2008 {
2009 // Record freed objects.
2010 TimingLogger::ScopedTiming split2("RecordFree", GetTimings());
2011 // Don't include thread-locals that are in the to-space.
Mathieu Chartier371b0472017-02-27 16:37:21 -08002012 const uint64_t from_bytes = region_space_->GetBytesAllocatedInFromSpace();
2013 const uint64_t from_objects = region_space_->GetObjectsAllocatedInFromSpace();
2014 const uint64_t unevac_from_bytes = region_space_->GetBytesAllocatedInUnevacFromSpace();
2015 const uint64_t unevac_from_objects = region_space_->GetObjectsAllocatedInUnevacFromSpace();
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002016 uint64_t to_bytes = bytes_moved_.load(std::memory_order_seq_cst) + bytes_moved_gc_thread_;
Orion Hodson88591fe2018-03-06 13:35:43 +00002017 cumulative_bytes_moved_.fetch_add(to_bytes, std::memory_order_relaxed);
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002018 uint64_t to_objects = objects_moved_.load(std::memory_order_seq_cst) + objects_moved_gc_thread_;
Orion Hodson88591fe2018-03-06 13:35:43 +00002019 cumulative_objects_moved_.fetch_add(to_objects, std::memory_order_relaxed);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002020 if (kEnableFromSpaceAccountingCheck) {
2021 CHECK_EQ(from_space_num_objects_at_first_pause_, from_objects + unevac_from_objects);
2022 CHECK_EQ(from_space_num_bytes_at_first_pause_, from_bytes + unevac_from_bytes);
2023 }
2024 CHECK_LE(to_objects, from_objects);
2025 CHECK_LE(to_bytes, from_bytes);
Roland Levillain8f7ea9a2018-01-26 17:27:59 +00002026 // Cleared bytes and objects, populated by the call to RegionSpace::ClearFromSpace below.
Mathieu Chartier371b0472017-02-27 16:37:21 -08002027 uint64_t cleared_bytes;
2028 uint64_t cleared_objects;
2029 {
2030 TimingLogger::ScopedTiming split4("ClearFromSpace", GetTimings());
2031 region_space_->ClearFromSpace(&cleared_bytes, &cleared_objects);
Roland Levillain8f7ea9a2018-01-26 17:27:59 +00002032 // `cleared_bytes` and `cleared_objects` may be greater than the from space equivalents since
2033 // RegionSpace::ClearFromSpace may clear empty unevac regions.
Mathieu Chartier371b0472017-02-27 16:37:21 -08002034 CHECK_GE(cleared_bytes, from_bytes);
2035 CHECK_GE(cleared_objects, from_objects);
2036 }
2037 int64_t freed_bytes = cleared_bytes - to_bytes;
2038 int64_t freed_objects = cleared_objects - to_objects;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002039 if (kVerboseMode) {
2040 LOG(INFO) << "RecordFree:"
2041 << " from_bytes=" << from_bytes << " from_objects=" << from_objects
Roland Levillain2ae376f2018-01-30 11:35:11 +00002042 << " unevac_from_bytes=" << unevac_from_bytes
2043 << " unevac_from_objects=" << unevac_from_objects
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002044 << " to_bytes=" << to_bytes << " to_objects=" << to_objects
2045 << " freed_bytes=" << freed_bytes << " freed_objects=" << freed_objects
2046 << " from_space size=" << region_space_->FromSpaceSize()
2047 << " unevac_from_space size=" << region_space_->UnevacFromSpaceSize()
2048 << " to_space size=" << region_space_->ToSpaceSize();
Roland Levillain2ae376f2018-01-30 11:35:11 +00002049 LOG(INFO) << "(before) num_bytes_allocated="
Orion Hodson88591fe2018-03-06 13:35:43 +00002050 << heap_->num_bytes_allocated_.load(std::memory_order_seq_cst);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002051 }
2052 RecordFree(ObjectBytePair(freed_objects, freed_bytes));
2053 if (kVerboseMode) {
Roland Levillain2ae376f2018-01-30 11:35:11 +00002054 LOG(INFO) << "(after) num_bytes_allocated="
Orion Hodson88591fe2018-03-06 13:35:43 +00002055 << heap_->num_bytes_allocated_.load(std::memory_order_seq_cst);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002056 }
2057 }
2058
2059 {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002060 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Roland Levillainb1e1dc32018-07-10 19:19:31 +01002061 Sweep(/* swap_bitmaps */ false);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002062 SwapBitmaps();
2063 heap_->UnBindBitmaps();
2064
Mathieu Chartier7ec38dc2016-10-07 15:24:46 -07002065 // 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 -07002066 DCHECK(region_space_bitmap_ != nullptr);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002067 region_space_bitmap_ = nullptr;
2068 }
2069
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002070 CheckEmptyMarkStack();
2071
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002072 if (kVerboseMode) {
2073 LOG(INFO) << "GC end of ReclaimPhase";
2074 }
2075}
2076
Roland Levillain001eff92018-01-24 14:24:33 +00002077std::string ConcurrentCopying::DumpReferenceInfo(mirror::Object* ref,
2078 const char* ref_name,
Andreas Gampebc802de2018-06-20 17:24:11 -07002079 const char* indent) {
Roland Levillain001eff92018-01-24 14:24:33 +00002080 std::ostringstream oss;
2081 oss << indent << heap_->GetVerification()->DumpObjectInfo(ref, ref_name) << '\n';
2082 if (ref != nullptr) {
2083 if (kUseBakerReadBarrier) {
2084 oss << indent << ref_name << "->GetMarkBit()=" << ref->GetMarkBit() << '\n';
2085 oss << indent << ref_name << "->GetReadBarrierState()=" << ref->GetReadBarrierState() << '\n';
2086 }
2087 }
2088 if (region_space_->HasAddress(ref)) {
2089 oss << indent << "Region containing " << ref_name << ":" << '\n';
2090 region_space_->DumpRegionForObject(oss, ref);
2091 if (region_space_bitmap_ != nullptr) {
2092 oss << indent << "region_space_bitmap_->Test(" << ref_name << ")="
2093 << std::boolalpha << region_space_bitmap_->Test(ref) << std::noboolalpha;
2094 }
2095 }
2096 return oss.str();
2097}
2098
2099std::string ConcurrentCopying::DumpHeapReference(mirror::Object* obj,
2100 MemberOffset offset,
2101 mirror::Object* ref) {
2102 std::ostringstream oss;
Andreas Gampebc802de2018-06-20 17:24:11 -07002103 constexpr const char* kIndent = " ";
2104 oss << kIndent << "Invalid reference: ref=" << ref
Roland Levillain001eff92018-01-24 14:24:33 +00002105 << " referenced from: object=" << obj << " offset= " << offset << '\n';
2106 // Information about `obj`.
Andreas Gampebc802de2018-06-20 17:24:11 -07002107 oss << DumpReferenceInfo(obj, "obj", kIndent) << '\n';
Roland Levillain001eff92018-01-24 14:24:33 +00002108 // Information about `ref`.
Andreas Gampebc802de2018-06-20 17:24:11 -07002109 oss << DumpReferenceInfo(ref, "ref", kIndent);
Roland Levillain001eff92018-01-24 14:24:33 +00002110 return oss.str();
2111}
2112
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07002113void ConcurrentCopying::AssertToSpaceInvariant(mirror::Object* obj,
2114 MemberOffset offset,
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002115 mirror::Object* ref) {
Roland Levillain001eff92018-01-24 14:24:33 +00002116 CHECK_EQ(heap_->collector_type_, kCollectorTypeCC) << static_cast<size_t>(heap_->collector_type_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002117 if (is_asserting_to_space_invariant_) {
Roland Levillain001eff92018-01-24 14:24:33 +00002118 if (region_space_->HasAddress(ref)) {
2119 // Check to-space invariant in region space (moving space).
2120 using RegionType = space::RegionSpace::RegionType;
Roland Levillain2dd2e1e2018-02-28 16:24:51 +00002121 space::RegionSpace::RegionType type = region_space_->GetRegionTypeUnsafe(ref);
Roland Levillain001eff92018-01-24 14:24:33 +00002122 if (type == RegionType::kRegionTypeToSpace) {
2123 // OK.
2124 return;
2125 } else if (type == RegionType::kRegionTypeUnevacFromSpace) {
2126 if (!IsMarkedInUnevacFromSpace(ref)) {
2127 LOG(FATAL_WITHOUT_ABORT) << "Found unmarked reference in unevac from-space:";
Roland Levillainca3dded2018-08-10 15:35:17 +01002128 // Remove memory protection from the region space and log debugging information.
2129 region_space_->Unprotect();
Roland Levillain001eff92018-01-24 14:24:33 +00002130 LOG(FATAL_WITHOUT_ABORT) << DumpHeapReference(obj, offset, ref);
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002131 Thread::Current()->DumpJavaStack(LOG_STREAM(FATAL_WITHOUT_ABORT));
Roland Levillain001eff92018-01-24 14:24:33 +00002132 }
2133 CHECK(IsMarkedInUnevacFromSpace(ref)) << ref;
2134 } else {
2135 // Not OK: either a from-space ref or a reference in an unused region.
Roland Levillain001eff92018-01-24 14:24:33 +00002136 if (type == RegionType::kRegionTypeFromSpace) {
2137 LOG(FATAL_WITHOUT_ABORT) << "Found from-space reference:";
2138 } else {
2139 LOG(FATAL_WITHOUT_ABORT) << "Found reference in region with type " << type << ":";
2140 }
Roland Levillainca3dded2018-08-10 15:35:17 +01002141 // Remove memory protection from the region space and log debugging information.
2142 region_space_->Unprotect();
Roland Levillain001eff92018-01-24 14:24:33 +00002143 LOG(FATAL_WITHOUT_ABORT) << DumpHeapReference(obj, offset, ref);
2144 if (obj != nullptr) {
2145 LogFromSpaceRefHolder(obj, offset);
Roland Levillain57ce0542018-08-07 16:20:31 +01002146 LOG(FATAL_WITHOUT_ABORT) << "UNEVAC " << region_space_->IsInUnevacFromSpace(obj) << " "
2147 << obj << " " << obj->GetMarkBit();
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002148 if (region_space_->HasAddress(obj)) {
Roland Levillain57ce0542018-08-07 16:20:31 +01002149 region_space_->DumpRegionForObject(LOG_STREAM(FATAL_WITHOUT_ABORT), obj);
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002150 }
Roland Levillain57ce0542018-08-07 16:20:31 +01002151 LOG(FATAL_WITHOUT_ABORT) << "CARD " << static_cast<size_t>(
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002152 *Runtime::Current()->GetHeap()->GetCardTable()->CardFromAddr(
2153 reinterpret_cast<uint8_t*>(obj)));
Roland Levillain57ce0542018-08-07 16:20:31 +01002154 if (region_space_->HasAddress(obj)) {
2155 LOG(FATAL_WITHOUT_ABORT) << "BITMAP " << region_space_bitmap_->Test(obj);
2156 } else {
2157 accounting::ContinuousSpaceBitmap* mark_bitmap =
2158 heap_mark_bitmap_->GetContinuousSpaceBitmap(obj);
2159 if (mark_bitmap != nullptr) {
2160 LOG(FATAL_WITHOUT_ABORT) << "BITMAP " << mark_bitmap->Test(obj);
2161 } else {
2162 accounting::LargeObjectBitmap* los_bitmap =
2163 heap_mark_bitmap_->GetLargeObjectBitmap(obj);
2164 LOG(FATAL_WITHOUT_ABORT) << "BITMAP " << los_bitmap->Test(obj);
2165 }
2166 }
Roland Levillain001eff92018-01-24 14:24:33 +00002167 }
2168 ref->GetLockWord(false).Dump(LOG_STREAM(FATAL_WITHOUT_ABORT));
2169 LOG(FATAL_WITHOUT_ABORT) << "Non-free regions:";
2170 region_space_->DumpNonFreeRegions(LOG_STREAM(FATAL_WITHOUT_ABORT));
2171 PrintFileToLog("/proc/self/maps", LogSeverity::FATAL_WITHOUT_ABORT);
Roland Levillain680e0992018-08-24 15:41:26 +01002172 MemMap::DumpMaps(LOG_STREAM(FATAL_WITHOUT_ABORT), /* terse */ true);
Roland Levillain001eff92018-01-24 14:24:33 +00002173 LOG(FATAL) << "Invalid reference " << ref
2174 << " referenced from object " << obj << " at offset " << offset;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002175 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002176 } else {
Roland Levillain001eff92018-01-24 14:24:33 +00002177 // Check to-space invariant in non-moving space.
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002178 AssertToSpaceInvariantInNonMovingSpace(obj, ref);
2179 }
2180 }
2181}
2182
2183class RootPrinter {
2184 public:
2185 RootPrinter() { }
2186
2187 template <class MirrorType>
2188 ALWAYS_INLINE void VisitRootIfNonNull(mirror::CompressedReference<MirrorType>* root)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002189 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002190 if (!root->IsNull()) {
2191 VisitRoot(root);
2192 }
2193 }
2194
2195 template <class MirrorType>
2196 void VisitRoot(mirror::Object** root)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002197 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07002198 LOG(FATAL_WITHOUT_ABORT) << "root=" << root << " ref=" << *root;
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002199 }
2200
2201 template <class MirrorType>
2202 void VisitRoot(mirror::CompressedReference<MirrorType>* root)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002203 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07002204 LOG(FATAL_WITHOUT_ABORT) << "root=" << root << " ref=" << root->AsMirrorPtr();
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002205 }
2206};
2207
Roland Levillain001eff92018-01-24 14:24:33 +00002208std::string ConcurrentCopying::DumpGcRoot(mirror::Object* ref) {
2209 std::ostringstream oss;
Andreas Gampebc802de2018-06-20 17:24:11 -07002210 constexpr const char* kIndent = " ";
2211 oss << kIndent << "Invalid GC root: ref=" << ref << '\n';
Roland Levillain001eff92018-01-24 14:24:33 +00002212 // Information about `ref`.
Andreas Gampebc802de2018-06-20 17:24:11 -07002213 oss << DumpReferenceInfo(ref, "ref", kIndent);
Roland Levillain001eff92018-01-24 14:24:33 +00002214 return oss.str();
2215}
2216
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002217void ConcurrentCopying::AssertToSpaceInvariant(GcRootSource* gc_root_source,
2218 mirror::Object* ref) {
Roland Levillain001eff92018-01-24 14:24:33 +00002219 CHECK_EQ(heap_->collector_type_, kCollectorTypeCC) << static_cast<size_t>(heap_->collector_type_);
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002220 if (is_asserting_to_space_invariant_) {
Roland Levillain001eff92018-01-24 14:24:33 +00002221 if (region_space_->HasAddress(ref)) {
2222 // Check to-space invariant in region space (moving space).
2223 using RegionType = space::RegionSpace::RegionType;
Roland Levillain2dd2e1e2018-02-28 16:24:51 +00002224 space::RegionSpace::RegionType type = region_space_->GetRegionTypeUnsafe(ref);
Roland Levillain001eff92018-01-24 14:24:33 +00002225 if (type == RegionType::kRegionTypeToSpace) {
2226 // OK.
2227 return;
2228 } else if (type == RegionType::kRegionTypeUnevacFromSpace) {
2229 if (!IsMarkedInUnevacFromSpace(ref)) {
2230 LOG(FATAL_WITHOUT_ABORT) << "Found unmarked reference in unevac from-space:";
Roland Levillainca3dded2018-08-10 15:35:17 +01002231 // Remove memory protection from the region space and log debugging information.
2232 region_space_->Unprotect();
Roland Levillain001eff92018-01-24 14:24:33 +00002233 LOG(FATAL_WITHOUT_ABORT) << DumpGcRoot(ref);
2234 }
2235 CHECK(IsMarkedInUnevacFromSpace(ref)) << ref;
2236 } else {
2237 // Not OK: either a from-space ref or a reference in an unused region.
Roland Levillain001eff92018-01-24 14:24:33 +00002238 if (type == RegionType::kRegionTypeFromSpace) {
2239 LOG(FATAL_WITHOUT_ABORT) << "Found from-space reference:";
2240 } else {
2241 LOG(FATAL_WITHOUT_ABORT) << "Found reference in region with type " << type << ":";
2242 }
Roland Levillainca3dded2018-08-10 15:35:17 +01002243 // Remove memory protection from the region space and log debugging information.
2244 region_space_->Unprotect();
Roland Levillain001eff92018-01-24 14:24:33 +00002245 LOG(FATAL_WITHOUT_ABORT) << DumpGcRoot(ref);
2246 if (gc_root_source == nullptr) {
2247 // No info.
2248 } else if (gc_root_source->HasArtField()) {
2249 ArtField* field = gc_root_source->GetArtField();
2250 LOG(FATAL_WITHOUT_ABORT) << "gc root in field " << field << " "
2251 << ArtField::PrettyField(field);
2252 RootPrinter root_printer;
2253 field->VisitRoots(root_printer);
2254 } else if (gc_root_source->HasArtMethod()) {
2255 ArtMethod* method = gc_root_source->GetArtMethod();
2256 LOG(FATAL_WITHOUT_ABORT) << "gc root in method " << method << " "
2257 << ArtMethod::PrettyMethod(method);
2258 RootPrinter root_printer;
2259 method->VisitRoots(root_printer, kRuntimePointerSize);
2260 }
2261 ref->GetLockWord(false).Dump(LOG_STREAM(FATAL_WITHOUT_ABORT));
2262 LOG(FATAL_WITHOUT_ABORT) << "Non-free regions:";
2263 region_space_->DumpNonFreeRegions(LOG_STREAM(FATAL_WITHOUT_ABORT));
2264 PrintFileToLog("/proc/self/maps", LogSeverity::FATAL_WITHOUT_ABORT);
Roland Levillain680e0992018-08-24 15:41:26 +01002265 MemMap::DumpMaps(LOG_STREAM(FATAL_WITHOUT_ABORT), /* terse */ true);
Roland Levillain001eff92018-01-24 14:24:33 +00002266 LOG(FATAL) << "Invalid reference " << ref;
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002267 }
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002268 } else {
Roland Levillain001eff92018-01-24 14:24:33 +00002269 // Check to-space invariant in non-moving space.
2270 AssertToSpaceInvariantInNonMovingSpace(/* obj */ nullptr, ref);
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002271 }
2272 }
2273}
2274
2275void ConcurrentCopying::LogFromSpaceRefHolder(mirror::Object* obj, MemberOffset offset) {
2276 if (kUseBakerReadBarrier) {
David Sehr709b0702016-10-13 09:12:37 -07002277 LOG(INFO) << "holder=" << obj << " " << obj->PrettyTypeOf()
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002278 << " holder rb_state=" << obj->GetReadBarrierState();
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002279 } else {
David Sehr709b0702016-10-13 09:12:37 -07002280 LOG(INFO) << "holder=" << obj << " " << obj->PrettyTypeOf();
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002281 }
2282 if (region_space_->IsInFromSpace(obj)) {
2283 LOG(INFO) << "holder is in the from-space.";
2284 } else if (region_space_->IsInToSpace(obj)) {
2285 LOG(INFO) << "holder is in the to-space.";
2286 } else if (region_space_->IsInUnevacFromSpace(obj)) {
2287 LOG(INFO) << "holder is in the unevac from-space.";
Mathieu Chartierc381c362016-08-23 13:27:53 -07002288 if (IsMarkedInUnevacFromSpace(obj)) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002289 LOG(INFO) << "holder is marked in the region space bitmap.";
2290 } else {
2291 LOG(INFO) << "holder is not marked in the region space bitmap.";
2292 }
2293 } else {
2294 // In a non-moving space.
Mathieu Chartier763a31e2015-11-16 16:05:55 -08002295 if (immune_spaces_.ContainsObject(obj)) {
2296 LOG(INFO) << "holder is in an immune image or the zygote space.";
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002297 } else {
Mathieu Chartier763a31e2015-11-16 16:05:55 -08002298 LOG(INFO) << "holder is in a non-immune, non-moving (or main) space.";
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002299 accounting::ContinuousSpaceBitmap* mark_bitmap =
2300 heap_mark_bitmap_->GetContinuousSpaceBitmap(obj);
2301 accounting::LargeObjectBitmap* los_bitmap =
2302 heap_mark_bitmap_->GetLargeObjectBitmap(obj);
2303 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
2304 bool is_los = mark_bitmap == nullptr;
2305 if (!is_los && mark_bitmap->Test(obj)) {
2306 LOG(INFO) << "holder is marked in the mark bit map.";
2307 } else if (is_los && los_bitmap->Test(obj)) {
2308 LOG(INFO) << "holder is marked in the los bit map.";
2309 } else {
2310 // If ref is on the allocation stack, then it is considered
2311 // mark/alive (but not necessarily on the live stack.)
2312 if (IsOnAllocStack(obj)) {
2313 LOG(INFO) << "holder is on the alloc stack.";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002314 } else {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002315 LOG(INFO) << "holder is not marked or on the alloc stack.";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002316 }
2317 }
2318 }
2319 }
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002320 LOG(INFO) << "offset=" << offset.SizeValue();
2321}
2322
2323void ConcurrentCopying::AssertToSpaceInvariantInNonMovingSpace(mirror::Object* obj,
2324 mirror::Object* ref) {
Roland Levillainbe4b8fd2018-09-03 14:38:37 +01002325 CHECK(ref != nullptr);
Roland Levillain001eff92018-01-24 14:24:33 +00002326 CHECK(!region_space_->HasAddress(ref)) << "obj=" << obj << " ref=" << ref;
Roland Levillainef012222017-06-21 16:28:06 +01002327 // In a non-moving space. Check that the ref is marked.
Mathieu Chartier763a31e2015-11-16 16:05:55 -08002328 if (immune_spaces_.ContainsObject(ref)) {
Roland Levillain8def52a2018-09-05 15:31:19 +01002329 // Immune space case.
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002330 if (kUseBakerReadBarrier) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002331 // Immune object may not be gray if called from the GC.
2332 if (Thread::Current() == thread_running_gc_ && !gc_grays_immune_objects_) {
2333 return;
2334 }
Orion Hodson88591fe2018-03-06 13:35:43 +00002335 bool updated_all_immune_objects = updated_all_immune_objects_.load(std::memory_order_seq_cst);
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002336 CHECK(updated_all_immune_objects || ref->GetReadBarrierState() == ReadBarrier::GrayState())
2337 << "Unmarked immune space ref. obj=" << obj << " rb_state="
2338 << (obj != nullptr ? obj->GetReadBarrierState() : 0U)
2339 << " ref=" << ref << " ref rb_state=" << ref->GetReadBarrierState()
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002340 << " updated_all_immune_objects=" << updated_all_immune_objects;
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002341 }
2342 } else {
Roland Levillain8def52a2018-09-05 15:31:19 +01002343 // Non-moving space and large-object space (LOS) cases.
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002344 accounting::ContinuousSpaceBitmap* mark_bitmap =
2345 heap_mark_bitmap_->GetContinuousSpaceBitmap(ref);
2346 accounting::LargeObjectBitmap* los_bitmap =
2347 heap_mark_bitmap_->GetLargeObjectBitmap(ref);
Roland Levillain8def52a2018-09-05 15:31:19 +01002348 bool is_los = (mark_bitmap == nullptr);
2349
2350 bool marked_in_non_moving_space_or_los =
2351 (kUseBakerReadBarrier
2352 && kEnableGenerationalConcurrentCopyingCollection
2353 && young_gen_
2354 && !done_scanning_.load(std::memory_order_acquire))
2355 // Don't use the mark bitmap to ensure `ref` is marked: check that the
2356 // read barrier state is gray instead. This is to take into account a
2357 // potential race between two read barriers on the same reference when the
2358 // young-generation collector is still scanning the dirty cards.
2359 //
2360 // For instance consider two concurrent read barriers on the same GC root
2361 // reference during the dirty-card-scanning step of a young-generation
2362 // collection. Both threads would call ReadBarrier::BarrierForRoot, which
2363 // would:
2364 // a. mark the reference (leading to a call to
2365 // ConcurrentCopying::MarkNonMoving); then
2366 // b. check the to-space invariant (leading to a call this
2367 // ConcurrentCopying::AssertToSpaceInvariantInNonMovingSpace -- this
2368 // method).
2369 //
2370 // In this situation, the following race could happen:
2371 // 1. Thread A successfully changes `ref`'s read barrier state from
2372 // non-gray (white) to gray (with AtomicSetReadBarrierState) in
2373 // ConcurrentCopying::MarkNonMoving, then gets preempted.
2374 // 2. Thread B also tries to change `ref`'s read barrier state with
2375 // AtomicSetReadBarrierState from non-gray to gray in
2376 // ConcurrentCopying::MarkNonMoving, but fails, as Thread A already
2377 // changed it.
2378 // 3. Because Thread B failed the previous CAS, it does *not* set the
2379 // bit in the mark bitmap for `ref`.
2380 // 4. Thread B checks the to-space invariant and calls
2381 // ConcurrentCopying::AssertToSpaceInvariantInNonMovingSpace: the bit
2382 // is not set in the mark bitmap for `ref`; checking that this bit is
2383 // set to check the to-space invariant is therefore not a reliable
2384 // test.
2385 // 5. (Note that eventually, Thread A will resume its execution and set
2386 // the bit for `ref` in the mark bitmap.)
2387 ? (ref->GetReadBarrierState() == ReadBarrier::GrayState())
2388 // It is safe to use the heap mark bitmap otherwise.
2389 : (!is_los && mark_bitmap->Test(ref)) || (is_los && los_bitmap->Test(ref));
2390
2391 // If `ref` is on the allocation stack, then it may not be
2392 // marked live, but considered marked/alive (but not
2393 // necessarily on the live stack).
2394 CHECK(marked_in_non_moving_space_or_los || IsOnAllocStack(ref))
2395 << "Unmarked ref that's not on the allocation stack."
2396 << " obj=" << obj
2397 << " ref=" << ref
2398 << " rb_state=" << ref->GetReadBarrierState()
2399 << " is_los=" << std::boolalpha << is_los << std::noboolalpha
2400 << " is_marking=" << std::boolalpha << is_marking_ << std::noboolalpha
2401 << " young_gen=" << std::boolalpha << young_gen_ << std::noboolalpha
2402 << " done_scanning="
2403 << std::boolalpha << done_scanning_.load(std::memory_order_acquire) << std::noboolalpha
2404 << " self=" << Thread::Current();
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002405 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002406}
2407
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002408// Used to scan ref fields of an object.
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002409template <bool kNoUnEvac>
Mathieu Chartiera07f5592016-06-16 11:44:28 -07002410class ConcurrentCopying::RefFieldsVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002411 public:
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002412 explicit RefFieldsVisitor(ConcurrentCopying* collector, Thread* const thread)
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002413 : collector_(collector), thread_(thread) {
2414 // Cannot have `kNoUnEvac` when Generational CC collection is disabled.
2415 DCHECK(kEnableGenerationalConcurrentCopyingCollection || !kNoUnEvac);
2416 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002417
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07002418 void operator()(mirror::Object* obj, MemberOffset offset, bool /* is_static */)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002419 const ALWAYS_INLINE REQUIRES_SHARED(Locks::mutator_lock_)
2420 REQUIRES_SHARED(Locks::heap_bitmap_lock_) {
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002421 collector_->Process<kNoUnEvac>(obj, offset);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002422 }
2423
Mathieu Chartier31e88222016-10-14 18:43:19 -07002424 void operator()(ObjPtr<mirror::Class> klass, ObjPtr<mirror::Reference> ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002425 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002426 CHECK(klass->IsTypeOfReferenceClass());
2427 collector_->DelayReferenceReferent(klass, ref);
2428 }
2429
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002430 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002431 ALWAYS_INLINE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002432 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002433 if (!root->IsNull()) {
2434 VisitRoot(root);
2435 }
2436 }
2437
2438 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002439 ALWAYS_INLINE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002440 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002441 collector_->MarkRoot</*kGrayImmuneObject*/false>(thread_, root);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002442 }
2443
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002444 private:
2445 ConcurrentCopying* const collector_;
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002446 Thread* const thread_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002447};
2448
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002449template <bool kNoUnEvac>
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002450inline void ConcurrentCopying::Scan(mirror::Object* to_ref) {
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002451 // Cannot have `kNoUnEvac` when Generational CC collection is disabled.
2452 DCHECK(kEnableGenerationalConcurrentCopyingCollection || !kNoUnEvac);
Hiroshi Yamauchi9b60d502017-02-03 15:09:26 -08002453 if (kDisallowReadBarrierDuringScan && !Runtime::Current()->IsActiveTransaction()) {
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07002454 // Avoid all read barriers during visit references to help performance.
Hiroshi Yamauchi9b60d502017-02-03 15:09:26 -08002455 // Don't do this in transaction mode because we may read the old value of an field which may
2456 // trigger read barriers.
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07002457 Thread::Current()->ModifyDebugDisallowReadBarrier(1);
2458 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002459 DCHECK(!region_space_->IsInFromSpace(to_ref));
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002460 DCHECK_EQ(Thread::Current(), thread_running_gc_);
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002461 RefFieldsVisitor<kNoUnEvac> visitor(this, thread_running_gc_);
Hiroshi Yamauchi5496f692016-02-17 13:29:59 -08002462 // Disable the read barrier for a performance reason.
2463 to_ref->VisitReferences</*kVisitNativeRoots*/true, kDefaultVerifyFlags, kWithoutReadBarrier>(
2464 visitor, visitor);
Hiroshi Yamauchi9b60d502017-02-03 15:09:26 -08002465 if (kDisallowReadBarrierDuringScan && !Runtime::Current()->IsActiveTransaction()) {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002466 thread_running_gc_->ModifyDebugDisallowReadBarrier(-1);
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07002467 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002468}
2469
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002470template <bool kNoUnEvac>
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002471inline void ConcurrentCopying::Process(mirror::Object* obj, MemberOffset offset) {
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002472 // Cannot have `kNoUnEvac` when Generational CC collection is disabled.
2473 DCHECK(kEnableGenerationalConcurrentCopyingCollection || !kNoUnEvac);
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002474 DCHECK_EQ(Thread::Current(), thread_running_gc_);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002475 mirror::Object* ref = obj->GetFieldObject<
2476 mirror::Object, kVerifyNone, kWithoutReadBarrier, false>(offset);
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002477 mirror::Object* to_ref = Mark</*kGrayImmuneObject*/false, kNoUnEvac, /*kFromGCThread*/true>(
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002478 thread_running_gc_,
Mathieu Chartier4ce0c762017-05-18 10:01:07 -07002479 ref,
2480 /*holder*/ obj,
2481 offset);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002482 if (to_ref == ref) {
2483 return;
2484 }
2485 // This may fail if the mutator writes to the field at the same time. But it's ok.
2486 mirror::Object* expected_ref = ref;
2487 mirror::Object* new_ref = to_ref;
2488 do {
2489 if (expected_ref !=
2490 obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier, false>(offset)) {
2491 // It was updated by the mutator.
2492 break;
2493 }
Roland Levillain2ae376f2018-01-30 11:35:11 +00002494 // Use release CAS to make sure threads reading the reference see contents of copied objects.
Mathieu Chartiera9746b92018-06-22 10:25:40 -07002495 } while (!obj->CasFieldObjectWithoutWriteBarrier<false, false, kVerifyNone>(
Mathieu Chartierfdd513d2017-06-01 11:26:50 -07002496 offset,
2497 expected_ref,
Mathieu Chartiera9746b92018-06-22 10:25:40 -07002498 new_ref,
2499 CASMode::kWeak,
2500 std::memory_order_release));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002501}
2502
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002503// Process some roots.
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002504inline void ConcurrentCopying::VisitRoots(
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002505 mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED) {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002506 Thread* const self = Thread::Current();
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002507 for (size_t i = 0; i < count; ++i) {
2508 mirror::Object** root = roots[i];
2509 mirror::Object* ref = *root;
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002510 mirror::Object* to_ref = Mark(self, ref);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002511 if (to_ref == ref) {
Mathieu Chartier4809d0a2015-04-07 10:39:04 -07002512 continue;
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002513 }
2514 Atomic<mirror::Object*>* addr = reinterpret_cast<Atomic<mirror::Object*>*>(root);
2515 mirror::Object* expected_ref = ref;
2516 mirror::Object* new_ref = to_ref;
2517 do {
Orion Hodson88591fe2018-03-06 13:35:43 +00002518 if (expected_ref != addr->load(std::memory_order_relaxed)) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002519 // It was updated by the mutator.
2520 break;
2521 }
Orion Hodson4557b382018-01-03 11:47:54 +00002522 } while (!addr->CompareAndSetWeakRelaxed(expected_ref, new_ref));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002523 }
2524}
2525
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002526template<bool kGrayImmuneObject>
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002527inline void ConcurrentCopying::MarkRoot(Thread* const self,
2528 mirror::CompressedReference<mirror::Object>* root) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002529 DCHECK(!root->IsNull());
2530 mirror::Object* const ref = root->AsMirrorPtr();
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002531 mirror::Object* to_ref = Mark<kGrayImmuneObject>(self, ref);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002532 if (to_ref != ref) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002533 auto* addr = reinterpret_cast<Atomic<mirror::CompressedReference<mirror::Object>>*>(root);
2534 auto expected_ref = mirror::CompressedReference<mirror::Object>::FromMirrorPtr(ref);
2535 auto new_ref = mirror::CompressedReference<mirror::Object>::FromMirrorPtr(to_ref);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002536 // If the cas fails, then it was updated by the mutator.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002537 do {
Orion Hodson88591fe2018-03-06 13:35:43 +00002538 if (ref != addr->load(std::memory_order_relaxed).AsMirrorPtr()) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002539 // It was updated by the mutator.
2540 break;
2541 }
Orion Hodson4557b382018-01-03 11:47:54 +00002542 } while (!addr->CompareAndSetWeakRelaxed(expected_ref, new_ref));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002543 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002544}
2545
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002546inline void ConcurrentCopying::VisitRoots(
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002547 mirror::CompressedReference<mirror::Object>** roots, size_t count,
2548 const RootInfo& info ATTRIBUTE_UNUSED) {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002549 Thread* const self = Thread::Current();
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002550 for (size_t i = 0; i < count; ++i) {
2551 mirror::CompressedReference<mirror::Object>* const root = roots[i];
2552 if (!root->IsNull()) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002553 // kGrayImmuneObject is true because this is used for the thread flip.
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002554 MarkRoot</*kGrayImmuneObject*/true>(self, root);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002555 }
2556 }
2557}
2558
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002559// Temporary set gc_grays_immune_objects_ to true in a scope if the current thread is GC.
2560class ConcurrentCopying::ScopedGcGraysImmuneObjects {
2561 public:
2562 explicit ScopedGcGraysImmuneObjects(ConcurrentCopying* collector)
2563 : collector_(collector), enabled_(false) {
2564 if (kUseBakerReadBarrier &&
2565 collector_->thread_running_gc_ == Thread::Current() &&
2566 !collector_->gc_grays_immune_objects_) {
2567 collector_->gc_grays_immune_objects_ = true;
2568 enabled_ = true;
2569 }
2570 }
2571
2572 ~ScopedGcGraysImmuneObjects() {
2573 if (kUseBakerReadBarrier &&
2574 collector_->thread_running_gc_ == Thread::Current() &&
2575 enabled_) {
2576 DCHECK(collector_->gc_grays_immune_objects_);
2577 collector_->gc_grays_immune_objects_ = false;
2578 }
2579 }
2580
2581 private:
2582 ConcurrentCopying* const collector_;
2583 bool enabled_;
2584};
2585
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002586// Fill the given memory block with a dummy object. Used to fill in a
2587// copy of objects that was lost in race.
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002588void ConcurrentCopying::FillWithDummyObject(Thread* const self,
2589 mirror::Object* dummy_obj,
2590 size_t byte_size) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002591 // GC doesn't gray immune objects while scanning immune objects. But we need to trigger the read
2592 // barriers here because we need the updated reference to the int array class, etc. Temporary set
2593 // gc_grays_immune_objects_ to true so that we won't cause a DCHECK failure in MarkImmuneSpace().
2594 ScopedGcGraysImmuneObjects scoped_gc_gray_immune_objects(this);
Roland Levillain14d90572015-07-16 10:52:26 +01002595 CHECK_ALIGNED(byte_size, kObjectAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002596 memset(dummy_obj, 0, byte_size);
Mathieu Chartierd6636d32016-07-28 11:02:38 -07002597 // Avoid going through read barrier for since kDisallowReadBarrierDuringScan may be enabled.
2598 // Explicitly mark to make sure to get an object in the to-space.
2599 mirror::Class* int_array_class = down_cast<mirror::Class*>(
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002600 Mark(self, GetClassRoot<mirror::IntArray, kWithoutReadBarrier>().Ptr()));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002601 CHECK(int_array_class != nullptr);
Andreas Gampe6c578712017-10-19 13:00:34 -07002602 if (ReadBarrier::kEnableToSpaceInvariantChecks) {
2603 AssertToSpaceInvariant(nullptr, MemberOffset(0), int_array_class);
2604 }
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07002605 size_t component_size = int_array_class->GetComponentSize<kWithoutReadBarrier>();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002606 CHECK_EQ(component_size, sizeof(int32_t));
2607 size_t data_offset = mirror::Array::DataOffset(component_size).SizeValue();
2608 if (data_offset > byte_size) {
2609 // An int array is too big. Use java.lang.Object.
Mathieu Chartier9aef9922017-04-23 13:53:50 -07002610 CHECK(java_lang_Object_ != nullptr);
Andreas Gampe6c578712017-10-19 13:00:34 -07002611 if (ReadBarrier::kEnableToSpaceInvariantChecks) {
2612 AssertToSpaceInvariant(nullptr, MemberOffset(0), java_lang_Object_);
2613 }
Mathieu Chartier3ed8ec12017-04-20 19:28:54 -07002614 CHECK_EQ(byte_size, (java_lang_Object_->GetObjectSize<kVerifyNone, kWithoutReadBarrier>()));
2615 dummy_obj->SetClass(java_lang_Object_);
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07002616 CHECK_EQ(byte_size, (dummy_obj->SizeOf<kVerifyNone>()));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002617 } else {
2618 // Use an int array.
2619 dummy_obj->SetClass(int_array_class);
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07002620 CHECK((dummy_obj->IsArrayInstance<kVerifyNone, kWithoutReadBarrier>()));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002621 int32_t length = (byte_size - data_offset) / component_size;
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07002622 mirror::Array* dummy_arr = dummy_obj->AsArray<kVerifyNone, kWithoutReadBarrier>();
2623 dummy_arr->SetLength(length);
2624 CHECK_EQ(dummy_arr->GetLength(), length)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002625 << "byte_size=" << byte_size << " length=" << length
2626 << " component_size=" << component_size << " data_offset=" << data_offset;
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07002627 CHECK_EQ(byte_size, (dummy_obj->SizeOf<kVerifyNone>()))
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002628 << "byte_size=" << byte_size << " length=" << length
2629 << " component_size=" << component_size << " data_offset=" << data_offset;
2630 }
2631}
2632
2633// Reuse the memory blocks that were copy of objects that were lost in race.
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002634mirror::Object* ConcurrentCopying::AllocateInSkippedBlock(Thread* const self, size_t alloc_size) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002635 // Try to reuse the blocks that were unused due to CAS failures.
Roland Levillain14d90572015-07-16 10:52:26 +01002636 CHECK_ALIGNED(alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002637 size_t min_object_size = RoundUp(sizeof(mirror::Object), space::RegionSpace::kAlignment);
Mathieu Chartierd6636d32016-07-28 11:02:38 -07002638 size_t byte_size;
2639 uint8_t* addr;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002640 {
Mathieu Chartierd6636d32016-07-28 11:02:38 -07002641 MutexLock mu(self, skipped_blocks_lock_);
2642 auto it = skipped_blocks_map_.lower_bound(alloc_size);
2643 if (it == skipped_blocks_map_.end()) {
2644 // Not found.
2645 return nullptr;
2646 }
2647 byte_size = it->first;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002648 CHECK_GE(byte_size, alloc_size);
2649 if (byte_size > alloc_size && byte_size - alloc_size < min_object_size) {
2650 // If remainder would be too small for a dummy object, retry with a larger request size.
2651 it = skipped_blocks_map_.lower_bound(alloc_size + min_object_size);
2652 if (it == skipped_blocks_map_.end()) {
2653 // Not found.
2654 return nullptr;
2655 }
Roland Levillain14d90572015-07-16 10:52:26 +01002656 CHECK_ALIGNED(it->first - alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002657 CHECK_GE(it->first - alloc_size, min_object_size)
2658 << "byte_size=" << byte_size << " it->first=" << it->first << " alloc_size=" << alloc_size;
2659 }
Mathieu Chartierd6636d32016-07-28 11:02:38 -07002660 // Found a block.
2661 CHECK(it != skipped_blocks_map_.end());
2662 byte_size = it->first;
2663 addr = it->second;
2664 CHECK_GE(byte_size, alloc_size);
2665 CHECK(region_space_->IsInToSpace(reinterpret_cast<mirror::Object*>(addr)));
2666 CHECK_ALIGNED(byte_size, space::RegionSpace::kAlignment);
2667 if (kVerboseMode) {
2668 LOG(INFO) << "Reusing skipped bytes : " << reinterpret_cast<void*>(addr) << ", " << byte_size;
2669 }
2670 skipped_blocks_map_.erase(it);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002671 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002672 memset(addr, 0, byte_size);
2673 if (byte_size > alloc_size) {
2674 // Return the remainder to the map.
Roland Levillain14d90572015-07-16 10:52:26 +01002675 CHECK_ALIGNED(byte_size - alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002676 CHECK_GE(byte_size - alloc_size, min_object_size);
Mathieu Chartierd6636d32016-07-28 11:02:38 -07002677 // FillWithDummyObject may mark an object, avoid holding skipped_blocks_lock_ to prevent lock
2678 // violation and possible deadlock. The deadlock case is a recursive case:
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002679 // FillWithDummyObject -> Mark(IntArray.class) -> Copy -> AllocateInSkippedBlock.
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002680 FillWithDummyObject(self,
2681 reinterpret_cast<mirror::Object*>(addr + alloc_size),
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002682 byte_size - alloc_size);
2683 CHECK(region_space_->IsInToSpace(reinterpret_cast<mirror::Object*>(addr + alloc_size)));
Mathieu Chartierd6636d32016-07-28 11:02:38 -07002684 {
2685 MutexLock mu(self, skipped_blocks_lock_);
2686 skipped_blocks_map_.insert(std::make_pair(byte_size - alloc_size, addr + alloc_size));
2687 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002688 }
2689 return reinterpret_cast<mirror::Object*>(addr);
2690}
2691
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002692mirror::Object* ConcurrentCopying::Copy(Thread* const self,
2693 mirror::Object* from_ref,
Mathieu Chartieref496d92017-04-28 18:58:59 -07002694 mirror::Object* holder,
2695 MemberOffset offset) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002696 DCHECK(region_space_->IsInFromSpace(from_ref));
Mathieu Chartieref496d92017-04-28 18:58:59 -07002697 // If the class pointer is null, the object is invalid. This could occur for a dangling pointer
2698 // from a previous GC that is either inside or outside the allocated region.
2699 mirror::Class* klass = from_ref->GetClass<kVerifyNone, kWithoutReadBarrier>();
2700 if (UNLIKELY(klass == nullptr)) {
Roland Levillainca3dded2018-08-10 15:35:17 +01002701 // Remove memory protection from the region space and log debugging information.
2702 region_space_->Unprotect();
Mathieu Chartieref496d92017-04-28 18:58:59 -07002703 heap_->GetVerification()->LogHeapCorruption(holder, offset, from_ref, /* fatal */ true);
2704 }
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07002705 // There must not be a read barrier to avoid nested RB that might violate the to-space invariant.
2706 // Note that from_ref is a from space ref so the SizeOf() call will access the from-space meta
2707 // objects, but it's ok and necessary.
2708 size_t obj_size = from_ref->SizeOf<kDefaultVerifyFlags>();
Nicolas Geoffray4b361a82017-07-06 15:30:10 +01002709 size_t region_space_alloc_size = (obj_size <= space::RegionSpace::kRegionSize)
2710 ? RoundUp(obj_size, space::RegionSpace::kAlignment)
2711 : RoundUp(obj_size, space::RegionSpace::kRegionSize);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002712 size_t region_space_bytes_allocated = 0U;
2713 size_t non_moving_space_bytes_allocated = 0U;
2714 size_t bytes_allocated = 0U;
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07002715 size_t dummy;
Lokesh Gidraf2a69312018-03-27 18:48:59 -07002716 bool fall_back_to_non_moving = false;
Lokesh Gidrab4f15412018-01-05 18:29:34 -08002717 mirror::Object* to_ref = region_space_->AllocNonvirtual</*kForEvac*/ true>(
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07002718 region_space_alloc_size, &region_space_bytes_allocated, nullptr, &dummy);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002719 bytes_allocated = region_space_bytes_allocated;
Lokesh Gidraf2a69312018-03-27 18:48:59 -07002720 if (LIKELY(to_ref != nullptr)) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002721 DCHECK_EQ(region_space_alloc_size, region_space_bytes_allocated);
Lokesh Gidraf2a69312018-03-27 18:48:59 -07002722 } else {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002723 // Failed to allocate in the region space. Try the skipped blocks.
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002724 to_ref = AllocateInSkippedBlock(self, region_space_alloc_size);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002725 if (to_ref != nullptr) {
2726 // Succeeded to allocate in a skipped block.
2727 if (heap_->use_tlab_) {
2728 // This is necessary for the tlab case as it's not accounted in the space.
2729 region_space_->RecordAlloc(to_ref);
2730 }
2731 bytes_allocated = region_space_alloc_size;
Lokesh Gidraf2a69312018-03-27 18:48:59 -07002732 heap_->num_bytes_allocated_.fetch_sub(bytes_allocated, std::memory_order_seq_cst);
2733 to_space_bytes_skipped_.fetch_sub(bytes_allocated, std::memory_order_seq_cst);
2734 to_space_objects_skipped_.fetch_sub(1, std::memory_order_seq_cst);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002735 } else {
2736 // Fall back to the non-moving space.
2737 fall_back_to_non_moving = true;
2738 if (kVerboseMode) {
2739 LOG(INFO) << "Out of memory in the to-space. Fall back to non-moving. skipped_bytes="
Orion Hodson88591fe2018-03-06 13:35:43 +00002740 << to_space_bytes_skipped_.load(std::memory_order_seq_cst)
2741 << " skipped_objects="
2742 << to_space_objects_skipped_.load(std::memory_order_seq_cst);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002743 }
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002744 to_ref = heap_->non_moving_space_->Alloc(self, obj_size,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07002745 &non_moving_space_bytes_allocated, nullptr, &dummy);
Mathieu Chartierb01335c2017-03-22 13:15:01 -07002746 if (UNLIKELY(to_ref == nullptr)) {
2747 LOG(FATAL_WITHOUT_ABORT) << "Fall-back non-moving space allocation failed for a "
2748 << obj_size << " byte object in region type "
2749 << region_space_->GetRegionType(from_ref);
2750 LOG(FATAL) << "Object address=" << from_ref << " type=" << from_ref->PrettyTypeOf();
2751 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002752 bytes_allocated = non_moving_space_bytes_allocated;
2753 // Mark it in the mark bitmap.
2754 accounting::ContinuousSpaceBitmap* mark_bitmap =
2755 heap_mark_bitmap_->GetContinuousSpaceBitmap(to_ref);
2756 CHECK(mark_bitmap != nullptr);
Roland Levillain5c54d862018-01-17 14:46:24 +00002757 bool previously_marked_in_bitmap = mark_bitmap->AtomicTestAndSet(to_ref);
2758 CHECK(!previously_marked_in_bitmap);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002759 }
2760 }
2761 DCHECK(to_ref != nullptr);
2762
Mathieu Chartierd818adb2016-09-15 13:12:47 -07002763 // Copy the object excluding the lock word since that is handled in the loop.
Mathieu Chartieref496d92017-04-28 18:58:59 -07002764 to_ref->SetClass(klass);
Mathieu Chartierd818adb2016-09-15 13:12:47 -07002765 const size_t kObjectHeaderSize = sizeof(mirror::Object);
2766 DCHECK_GE(obj_size, kObjectHeaderSize);
2767 static_assert(kObjectHeaderSize == sizeof(mirror::HeapReference<mirror::Class>) +
2768 sizeof(LockWord),
2769 "Object header size does not match");
2770 // Memcpy can tear for words since it may do byte copy. It is only safe to do this since the
2771 // object in the from space is immutable other than the lock word. b/31423258
2772 memcpy(reinterpret_cast<uint8_t*>(to_ref) + kObjectHeaderSize,
2773 reinterpret_cast<const uint8_t*>(from_ref) + kObjectHeaderSize,
2774 obj_size - kObjectHeaderSize);
2775
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002776 // Attempt to install the forward pointer. This is in a loop as the
2777 // lock word atomic write can fail.
2778 while (true) {
Mathieu Chartierd818adb2016-09-15 13:12:47 -07002779 LockWord old_lock_word = from_ref->GetLockWord(false);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002780
2781 if (old_lock_word.GetState() == LockWord::kForwardingAddress) {
2782 // Lost the race. Another thread (either GC or mutator) stored
2783 // the forwarding pointer first. Make the lost copy (to_ref)
2784 // look like a valid but dead (dummy) object and keep it for
2785 // future reuse.
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002786 FillWithDummyObject(self, to_ref, bytes_allocated);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002787 if (!fall_back_to_non_moving) {
2788 DCHECK(region_space_->IsInToSpace(to_ref));
2789 if (bytes_allocated > space::RegionSpace::kRegionSize) {
2790 // Free the large alloc.
Lokesh Gidrab4f15412018-01-05 18:29:34 -08002791 region_space_->FreeLarge</*kForEvac*/ true>(to_ref, bytes_allocated);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002792 } else {
2793 // Record the lost copy for later reuse.
Orion Hodson88591fe2018-03-06 13:35:43 +00002794 heap_->num_bytes_allocated_.fetch_add(bytes_allocated, std::memory_order_seq_cst);
2795 to_space_bytes_skipped_.fetch_add(bytes_allocated, std::memory_order_seq_cst);
2796 to_space_objects_skipped_.fetch_add(1, std::memory_order_seq_cst);
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002797 MutexLock mu(self, skipped_blocks_lock_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002798 skipped_blocks_map_.insert(std::make_pair(bytes_allocated,
2799 reinterpret_cast<uint8_t*>(to_ref)));
2800 }
2801 } else {
2802 DCHECK(heap_->non_moving_space_->HasAddress(to_ref));
2803 DCHECK_EQ(bytes_allocated, non_moving_space_bytes_allocated);
2804 // Free the non-moving-space chunk.
2805 accounting::ContinuousSpaceBitmap* mark_bitmap =
2806 heap_mark_bitmap_->GetContinuousSpaceBitmap(to_ref);
2807 CHECK(mark_bitmap != nullptr);
2808 CHECK(mark_bitmap->Clear(to_ref));
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002809 heap_->non_moving_space_->Free(self, to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002810 }
2811
2812 // Get the winner's forward ptr.
2813 mirror::Object* lost_fwd_ptr = to_ref;
2814 to_ref = reinterpret_cast<mirror::Object*>(old_lock_word.ForwardingAddress());
2815 CHECK(to_ref != nullptr);
2816 CHECK_NE(to_ref, lost_fwd_ptr);
Mathieu Chartierdfcd6f42016-09-13 10:02:48 -07002817 CHECK(region_space_->IsInToSpace(to_ref) || heap_->non_moving_space_->HasAddress(to_ref))
2818 << "to_ref=" << to_ref << " " << heap_->DumpSpaces();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002819 CHECK_NE(to_ref->GetLockWord(false).GetState(), LockWord::kForwardingAddress);
2820 return to_ref;
2821 }
2822
Mathieu Chartierd818adb2016-09-15 13:12:47 -07002823 // Copy the old lock word over since we did not copy it yet.
2824 to_ref->SetLockWord(old_lock_word, false);
Hiroshi Yamauchi60f63f52015-04-23 16:12:40 -07002825 // Set the gray ptr.
2826 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002827 to_ref->SetReadBarrierState(ReadBarrier::GrayState());
Hiroshi Yamauchi60f63f52015-04-23 16:12:40 -07002828 }
2829
Mathieu Chartiera8131262016-11-29 17:55:19 -08002830 // Do a fence to prevent the field CAS in ConcurrentCopying::Process from possibly reordering
2831 // before the object copy.
Orion Hodson27b96762018-03-13 16:06:57 +00002832 std::atomic_thread_fence(std::memory_order_release);
Mathieu Chartiera8131262016-11-29 17:55:19 -08002833
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002834 LockWord new_lock_word = LockWord::FromForwardingAddress(reinterpret_cast<size_t>(to_ref));
2835
2836 // Try to atomically write the fwd ptr.
Mathieu Chartier42c2e502018-06-19 12:30:56 -07002837 bool success = from_ref->CasLockWord(old_lock_word,
2838 new_lock_word,
2839 CASMode::kWeak,
2840 std::memory_order_relaxed);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002841 if (LIKELY(success)) {
2842 // The CAS succeeded.
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002843 DCHECK(thread_running_gc_ != nullptr);
2844 if (LIKELY(self == thread_running_gc_)) {
2845 objects_moved_gc_thread_ += 1;
2846 bytes_moved_gc_thread_ += region_space_alloc_size;
2847 } else {
2848 objects_moved_.fetch_add(1, std::memory_order_relaxed);
2849 bytes_moved_.fetch_add(region_space_alloc_size, std::memory_order_relaxed);
2850 }
2851
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002852 if (LIKELY(!fall_back_to_non_moving)) {
2853 DCHECK(region_space_->IsInToSpace(to_ref));
2854 } else {
2855 DCHECK(heap_->non_moving_space_->HasAddress(to_ref));
2856 DCHECK_EQ(bytes_allocated, non_moving_space_bytes_allocated);
2857 }
2858 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002859 DCHECK(to_ref->GetReadBarrierState() == ReadBarrier::GrayState());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002860 }
2861 DCHECK(GetFwdPtr(from_ref) == to_ref);
2862 CHECK_NE(to_ref->GetLockWord(false).GetState(), LockWord::kForwardingAddress);
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002863 PushOntoMarkStack(self, to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002864 return to_ref;
2865 } else {
2866 // The CAS failed. It may have lost the race or may have failed
2867 // due to monitor/hashcode ops. Either way, retry.
2868 }
2869 }
2870}
2871
2872mirror::Object* ConcurrentCopying::IsMarked(mirror::Object* from_ref) {
2873 DCHECK(from_ref != nullptr);
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08002874 space::RegionSpace::RegionType rtype = region_space_->GetRegionType(from_ref);
2875 if (rtype == space::RegionSpace::RegionType::kRegionTypeToSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002876 // It's already marked.
2877 return from_ref;
2878 }
2879 mirror::Object* to_ref;
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08002880 if (rtype == space::RegionSpace::RegionType::kRegionTypeFromSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002881 to_ref = GetFwdPtr(from_ref);
2882 DCHECK(to_ref == nullptr || region_space_->IsInToSpace(to_ref) ||
2883 heap_->non_moving_space_->HasAddress(to_ref))
2884 << "from_ref=" << from_ref << " to_ref=" << to_ref;
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08002885 } else if (rtype == space::RegionSpace::RegionType::kRegionTypeUnevacFromSpace) {
Mathieu Chartierc381c362016-08-23 13:27:53 -07002886 if (IsMarkedInUnevacFromSpace(from_ref)) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002887 to_ref = from_ref;
2888 } else {
2889 to_ref = nullptr;
2890 }
2891 } else {
Roland Levillain001eff92018-01-24 14:24:33 +00002892 // At this point, `from_ref` should not be in the region space
2893 // (i.e. within an "unused" region).
2894 DCHECK(!region_space_->HasAddress(from_ref)) << from_ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002895 // from_ref is in a non-moving space.
Mathieu Chartier763a31e2015-11-16 16:05:55 -08002896 if (immune_spaces_.ContainsObject(from_ref)) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002897 // An immune object is alive.
2898 to_ref = from_ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002899 } else {
2900 // Non-immune non-moving space. Use the mark bitmap.
2901 accounting::ContinuousSpaceBitmap* mark_bitmap =
2902 heap_mark_bitmap_->GetContinuousSpaceBitmap(from_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002903 bool is_los = mark_bitmap == nullptr;
2904 if (!is_los && mark_bitmap->Test(from_ref)) {
2905 // Already marked.
2906 to_ref = from_ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002907 } else {
Mathieu Chartier47863bb2017-08-04 11:30:27 -07002908 accounting::LargeObjectBitmap* los_bitmap =
2909 heap_mark_bitmap_->GetLargeObjectBitmap(from_ref);
2910 // We may not have a large object space for dex2oat, don't assume it exists.
2911 if (los_bitmap == nullptr) {
2912 CHECK(heap_->GetLargeObjectsSpace() == nullptr)
2913 << "LOS bitmap covers the entire address range " << from_ref
2914 << " " << heap_->DumpSpaces();
2915 }
2916 if (los_bitmap != nullptr && is_los && los_bitmap->Test(from_ref)) {
2917 // Already marked in LOS.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002918 to_ref = from_ref;
2919 } else {
2920 // Not marked.
Mathieu Chartier47863bb2017-08-04 11:30:27 -07002921 if (IsOnAllocStack(from_ref)) {
2922 // If on the allocation stack, it's considered marked.
2923 to_ref = from_ref;
2924 } else {
2925 // Not marked.
2926 to_ref = nullptr;
2927 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002928 }
2929 }
2930 }
2931 }
2932 return to_ref;
2933}
2934
2935bool ConcurrentCopying::IsOnAllocStack(mirror::Object* ref) {
Hans Boehmcc55e1d2017-07-27 15:28:07 -07002936 // TODO: Explain why this is here. What release operation does it pair with?
Orion Hodson27b96762018-03-13 16:06:57 +00002937 std::atomic_thread_fence(std::memory_order_acquire);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002938 accounting::ObjectStack* alloc_stack = GetAllocationStack();
Mathieu Chartiercb535da2015-01-23 13:50:03 -08002939 return alloc_stack->Contains(ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002940}
2941
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002942mirror::Object* ConcurrentCopying::MarkNonMoving(Thread* const self,
2943 mirror::Object* ref,
Mathieu Chartier1ca68902017-04-18 11:26:22 -07002944 mirror::Object* holder,
2945 MemberOffset offset) {
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002946 // ref is in a non-moving space (from_ref == to_ref).
2947 DCHECK(!region_space_->HasAddress(ref)) << ref;
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002948 DCHECK(!immune_spaces_.ContainsObject(ref));
2949 // Use the mark bitmap.
2950 accounting::ContinuousSpaceBitmap* mark_bitmap =
2951 heap_mark_bitmap_->GetContinuousSpaceBitmap(ref);
2952 accounting::LargeObjectBitmap* los_bitmap =
2953 heap_mark_bitmap_->GetLargeObjectBitmap(ref);
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002954 bool is_los = mark_bitmap == nullptr;
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002955 if (kEnableGenerationalConcurrentCopyingCollection && young_gen_) {
Roland Levillainade74a62018-08-08 15:55:42 +01002956 // The sticky-bit CC collector is only compatible with Baker-style read barriers.
2957 DCHECK(kUseBakerReadBarrier);
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002958 // Not done scanning, use AtomicSetReadBarrierPointer.
Roland Levillain2d94e292018-08-15 16:46:30 +01002959 if (!done_scanning_.load(std::memory_order_acquire)) {
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002960 // 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 +01002961 // mutator may see references to the from space. Instead, use the Baker pointer itself as
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002962 // the mark bit.
2963 if (ref->AtomicSetReadBarrierState(ReadBarrier::NonGrayState(), ReadBarrier::GrayState())) {
2964 // TODO: We don't actually need to scan this object later, we just need to clear the gray
2965 // bit.
2966 // Also make sure the object is marked.
2967 if (is_los) {
2968 los_bitmap->AtomicTestAndSet(ref);
2969 } else {
2970 mark_bitmap->AtomicTestAndSet(ref);
2971 }
2972 PushOntoMarkStack(self, ref);
2973 }
2974 return ref;
2975 }
2976 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002977 if (!is_los && mark_bitmap->Test(ref)) {
2978 // Already marked.
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002979 } else if (is_los && los_bitmap->Test(ref)) {
2980 // Already marked in LOS.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002981 } else {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002982 // Not marked.
2983 if (IsOnAllocStack(ref)) {
Roland Levillain14e5a292018-06-28 12:00:56 +01002984 // If it's on the allocation stack, it's considered marked. Keep it white (non-gray).
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002985 // Objects on the allocation stack need not be marked.
2986 if (!is_los) {
2987 DCHECK(!mark_bitmap->Test(ref));
2988 } else {
2989 DCHECK(!los_bitmap->Test(ref));
Nicolas Geoffrayddeb1722016-06-28 08:25:59 +00002990 }
Nicolas Geoffrayddeb1722016-06-28 08:25:59 +00002991 if (kUseBakerReadBarrier) {
Roland Levillain14e5a292018-06-28 12:00:56 +01002992 DCHECK_EQ(ref->GetReadBarrierState(), ReadBarrier::NonGrayState());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002993 }
2994 } else {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002995 // For the baker-style RB, we need to handle 'false-gray' cases. See the
2996 // kRegionTypeUnevacFromSpace-case comment in Mark().
2997 if (kUseBakerReadBarrier) {
2998 // Test the bitmap first to reduce the chance of false gray cases.
2999 if ((!is_los && mark_bitmap->Test(ref)) ||
3000 (is_los && los_bitmap->Test(ref))) {
3001 return ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003002 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07003003 }
Mathieu Chartier1ca68902017-04-18 11:26:22 -07003004 if (is_los && !IsAligned<kPageSize>(ref)) {
Roland Levillainca3dded2018-08-10 15:35:17 +01003005 // Ref is a large object that is not aligned, it must be heap
3006 // corruption. Remove memory protection and dump data before
3007 // AtomicSetReadBarrierState since it will fault if the address is not
3008 // valid.
3009 region_space_->Unprotect();
Mathieu Chartieref496d92017-04-28 18:58:59 -07003010 heap_->GetVerification()->LogHeapCorruption(holder, offset, ref, /* fatal */ true);
Mathieu Chartier1ca68902017-04-18 11:26:22 -07003011 }
Roland Levillain14e5a292018-06-28 12:00:56 +01003012 // Not marked nor on the allocation stack. Try to mark it.
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07003013 // This may or may not succeed, which is ok.
3014 bool cas_success = false;
3015 if (kUseBakerReadBarrier) {
Roland Levillain14e5a292018-06-28 12:00:56 +01003016 cas_success = ref->AtomicSetReadBarrierState(ReadBarrier::NonGrayState(),
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07003017 ReadBarrier::GrayState());
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07003018 }
3019 if (!is_los && mark_bitmap->AtomicTestAndSet(ref)) {
3020 // Already marked.
Roland Levillain14e5a292018-06-28 12:00:56 +01003021 if (kUseBakerReadBarrier &&
3022 cas_success &&
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07003023 ref->GetReadBarrierState() == ReadBarrier::GrayState()) {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08003024 PushOntoFalseGrayStack(self, ref);
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07003025 }
3026 } else if (is_los && los_bitmap->AtomicTestAndSet(ref)) {
3027 // Already marked in LOS.
Roland Levillain14e5a292018-06-28 12:00:56 +01003028 if (kUseBakerReadBarrier &&
3029 cas_success &&
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07003030 ref->GetReadBarrierState() == ReadBarrier::GrayState()) {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08003031 PushOntoFalseGrayStack(self, ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003032 }
3033 } else {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07003034 // Newly marked.
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08003035 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07003036 DCHECK_EQ(ref->GetReadBarrierState(), ReadBarrier::GrayState());
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08003037 }
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08003038 PushOntoMarkStack(self, ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003039 }
3040 }
3041 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07003042 return ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003043}
3044
3045void ConcurrentCopying::FinishPhase() {
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -08003046 Thread* const self = Thread::Current();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07003047 {
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -08003048 MutexLock mu(self, mark_stack_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07003049 CHECK_EQ(pooled_mark_stacks_.size(), kMarkStackPoolSize);
3050 }
Mathieu Chartiera1467d02017-02-22 09:22:50 -08003051 // kVerifyNoMissingCardMarks relies on the region space cards not being cleared to avoid false
3052 // positives.
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07003053 if (!kEnableGenerationalConcurrentCopyingCollection && !kVerifyNoMissingCardMarks) {
Mathieu Chartier6e6078a2016-10-24 15:45:41 -07003054 TimingLogger::ScopedTiming split("ClearRegionSpaceCards", GetTimings());
3055 // We do not currently use the region space cards at all, madvise them away to save ram.
3056 heap_->GetCardTable()->ClearCardRange(region_space_->Begin(), region_space_->Limit());
Mathieu Chartier6e6078a2016-10-24 15:45:41 -07003057 }
3058 {
3059 MutexLock mu(self, skipped_blocks_lock_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003060 skipped_blocks_map_.clear();
3061 }
Mathieu Chartier56fe2582016-07-14 13:30:03 -07003062 {
3063 ReaderMutexLock mu(self, *Locks::mutator_lock_);
Mathieu Chartier21328a12016-07-22 10:47:45 -07003064 {
3065 WriterMutexLock mu2(self, *Locks::heap_bitmap_lock_);
3066 heap_->ClearMarkedObjects();
3067 }
3068 if (kUseBakerReadBarrier && kFilterModUnionCards) {
3069 TimingLogger::ScopedTiming split("FilterModUnionCards", GetTimings());
3070 ReaderMutexLock mu2(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier21328a12016-07-22 10:47:45 -07003071 for (space::ContinuousSpace* space : immune_spaces_.GetSpaces()) {
3072 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
Mathieu Chartier6e6078a2016-10-24 15:45:41 -07003073 accounting::ModUnionTable* table = heap_->FindModUnionTableFromSpace(space);
Mathieu Chartier21328a12016-07-22 10:47:45 -07003074 // Filter out cards that don't need to be set.
3075 if (table != nullptr) {
3076 table->FilterCards();
3077 }
3078 }
3079 }
Mathieu Chartier36a270a2016-07-28 18:08:51 -07003080 if (kUseBakerReadBarrier) {
3081 TimingLogger::ScopedTiming split("EmptyRBMarkBitStack", GetTimings());
Mathieu Chartier6e6078a2016-10-24 15:45:41 -07003082 DCHECK(rb_mark_bit_stack_ != nullptr);
Mathieu Chartier36a270a2016-07-28 18:08:51 -07003083 const auto* limit = rb_mark_bit_stack_->End();
3084 for (StackReference<mirror::Object>* it = rb_mark_bit_stack_->Begin(); it != limit; ++it) {
Roland Levillain001eff92018-01-24 14:24:33 +00003085 CHECK(it->AsMirrorPtr()->AtomicSetMarkBit(1, 0))
3086 << "rb_mark_bit_stack_->Begin()" << rb_mark_bit_stack_->Begin() << '\n'
3087 << "rb_mark_bit_stack_->End()" << rb_mark_bit_stack_->End() << '\n'
3088 << "rb_mark_bit_stack_->IsFull()"
3089 << std::boolalpha << rb_mark_bit_stack_->IsFull() << std::noboolalpha << '\n'
3090 << DumpReferenceInfo(it->AsMirrorPtr(), "*it");
Mathieu Chartier36a270a2016-07-28 18:08:51 -07003091 }
3092 rb_mark_bit_stack_->Reset();
3093 }
Mathieu Chartier56fe2582016-07-14 13:30:03 -07003094 }
3095 if (measure_read_barrier_slow_path_) {
3096 MutexLock mu(self, rb_slow_path_histogram_lock_);
Orion Hodson88591fe2018-03-06 13:35:43 +00003097 rb_slow_path_time_histogram_.AdjustAndAddValue(
3098 rb_slow_path_ns_.load(std::memory_order_relaxed));
3099 rb_slow_path_count_total_ += rb_slow_path_count_.load(std::memory_order_relaxed);
3100 rb_slow_path_count_gc_total_ += rb_slow_path_count_gc_.load(std::memory_order_relaxed);
Mathieu Chartier56fe2582016-07-14 13:30:03 -07003101 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003102}
3103
Hiroshi Yamauchi65f5f242016-12-19 11:44:47 -08003104bool ConcurrentCopying::IsNullOrMarkedHeapReference(mirror::HeapReference<mirror::Object>* field,
3105 bool do_atomic_update) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003106 mirror::Object* from_ref = field->AsMirrorPtr();
Hiroshi Yamauchi65f5f242016-12-19 11:44:47 -08003107 if (from_ref == nullptr) {
3108 return true;
3109 }
Mathieu Chartier97509952015-07-13 14:35:43 -07003110 mirror::Object* to_ref = IsMarked(from_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003111 if (to_ref == nullptr) {
3112 return false;
3113 }
3114 if (from_ref != to_ref) {
Hiroshi Yamauchi65f5f242016-12-19 11:44:47 -08003115 if (do_atomic_update) {
3116 do {
3117 if (field->AsMirrorPtr() != from_ref) {
3118 // Concurrently overwritten by a mutator.
3119 break;
3120 }
3121 } while (!field->CasWeakRelaxed(from_ref, to_ref));
3122 } else {
Hans Boehmcc55e1d2017-07-27 15:28:07 -07003123 // TODO: Why is this seq_cst when the above is relaxed? Document memory ordering.
3124 field->Assign</* kIsVolatile */ true>(to_ref);
Hiroshi Yamauchi65f5f242016-12-19 11:44:47 -08003125 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003126 }
3127 return true;
3128}
3129
Mathieu Chartier97509952015-07-13 14:35:43 -07003130mirror::Object* ConcurrentCopying::MarkObject(mirror::Object* from_ref) {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08003131 return Mark(Thread::Current(), from_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003132}
3133
Mathieu Chartier31e88222016-10-14 18:43:19 -07003134void ConcurrentCopying::DelayReferenceReferent(ObjPtr<mirror::Class> klass,
3135 ObjPtr<mirror::Reference> reference) {
Mathieu Chartier97509952015-07-13 14:35:43 -07003136 heap_->GetReferenceProcessor()->DelayReferenceReferent(klass, reference, this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003137}
3138
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07003139void ConcurrentCopying::ProcessReferences(Thread* self) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003140 TimingLogger::ScopedTiming split("ProcessReferences", GetTimings());
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07003141 // 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 -08003142 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
3143 GetHeap()->GetReferenceProcessor()->ProcessReferences(
Mathieu Chartier97509952015-07-13 14:35:43 -07003144 true /*concurrent*/, GetTimings(), GetCurrentIteration()->GetClearSoftReferences(), this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003145}
3146
3147void ConcurrentCopying::RevokeAllThreadLocalBuffers() {
3148 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
3149 region_space_->RevokeAllThreadLocalBuffers();
3150}
3151
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08003152mirror::Object* ConcurrentCopying::MarkFromReadBarrierWithMeasurements(Thread* const self,
3153 mirror::Object* from_ref) {
3154 if (self != thread_running_gc_) {
Orion Hodson88591fe2018-03-06 13:35:43 +00003155 rb_slow_path_count_.fetch_add(1u, std::memory_order_relaxed);
Mathieu Chartier56fe2582016-07-14 13:30:03 -07003156 } else {
Orion Hodson88591fe2018-03-06 13:35:43 +00003157 rb_slow_path_count_gc_.fetch_add(1u, std::memory_order_relaxed);
Mathieu Chartier56fe2582016-07-14 13:30:03 -07003158 }
3159 ScopedTrace tr(__FUNCTION__);
3160 const uint64_t start_time = measure_read_barrier_slow_path_ ? NanoTime() : 0u;
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07003161 mirror::Object* ret =
3162 Mark</*kGrayImmuneObject*/true, /*kNoUnEvac*/false, /*kFromGCThread*/false>(self, from_ref);
Mathieu Chartier56fe2582016-07-14 13:30:03 -07003163 if (measure_read_barrier_slow_path_) {
Orion Hodson88591fe2018-03-06 13:35:43 +00003164 rb_slow_path_ns_.fetch_add(NanoTime() - start_time, std::memory_order_relaxed);
Mathieu Chartier56fe2582016-07-14 13:30:03 -07003165 }
3166 return ret;
3167}
3168
3169void ConcurrentCopying::DumpPerformanceInfo(std::ostream& os) {
3170 GarbageCollector::DumpPerformanceInfo(os);
3171 MutexLock mu(Thread::Current(), rb_slow_path_histogram_lock_);
3172 if (rb_slow_path_time_histogram_.SampleSize() > 0) {
3173 Histogram<uint64_t>::CumulativeData cumulative_data;
3174 rb_slow_path_time_histogram_.CreateHistogram(&cumulative_data);
3175 rb_slow_path_time_histogram_.PrintConfidenceIntervals(os, 0.99, cumulative_data);
3176 }
3177 if (rb_slow_path_count_total_ > 0) {
3178 os << "Slow path count " << rb_slow_path_count_total_ << "\n";
3179 }
3180 if (rb_slow_path_count_gc_total_ > 0) {
3181 os << "GC slow path count " << rb_slow_path_count_gc_total_ << "\n";
3182 }
Orion Hodson88591fe2018-03-06 13:35:43 +00003183 os << "Cumulative bytes moved "
3184 << cumulative_bytes_moved_.load(std::memory_order_relaxed) << "\n";
3185 os << "Cumulative objects moved "
3186 << cumulative_objects_moved_.load(std::memory_order_relaxed) << "\n";
Lokesh Gidra29895822017-12-15 15:37:40 -08003187
3188 os << "Peak regions allocated "
Lokesh Gidrab4f15412018-01-05 18:29:34 -08003189 << region_space_->GetMaxPeakNumNonFreeRegions() << " ("
3190 << PrettySize(region_space_->GetMaxPeakNumNonFreeRegions() * space::RegionSpace::kRegionSize)
3191 << ") / " << region_space_->GetNumRegions() / 2 << " ("
3192 << PrettySize(region_space_->GetNumRegions() * space::RegionSpace::kRegionSize / 2)
Lokesh Gidra29895822017-12-15 15:37:40 -08003193 << ")\n";
Mathieu Chartier56fe2582016-07-14 13:30:03 -07003194}
3195
Hiroshi Yamauchid5307ec2014-03-27 21:07:51 -07003196} // namespace collector
3197} // namespace gc
3198} // namespace art