blob: f6e74dab286197924dc7e087dfaab5c1e0e9829f [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"
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070023#include "base/stl_util.h"
Mathieu Chartier56fe2582016-07-14 13:30:03 -070024#include "base/systrace.h"
Mathieu Chartiera6b1ead2015-10-06 10:32:38 -070025#include "debugger.h"
Andreas Gampe291ce172017-04-24 13:22:18 -070026#include "gc/accounting/atomic_stack.h"
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080027#include "gc/accounting/heap_bitmap-inl.h"
Mathieu Chartier21328a12016-07-22 10:47:45 -070028#include "gc/accounting/mod_union_table-inl.h"
Andreas Gampe291ce172017-04-24 13:22:18 -070029#include "gc/accounting/read_barrier_table.h"
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080030#include "gc/accounting/space_bitmap-inl.h"
Andreas Gampe4934eb12017-01-30 13:15:26 -080031#include "gc/gc_pause_listener.h"
Mathieu Chartier3cf22532015-07-09 15:15:09 -070032#include "gc/reference_processor.h"
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080033#include "gc/space/image_space.h"
Mathieu Chartier073b16c2015-11-10 14:13:23 -080034#include "gc/space/space-inl.h"
Mathieu Chartier1ca68902017-04-18 11:26:22 -070035#include "gc/verification.h"
Mathieu Chartier4a26f172016-01-26 14:26:18 -080036#include "image-inl.h"
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080037#include "intern_table.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070038#include "mirror/class-inl.h"
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080039#include "mirror/object-inl.h"
Andreas Gampec6ea7d02017-02-01 16:46:28 -080040#include "mirror/object-refvisitor-inl.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070041#include "scoped_thread_state_change-inl.h"
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080042#include "thread-inl.h"
43#include "thread_list.h"
44#include "well_known_classes.h"
45
Hiroshi Yamauchid5307ec2014-03-27 21:07:51 -070046namespace art {
47namespace gc {
48namespace collector {
49
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -070050static constexpr size_t kDefaultGcMarkStackSize = 2 * MB;
Mathieu Chartier21328a12016-07-22 10:47:45 -070051// If kFilterModUnionCards then we attempt to filter cards that don't need to be dirty in the mod
52// union table. Disabled since it does not seem to help the pause much.
53static constexpr bool kFilterModUnionCards = kIsDebugBuild;
Mathieu Chartierd6636d32016-07-28 11:02:38 -070054// If kDisallowReadBarrierDuringScan is true then the GC aborts if there are any that occur during
55// ConcurrentCopying::Scan. May be used to diagnose possibly unnecessary read barriers.
56// Only enabled for kIsDebugBuild to avoid performance hit.
57static constexpr bool kDisallowReadBarrierDuringScan = kIsDebugBuild;
Mathieu Chartier36a270a2016-07-28 18:08:51 -070058// Slow path mark stack size, increase this if the stack is getting full and it is causing
59// performance problems.
60static constexpr size_t kReadBarrierMarkStackSize = 512 * KB;
Mathieu Chartiera1467d02017-02-22 09:22:50 -080061// Verify that there are no missing card marks.
62static constexpr bool kVerifyNoMissingCardMarks = kIsDebugBuild;
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -070063
Mathieu Chartier56fe2582016-07-14 13:30:03 -070064ConcurrentCopying::ConcurrentCopying(Heap* heap,
65 const std::string& name_prefix,
66 bool measure_read_barrier_slow_path)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080067 : GarbageCollector(heap,
68 name_prefix + (name_prefix.empty() ? "" : " ") +
Hiroshi Yamauchi88e08162017-01-06 15:03:26 -080069 "concurrent copying"),
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070070 region_space_(nullptr), gc_barrier_(new Barrier(0)),
71 gc_mark_stack_(accounting::ObjectStack::Create("concurrent copying gc mark stack",
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -070072 kDefaultGcMarkStackSize,
73 kDefaultGcMarkStackSize)),
Mathieu Chartier36a270a2016-07-28 18:08:51 -070074 rb_mark_bit_stack_(accounting::ObjectStack::Create("rb copying gc mark stack",
75 kReadBarrierMarkStackSize,
76 kReadBarrierMarkStackSize)),
77 rb_mark_bit_stack_full_(false),
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070078 mark_stack_lock_("concurrent copying mark stack lock", kMarkSweepMarkStackLock),
79 thread_running_gc_(nullptr),
Andreas Gamped9911ee2017-03-27 13:27:24 -070080 is_marking_(false),
Mathieu Chartier3768ade2017-05-02 14:04:39 -070081 is_using_read_barrier_entrypoints_(false),
Andreas Gamped9911ee2017-03-27 13:27:24 -070082 is_active_(false),
83 is_asserting_to_space_invariant_(false),
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -070084 region_space_bitmap_(nullptr),
Andreas Gamped9911ee2017-03-27 13:27:24 -070085 heap_mark_bitmap_(nullptr),
86 live_stack_freeze_size_(0),
87 from_space_num_objects_at_first_pause_(0),
88 from_space_num_bytes_at_first_pause_(0),
89 mark_stack_mode_(kMarkStackModeOff),
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070090 weak_ref_access_enabled_(true),
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080091 skipped_blocks_lock_("concurrent copying bytes blocks lock", kMarkSweepMarkStackLock),
Mathieu Chartier56fe2582016-07-14 13:30:03 -070092 measure_read_barrier_slow_path_(measure_read_barrier_slow_path),
Andreas Gamped9911ee2017-03-27 13:27:24 -070093 mark_from_read_barrier_measurements_(false),
Mathieu Chartier56fe2582016-07-14 13:30:03 -070094 rb_slow_path_ns_(0),
95 rb_slow_path_count_(0),
96 rb_slow_path_count_gc_(0),
97 rb_slow_path_histogram_lock_("Read barrier histogram lock"),
98 rb_slow_path_time_histogram_("Mutator time in read barrier slow path", 500, 32),
99 rb_slow_path_count_total_(0),
100 rb_slow_path_count_gc_total_(0),
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800101 rb_table_(heap_->GetReadBarrierTable()),
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700102 force_evacuate_all_(false),
Andreas Gamped9911ee2017-03-27 13:27:24 -0700103 gc_grays_immune_objects_(false),
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700104 immune_gray_stack_lock_("concurrent copying immune gray stack lock",
105 kMarkSweepMarkStackLock) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800106 static_assert(space::RegionSpace::kRegionSize == accounting::ReadBarrierTable::kRegionSize,
107 "The region space size and the read barrier table region size must match");
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700108 Thread* self = Thread::Current();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800109 {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800110 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
111 // Cache this so that we won't have to lock heap_bitmap_lock_ in
112 // Mark() which could cause a nested lock on heap_bitmap_lock_
113 // when GC causes a RB while doing GC or a lock order violation
114 // (class_linker_lock_ and heap_bitmap_lock_).
115 heap_mark_bitmap_ = heap->GetMarkBitmap();
116 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700117 {
118 MutexLock mu(self, mark_stack_lock_);
119 for (size_t i = 0; i < kMarkStackPoolSize; ++i) {
120 accounting::AtomicStack<mirror::Object>* mark_stack =
121 accounting::AtomicStack<mirror::Object>::Create(
122 "thread local mark stack", kMarkStackSize, kMarkStackSize);
123 pooled_mark_stacks_.push_back(mark_stack);
124 }
125 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800126}
127
Hiroshi Yamauchi057d9772017-02-17 15:33:23 -0800128void ConcurrentCopying::MarkHeapReference(mirror::HeapReference<mirror::Object>* field,
129 bool do_atomic_update) {
130 if (UNLIKELY(do_atomic_update)) {
131 // Used to mark the referent in DelayReferenceReferent in transaction mode.
132 mirror::Object* from_ref = field->AsMirrorPtr();
133 if (from_ref == nullptr) {
134 return;
135 }
136 mirror::Object* to_ref = Mark(from_ref);
137 if (from_ref != to_ref) {
138 do {
139 if (field->AsMirrorPtr() != from_ref) {
140 // Concurrently overwritten by a mutator.
141 break;
142 }
143 } while (!field->CasWeakRelaxed(from_ref, to_ref));
144 }
145 } else {
146 // Used for preserving soft references, should be OK to not have a CAS here since there should be
147 // no other threads which can trigger read barriers on the same referent during reference
148 // processing.
149 field->Assign(Mark(field->AsMirrorPtr()));
150 }
Mathieu Chartier97509952015-07-13 14:35:43 -0700151}
152
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800153ConcurrentCopying::~ConcurrentCopying() {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700154 STLDeleteElements(&pooled_mark_stacks_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800155}
156
157void ConcurrentCopying::RunPhases() {
158 CHECK(kUseBakerReadBarrier || kUseTableLookupReadBarrier);
159 CHECK(!is_active_);
160 is_active_ = true;
161 Thread* self = Thread::Current();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700162 thread_running_gc_ = self;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800163 Locks::mutator_lock_->AssertNotHeld(self);
164 {
165 ReaderMutexLock mu(self, *Locks::mutator_lock_);
166 InitializePhase();
167 }
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700168 if (kUseBakerReadBarrier && kGrayDirtyImmuneObjects) {
169 // Switch to read barrier mark entrypoints before we gray the objects. This is required in case
Roland Levillain97c46462017-05-11 14:04:03 +0100170 // a mutator sees a gray bit and dispatches on the entrypoint. (b/37876887).
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700171 ActivateReadBarrierEntrypoints();
172 // Gray dirty immune objects concurrently to reduce GC pause times. We re-process gray cards in
173 // the pause.
174 ReaderMutexLock mu(self, *Locks::mutator_lock_);
175 GrayAllDirtyImmuneObjects();
176 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800177 FlipThreadRoots();
178 {
179 ReaderMutexLock mu(self, *Locks::mutator_lock_);
180 MarkingPhase();
181 }
182 // Verify no from space refs. This causes a pause.
Andreas Gampee3ce7872017-02-22 13:36:21 -0800183 if (kEnableNoFromSpaceRefsVerification) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800184 TimingLogger::ScopedTiming split("(Paused)VerifyNoFromSpaceReferences", GetTimings());
Andreas Gampe4934eb12017-01-30 13:15:26 -0800185 ScopedPause pause(this, false);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700186 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800187 if (kVerboseMode) {
188 LOG(INFO) << "Verifying no from-space refs";
189 }
190 VerifyNoFromSpaceReferences();
Mathieu Chartier720e71a2015-04-06 17:10:58 -0700191 if (kVerboseMode) {
192 LOG(INFO) << "Done verifying no from-space refs";
193 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700194 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800195 }
196 {
197 ReaderMutexLock mu(self, *Locks::mutator_lock_);
198 ReclaimPhase();
199 }
200 FinishPhase();
201 CHECK(is_active_);
202 is_active_ = false;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700203 thread_running_gc_ = nullptr;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800204}
205
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700206class ConcurrentCopying::ActivateReadBarrierEntrypointsCheckpoint : public Closure {
207 public:
208 explicit ActivateReadBarrierEntrypointsCheckpoint(ConcurrentCopying* concurrent_copying)
209 : concurrent_copying_(concurrent_copying) {}
210
211 void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
212 // Note: self is not necessarily equal to thread since thread may be suspended.
213 Thread* self = Thread::Current();
214 DCHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
215 << thread->GetState() << " thread " << thread << " self " << self;
216 // Switch to the read barrier entrypoints.
217 thread->SetReadBarrierEntrypoints();
218 // If thread is a running mutator, then act on behalf of the garbage collector.
219 // See the code in ThreadList::RunCheckpoint.
220 concurrent_copying_->GetBarrier().Pass(self);
221 }
222
223 private:
224 ConcurrentCopying* const concurrent_copying_;
225};
226
227class ConcurrentCopying::ActivateReadBarrierEntrypointsCallback : public Closure {
228 public:
229 explicit ActivateReadBarrierEntrypointsCallback(ConcurrentCopying* concurrent_copying)
230 : concurrent_copying_(concurrent_copying) {}
231
232 void Run(Thread* self ATTRIBUTE_UNUSED) OVERRIDE REQUIRES(Locks::thread_list_lock_) {
233 // This needs to run under the thread_list_lock_ critical section in ThreadList::RunCheckpoint()
234 // to avoid a race with ThreadList::Register().
235 CHECK(!concurrent_copying_->is_using_read_barrier_entrypoints_);
236 concurrent_copying_->is_using_read_barrier_entrypoints_ = true;
237 }
238
239 private:
240 ConcurrentCopying* const concurrent_copying_;
241};
242
243void ConcurrentCopying::ActivateReadBarrierEntrypoints() {
244 Thread* const self = Thread::Current();
245 ActivateReadBarrierEntrypointsCheckpoint checkpoint(this);
246 ThreadList* thread_list = Runtime::Current()->GetThreadList();
247 gc_barrier_->Init(self, 0);
248 ActivateReadBarrierEntrypointsCallback callback(this);
249 const size_t barrier_count = thread_list->RunCheckpoint(&checkpoint, &callback);
250 // If there are no threads to wait which implies that all the checkpoint functions are finished,
251 // then no need to release the mutator lock.
252 if (barrier_count == 0) {
253 return;
254 }
255 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
256 gc_barrier_->Increment(self, barrier_count);
257}
258
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800259void ConcurrentCopying::BindBitmaps() {
260 Thread* self = Thread::Current();
261 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
262 // Mark all of the spaces we never collect as immune.
263 for (const auto& space : heap_->GetContinuousSpaces()) {
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800264 if (space->GetGcRetentionPolicy() == space::kGcRetentionPolicyNeverCollect ||
265 space->GetGcRetentionPolicy() == space::kGcRetentionPolicyFullCollect) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800266 CHECK(space->IsZygoteSpace() || space->IsImageSpace());
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800267 immune_spaces_.AddSpace(space);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800268 } else if (space == region_space_) {
Mathieu Chartier7ec38dc2016-10-07 15:24:46 -0700269 // It is OK to clear the bitmap with mutators running since the only place it is read is
270 // VisitObjects which has exclusion with CC.
271 region_space_bitmap_ = region_space_->GetMarkBitmap();
272 region_space_bitmap_->Clear();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800273 }
274 }
275}
276
277void ConcurrentCopying::InitializePhase() {
278 TimingLogger::ScopedTiming split("InitializePhase", GetTimings());
279 if (kVerboseMode) {
280 LOG(INFO) << "GC InitializePhase";
281 LOG(INFO) << "Region-space : " << reinterpret_cast<void*>(region_space_->Begin()) << "-"
282 << reinterpret_cast<void*>(region_space_->Limit());
283 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700284 CheckEmptyMarkStack();
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800285 if (kIsDebugBuild) {
286 MutexLock mu(Thread::Current(), mark_stack_lock_);
287 CHECK(false_gray_stack_.empty());
288 }
Mathieu Chartier56fe2582016-07-14 13:30:03 -0700289
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700290 rb_mark_bit_stack_full_ = false;
Mathieu Chartier56fe2582016-07-14 13:30:03 -0700291 mark_from_read_barrier_measurements_ = measure_read_barrier_slow_path_;
292 if (measure_read_barrier_slow_path_) {
293 rb_slow_path_ns_.StoreRelaxed(0);
294 rb_slow_path_count_.StoreRelaxed(0);
295 rb_slow_path_count_gc_.StoreRelaxed(0);
296 }
297
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800298 immune_spaces_.Reset();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800299 bytes_moved_.StoreRelaxed(0);
300 objects_moved_.StoreRelaxed(0);
Hiroshi Yamauchi60985b72016-08-24 13:53:12 -0700301 GcCause gc_cause = GetCurrentIteration()->GetGcCause();
302 if (gc_cause == kGcCauseExplicit ||
Hiroshi Yamauchi60985b72016-08-24 13:53:12 -0700303 gc_cause == kGcCauseCollectorTransition ||
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800304 GetCurrentIteration()->GetClearSoftReferences()) {
305 force_evacuate_all_ = true;
306 } else {
307 force_evacuate_all_ = false;
308 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700309 if (kUseBakerReadBarrier) {
310 updated_all_immune_objects_.StoreRelaxed(false);
311 // GC may gray immune objects in the thread flip.
312 gc_grays_immune_objects_ = true;
313 if (kIsDebugBuild) {
314 MutexLock mu(Thread::Current(), immune_gray_stack_lock_);
315 DCHECK(immune_gray_stack_.empty());
316 }
317 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800318 BindBitmaps();
319 if (kVerboseMode) {
320 LOG(INFO) << "force_evacuate_all=" << force_evacuate_all_;
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800321 LOG(INFO) << "Largest immune region: " << immune_spaces_.GetLargestImmuneRegion().Begin()
322 << "-" << immune_spaces_.GetLargestImmuneRegion().End();
323 for (space::ContinuousSpace* space : immune_spaces_.GetSpaces()) {
324 LOG(INFO) << "Immune space: " << *space;
325 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800326 LOG(INFO) << "GC end of InitializePhase";
327 }
Mathieu Chartier962cd7a2016-08-16 12:15:59 -0700328 // Mark all of the zygote large objects without graying them.
329 MarkZygoteLargeObjects();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800330}
331
332// Used to switch the thread roots of a thread from from-space refs to to-space refs.
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700333class ConcurrentCopying::ThreadFlipVisitor : public Closure, public RootVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800334 public:
Roland Levillain3887c462015-08-12 18:15:42 +0100335 ThreadFlipVisitor(ConcurrentCopying* concurrent_copying, bool use_tlab)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800336 : concurrent_copying_(concurrent_copying), use_tlab_(use_tlab) {
337 }
338
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700339 virtual void Run(Thread* thread) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800340 // Note: self is not necessarily equal to thread since thread may be suspended.
341 Thread* self = Thread::Current();
342 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
343 << thread->GetState() << " thread " << thread << " self " << self;
Mathieu Chartierfe814e82016-11-09 14:32:49 -0800344 thread->SetIsGcMarkingAndUpdateEntrypoints(true);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800345 if (use_tlab_ && thread->HasTlab()) {
346 if (ConcurrentCopying::kEnableFromSpaceAccountingCheck) {
347 // This must come before the revoke.
348 size_t thread_local_objects = thread->GetThreadLocalObjectsAllocated();
349 concurrent_copying_->region_space_->RevokeThreadLocalBuffers(thread);
350 reinterpret_cast<Atomic<size_t>*>(&concurrent_copying_->from_space_num_objects_at_first_pause_)->
351 FetchAndAddSequentiallyConsistent(thread_local_objects);
352 } else {
353 concurrent_copying_->region_space_->RevokeThreadLocalBuffers(thread);
354 }
355 }
356 if (kUseThreadLocalAllocationStack) {
357 thread->RevokeThreadLocalAllocationStack();
358 }
359 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700360 // We can use the non-CAS VisitRoots functions below because we update thread-local GC roots
361 // only.
Andreas Gampe513061a2017-06-01 09:17:34 -0700362 thread->VisitRoots(this, kVisitRootFlagAllRoots);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800363 concurrent_copying_->GetBarrier().Pass(self);
364 }
365
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700366 void VisitRoots(mirror::Object*** roots,
367 size_t count,
368 const RootInfo& info ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700369 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700370 for (size_t i = 0; i < count; ++i) {
371 mirror::Object** root = roots[i];
372 mirror::Object* ref = *root;
373 if (ref != nullptr) {
374 mirror::Object* to_ref = concurrent_copying_->Mark(ref);
375 if (to_ref != ref) {
376 *root = to_ref;
377 }
378 }
379 }
380 }
381
382 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots,
383 size_t count,
384 const RootInfo& info ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700385 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700386 for (size_t i = 0; i < count; ++i) {
387 mirror::CompressedReference<mirror::Object>* const root = roots[i];
388 if (!root->IsNull()) {
389 mirror::Object* ref = root->AsMirrorPtr();
390 mirror::Object* to_ref = concurrent_copying_->Mark(ref);
391 if (to_ref != ref) {
392 root->Assign(to_ref);
393 }
394 }
395 }
396 }
397
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800398 private:
399 ConcurrentCopying* const concurrent_copying_;
400 const bool use_tlab_;
401};
402
403// Called back from Runtime::FlipThreadRoots() during a pause.
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700404class ConcurrentCopying::FlipCallback : public Closure {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800405 public:
406 explicit FlipCallback(ConcurrentCopying* concurrent_copying)
407 : concurrent_copying_(concurrent_copying) {
408 }
409
Mathieu Chartier90443472015-07-16 20:32:27 -0700410 virtual void Run(Thread* thread) OVERRIDE REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800411 ConcurrentCopying* cc = concurrent_copying_;
412 TimingLogger::ScopedTiming split("(Paused)FlipCallback", cc->GetTimings());
413 // Note: self is not necessarily equal to thread since thread may be suspended.
414 Thread* self = Thread::Current();
Mathieu Chartiera1467d02017-02-22 09:22:50 -0800415 if (kVerifyNoMissingCardMarks) {
416 cc->VerifyNoMissingCardMarks();
417 }
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700418 CHECK_EQ(thread, self);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800419 Locks::mutator_lock_->AssertExclusiveHeld(self);
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700420 {
421 TimingLogger::ScopedTiming split2("(Paused)SetFromSpace", cc->GetTimings());
422 cc->region_space_->SetFromSpace(cc->rb_table_, cc->force_evacuate_all_);
423 }
Mathieu Chartiera4f6af92015-08-11 17:35:25 -0700424 cc->SwapStacks();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800425 if (ConcurrentCopying::kEnableFromSpaceAccountingCheck) {
426 cc->RecordLiveStackFreezeSize(self);
427 cc->from_space_num_objects_at_first_pause_ = cc->region_space_->GetObjectsAllocated();
428 cc->from_space_num_bytes_at_first_pause_ = cc->region_space_->GetBytesAllocated();
429 }
430 cc->is_marking_ = true;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700431 cc->mark_stack_mode_.StoreRelaxed(ConcurrentCopying::kMarkStackModeThreadLocal);
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800432 if (kIsDebugBuild) {
433 cc->region_space_->AssertAllRegionLiveBytesZeroOrCleared();
434 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800435 if (UNLIKELY(Runtime::Current()->IsActiveTransaction())) {
Mathieu Chartier184c9dc2015-03-05 13:20:54 -0800436 CHECK(Runtime::Current()->IsAotCompiler());
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700437 TimingLogger::ScopedTiming split3("(Paused)VisitTransactionRoots", cc->GetTimings());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700438 Runtime::Current()->VisitTransactionRoots(cc);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800439 }
Mathieu Chartier21328a12016-07-22 10:47:45 -0700440 if (kUseBakerReadBarrier && kGrayDirtyImmuneObjects) {
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700441 cc->GrayAllNewlyDirtyImmuneObjects();
Mathieu Chartier21328a12016-07-22 10:47:45 -0700442 if (kIsDebugBuild) {
Roland Levillain001eff92018-01-24 14:24:33 +0000443 // Check that all non-gray immune objects only reference immune objects.
Mathieu Chartier21328a12016-07-22 10:47:45 -0700444 cc->VerifyGrayImmuneObjects();
445 }
446 }
Mathieu Chartier9aef9922017-04-23 13:53:50 -0700447 // May be null during runtime creation, in this case leave java_lang_Object null.
448 // This is safe since single threaded behavior should mean FillDummyObject does not
449 // happen when java_lang_Object_ is null.
450 if (WellKnownClasses::java_lang_Object != nullptr) {
451 cc->java_lang_Object_ = down_cast<mirror::Class*>(cc->Mark(
452 WellKnownClasses::ToClass(WellKnownClasses::java_lang_Object).Ptr()));
453 } else {
454 cc->java_lang_Object_ = nullptr;
455 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800456 }
457
458 private:
459 ConcurrentCopying* const concurrent_copying_;
460};
461
Mathieu Chartier21328a12016-07-22 10:47:45 -0700462class ConcurrentCopying::VerifyGrayImmuneObjectsVisitor {
463 public:
464 explicit VerifyGrayImmuneObjectsVisitor(ConcurrentCopying* collector)
465 : collector_(collector) {}
466
Mathieu Chartier31e88222016-10-14 18:43:19 -0700467 void operator()(ObjPtr<mirror::Object> obj, MemberOffset offset, bool /* is_static */)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700468 const ALWAYS_INLINE REQUIRES_SHARED(Locks::mutator_lock_)
469 REQUIRES_SHARED(Locks::heap_bitmap_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700470 CheckReference(obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(offset),
471 obj, offset);
472 }
473
Mathieu Chartier31e88222016-10-14 18:43:19 -0700474 void operator()(ObjPtr<mirror::Class> klass, ObjPtr<mirror::Reference> ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700475 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700476 CHECK(klass->IsTypeOfReferenceClass());
477 CheckReference(ref->GetReferent<kWithoutReadBarrier>(),
478 ref,
479 mirror::Reference::ReferentOffset());
480 }
481
482 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
483 ALWAYS_INLINE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700484 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700485 if (!root->IsNull()) {
486 VisitRoot(root);
487 }
488 }
489
490 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
491 ALWAYS_INLINE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700492 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700493 CheckReference(root->AsMirrorPtr(), nullptr, MemberOffset(0));
494 }
495
496 private:
497 ConcurrentCopying* const collector_;
498
Mathieu Chartier31e88222016-10-14 18:43:19 -0700499 void CheckReference(ObjPtr<mirror::Object> ref,
500 ObjPtr<mirror::Object> holder,
501 MemberOffset offset) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700502 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700503 if (ref != nullptr) {
Mathieu Chartier31e88222016-10-14 18:43:19 -0700504 if (!collector_->immune_spaces_.ContainsObject(ref.Ptr())) {
Mathieu Chartier962cd7a2016-08-16 12:15:59 -0700505 // Not immune, must be a zygote large object.
506 CHECK(Runtime::Current()->GetHeap()->GetLargeObjectsSpace()->IsZygoteLargeObject(
Mathieu Chartier31e88222016-10-14 18:43:19 -0700507 Thread::Current(), ref.Ptr()))
Mathieu Chartier962cd7a2016-08-16 12:15:59 -0700508 << "Non gray object references non immune, non zygote large object "<< ref << " "
David Sehr709b0702016-10-13 09:12:37 -0700509 << mirror::Object::PrettyTypeOf(ref) << " in holder " << holder << " "
510 << mirror::Object::PrettyTypeOf(holder) << " offset=" << offset.Uint32Value();
Mathieu Chartier962cd7a2016-08-16 12:15:59 -0700511 } else {
512 // Make sure the large object class is immune since we will never scan the large object.
513 CHECK(collector_->immune_spaces_.ContainsObject(
514 ref->GetClass<kVerifyNone, kWithoutReadBarrier>()));
515 }
Mathieu Chartier21328a12016-07-22 10:47:45 -0700516 }
517 }
518};
519
520void ConcurrentCopying::VerifyGrayImmuneObjects() {
521 TimingLogger::ScopedTiming split(__FUNCTION__, GetTimings());
522 for (auto& space : immune_spaces_.GetSpaces()) {
523 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
524 accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
525 VerifyGrayImmuneObjectsVisitor visitor(this);
526 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()),
527 reinterpret_cast<uintptr_t>(space->Limit()),
528 [&visitor](mirror::Object* obj)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700529 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700530 // If an object is not gray, it should only have references to things in the immune spaces.
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700531 if (obj->GetReadBarrierState() != ReadBarrier::GrayState()) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700532 obj->VisitReferences</*kVisitNativeRoots*/true,
533 kDefaultVerifyFlags,
534 kWithoutReadBarrier>(visitor, visitor);
535 }
536 });
537 }
538}
539
Mathieu Chartiera1467d02017-02-22 09:22:50 -0800540class ConcurrentCopying::VerifyNoMissingCardMarkVisitor {
541 public:
542 VerifyNoMissingCardMarkVisitor(ConcurrentCopying* cc, ObjPtr<mirror::Object> holder)
543 : cc_(cc),
544 holder_(holder) {}
545
546 void operator()(ObjPtr<mirror::Object> obj,
547 MemberOffset offset,
548 bool is_static ATTRIBUTE_UNUSED) const
549 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
550 if (offset.Uint32Value() != mirror::Object::ClassOffset().Uint32Value()) {
551 CheckReference(obj->GetFieldObject<mirror::Object, kDefaultVerifyFlags, kWithoutReadBarrier>(
552 offset), offset.Uint32Value());
553 }
554 }
555 void operator()(ObjPtr<mirror::Class> klass,
556 ObjPtr<mirror::Reference> ref) const
557 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
558 CHECK(klass->IsTypeOfReferenceClass());
559 this->operator()(ref, mirror::Reference::ReferentOffset(), false);
560 }
561
562 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
563 REQUIRES_SHARED(Locks::mutator_lock_) {
564 if (!root->IsNull()) {
565 VisitRoot(root);
566 }
567 }
568
569 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
570 REQUIRES_SHARED(Locks::mutator_lock_) {
571 CheckReference(root->AsMirrorPtr());
572 }
573
574 void CheckReference(mirror::Object* ref, int32_t offset = -1) const
575 REQUIRES_SHARED(Locks::mutator_lock_) {
576 CHECK(ref == nullptr || !cc_->region_space_->IsInNewlyAllocatedRegion(ref))
577 << holder_->PrettyTypeOf() << "(" << holder_.Ptr() << ") references object "
578 << ref->PrettyTypeOf() << "(" << ref << ") in newly allocated region at offset=" << offset;
579 }
580
581 private:
582 ConcurrentCopying* const cc_;
583 ObjPtr<mirror::Object> const holder_;
584};
585
Mathieu Chartiera1467d02017-02-22 09:22:50 -0800586void ConcurrentCopying::VerifyNoMissingCardMarks() {
Andreas Gampe0c183382017-07-13 22:26:24 -0700587 auto visitor = [&](mirror::Object* obj)
588 REQUIRES(Locks::mutator_lock_)
589 REQUIRES(!mark_stack_lock_) {
590 // Objects not on dirty or aged cards should never have references to newly allocated regions.
591 if (heap_->GetCardTable()->GetCard(obj) == gc::accounting::CardTable::kCardClean) {
592 VerifyNoMissingCardMarkVisitor internal_visitor(this, /*holder*/ obj);
593 obj->VisitReferences</*kVisitNativeRoots*/true, kVerifyNone, kWithoutReadBarrier>(
594 internal_visitor, internal_visitor);
595 }
596 };
Mathieu Chartiera1467d02017-02-22 09:22:50 -0800597 TimingLogger::ScopedTiming split(__FUNCTION__, GetTimings());
Andreas Gampe0c183382017-07-13 22:26:24 -0700598 region_space_->Walk(visitor);
Mathieu Chartiera1467d02017-02-22 09:22:50 -0800599 {
600 ReaderMutexLock rmu(Thread::Current(), *Locks::heap_bitmap_lock_);
Andreas Gampe0c183382017-07-13 22:26:24 -0700601 heap_->GetLiveBitmap()->Visit(visitor);
Mathieu Chartiera1467d02017-02-22 09:22:50 -0800602 }
603}
604
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800605// Switch threads that from from-space to to-space refs. Forward/mark the thread roots.
606void ConcurrentCopying::FlipThreadRoots() {
607 TimingLogger::ScopedTiming split("FlipThreadRoots", GetTimings());
608 if (kVerboseMode) {
609 LOG(INFO) << "time=" << region_space_->Time();
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700610 region_space_->DumpNonFreeRegions(LOG_STREAM(INFO));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800611 }
612 Thread* self = Thread::Current();
613 Locks::mutator_lock_->AssertNotHeld(self);
614 gc_barrier_->Init(self, 0);
615 ThreadFlipVisitor thread_flip_visitor(this, heap_->use_tlab_);
616 FlipCallback flip_callback(this);
Andreas Gampe4934eb12017-01-30 13:15:26 -0800617
Andreas Gampe6e644452017-05-09 16:30:27 -0700618 size_t barrier_count = Runtime::Current()->GetThreadList()->FlipThreadRoots(
619 &thread_flip_visitor, &flip_callback, this, GetHeap()->GetGcPauseListener());
Andreas Gampe4934eb12017-01-30 13:15:26 -0800620
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800621 {
622 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
623 gc_barrier_->Increment(self, barrier_count);
624 }
625 is_asserting_to_space_invariant_ = true;
626 QuasiAtomic::ThreadFenceForConstructor();
627 if (kVerboseMode) {
628 LOG(INFO) << "time=" << region_space_->Time();
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700629 region_space_->DumpNonFreeRegions(LOG_STREAM(INFO));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800630 LOG(INFO) << "GC end of FlipThreadRoots";
631 }
632}
633
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700634template <bool kConcurrent>
Mathieu Chartier21328a12016-07-22 10:47:45 -0700635class ConcurrentCopying::GrayImmuneObjectVisitor {
636 public:
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700637 explicit GrayImmuneObjectVisitor(Thread* self) : self_(self) {}
Mathieu Chartier21328a12016-07-22 10:47:45 -0700638
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700639 ALWAYS_INLINE void operator()(mirror::Object* obj) const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700640 if (kUseBakerReadBarrier && obj->GetReadBarrierState() == ReadBarrier::WhiteState()) {
641 if (kConcurrent) {
642 Locks::mutator_lock_->AssertSharedHeld(self_);
643 obj->AtomicSetReadBarrierState(ReadBarrier::WhiteState(), ReadBarrier::GrayState());
644 // Mod union table VisitObjects may visit the same object multiple times so we can't check
645 // the result of the atomic set.
646 } else {
647 Locks::mutator_lock_->AssertExclusiveHeld(self_);
648 obj->SetReadBarrierState(ReadBarrier::GrayState());
Mathieu Chartier21328a12016-07-22 10:47:45 -0700649 }
Mathieu Chartier21328a12016-07-22 10:47:45 -0700650 }
651 }
652
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700653 static void Callback(mirror::Object* obj, void* arg) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700654 reinterpret_cast<GrayImmuneObjectVisitor<kConcurrent>*>(arg)->operator()(obj);
Mathieu Chartier21328a12016-07-22 10:47:45 -0700655 }
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700656
657 private:
658 Thread* const self_;
Mathieu Chartier21328a12016-07-22 10:47:45 -0700659};
660
661void ConcurrentCopying::GrayAllDirtyImmuneObjects() {
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700662 TimingLogger::ScopedTiming split("GrayAllDirtyImmuneObjects", GetTimings());
663 accounting::CardTable* const card_table = heap_->GetCardTable();
664 Thread* const self = Thread::Current();
665 using VisitorType = GrayImmuneObjectVisitor</* kIsConcurrent */ true>;
666 VisitorType visitor(self);
667 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier21328a12016-07-22 10:47:45 -0700668 for (space::ContinuousSpace* space : immune_spaces_.GetSpaces()) {
669 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700670 accounting::ModUnionTable* table = heap_->FindModUnionTableFromSpace(space);
Mathieu Chartier21328a12016-07-22 10:47:45 -0700671 // Mark all the objects on dirty cards since these may point to objects in other space.
672 // Once these are marked, the GC will eventually clear them later.
673 // Table is non null for boot image and zygote spaces. It is only null for application image
674 // spaces.
675 if (table != nullptr) {
Mathieu Chartier6e6078a2016-10-24 15:45:41 -0700676 table->ProcessCards();
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700677 table->VisitObjects(&VisitorType::Callback, &visitor);
678 // Don't clear cards here since we need to rescan in the pause. If we cleared the cards here,
679 // there would be races with the mutator marking new cards.
680 } else {
681 // Keep cards aged if we don't have a mod-union table since we may need to scan them in future
682 // GCs. This case is for app images.
683 card_table->ModifyCardsAtomic(
684 space->Begin(),
685 space->End(),
686 [](uint8_t card) {
687 return (card != gc::accounting::CardTable::kCardClean)
688 ? gc::accounting::CardTable::kCardAged
689 : card;
690 },
691 /* card modified visitor */ VoidFunctor());
692 card_table->Scan</* kClearCard */ false>(space->GetMarkBitmap(),
693 space->Begin(),
694 space->End(),
695 visitor,
696 gc::accounting::CardTable::kCardAged);
697 }
698 }
699}
700
701void ConcurrentCopying::GrayAllNewlyDirtyImmuneObjects() {
702 TimingLogger::ScopedTiming split("(Paused)GrayAllNewlyDirtyImmuneObjects", GetTimings());
703 accounting::CardTable* const card_table = heap_->GetCardTable();
704 using VisitorType = GrayImmuneObjectVisitor</* kIsConcurrent */ false>;
705 Thread* const self = Thread::Current();
706 VisitorType visitor(self);
707 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
708 for (space::ContinuousSpace* space : immune_spaces_.GetSpaces()) {
709 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
710 accounting::ModUnionTable* table = heap_->FindModUnionTableFromSpace(space);
711
712 // Don't need to scan aged cards since we did these before the pause. Note that scanning cards
713 // also handles the mod-union table cards.
714 card_table->Scan</* kClearCard */ false>(space->GetMarkBitmap(),
715 space->Begin(),
716 space->End(),
717 visitor,
718 gc::accounting::CardTable::kCardDirty);
719 if (table != nullptr) {
720 // Add the cards to the mod-union table so that we can clear cards to save RAM.
721 table->ProcessCards();
Mathieu Chartier6e6078a2016-10-24 15:45:41 -0700722 TimingLogger::ScopedTiming split2("(Paused)ClearCards", GetTimings());
723 card_table->ClearCardRange(space->Begin(),
724 AlignDown(space->End(), accounting::CardTable::kCardSize));
Mathieu Chartier21328a12016-07-22 10:47:45 -0700725 }
726 }
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700727 // 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 -0700728 // barriers in the immune spaces.
729 updated_all_immune_objects_.StoreRelaxed(true);
730}
731
Mathieu Chartiera4f6af92015-08-11 17:35:25 -0700732void ConcurrentCopying::SwapStacks() {
733 heap_->SwapStacks();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800734}
735
736void ConcurrentCopying::RecordLiveStackFreezeSize(Thread* self) {
737 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
738 live_stack_freeze_size_ = heap_->GetLiveStack()->Size();
739}
740
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700741// Used to visit objects in the immune spaces.
742inline void ConcurrentCopying::ScanImmuneObject(mirror::Object* obj) {
743 DCHECK(obj != nullptr);
744 DCHECK(immune_spaces_.ContainsObject(obj));
745 // Update the fields without graying it or pushing it onto the mark stack.
746 Scan(obj);
747}
748
749class ConcurrentCopying::ImmuneSpaceScanObjVisitor {
750 public:
751 explicit ImmuneSpaceScanObjVisitor(ConcurrentCopying* cc)
752 : collector_(cc) {}
753
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700754 ALWAYS_INLINE void operator()(mirror::Object* obj) const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700755 if (kUseBakerReadBarrier && kGrayDirtyImmuneObjects) {
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700756 // Only need to scan gray objects.
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700757 if (obj->GetReadBarrierState() == ReadBarrier::GrayState()) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700758 collector_->ScanImmuneObject(obj);
759 // Done scanning the object, go back to white.
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700760 bool success = obj->AtomicSetReadBarrierState(ReadBarrier::GrayState(),
761 ReadBarrier::WhiteState());
Mathieu Chartier2af7a3e2017-12-14 18:36:05 -0800762 CHECK(success)
763 << Runtime::Current()->GetHeap()->GetVerification()->DumpObjectInfo(obj, "failed CAS");
Mathieu Chartier21328a12016-07-22 10:47:45 -0700764 }
765 } else {
766 collector_->ScanImmuneObject(obj);
767 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700768 }
769
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700770 static void Callback(mirror::Object* obj, void* arg) REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi5408f232016-07-29 15:07:05 -0700771 reinterpret_cast<ImmuneSpaceScanObjVisitor*>(arg)->operator()(obj);
772 }
773
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700774 private:
775 ConcurrentCopying* const collector_;
776};
777
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800778// Concurrently mark roots that are guarded by read barriers and process the mark stack.
779void ConcurrentCopying::MarkingPhase() {
780 TimingLogger::ScopedTiming split("MarkingPhase", GetTimings());
781 if (kVerboseMode) {
782 LOG(INFO) << "GC MarkingPhase";
783 }
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -0700784 Thread* self = Thread::Current();
785 if (kIsDebugBuild) {
786 MutexLock mu(self, *Locks::thread_list_lock_);
787 CHECK(weak_ref_access_enabled_);
788 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700789
790 // Scan immune spaces.
791 // Update all the fields in the immune spaces first without graying the objects so that we
792 // minimize dirty pages in the immune spaces. Note mutators can concurrently access and gray some
793 // of the objects.
794 if (kUseBakerReadBarrier) {
795 gc_grays_immune_objects_ = false;
Hiroshi Yamauchi16292fc2016-06-20 20:23:34 -0700796 }
Mathieu Chartier21328a12016-07-22 10:47:45 -0700797 {
798 TimingLogger::ScopedTiming split2("ScanImmuneSpaces", GetTimings());
799 for (auto& space : immune_spaces_.GetSpaces()) {
800 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
801 accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
Hiroshi Yamauchi5408f232016-07-29 15:07:05 -0700802 accounting::ModUnionTable* table = heap_->FindModUnionTableFromSpace(space);
Mathieu Chartier21328a12016-07-22 10:47:45 -0700803 ImmuneSpaceScanObjVisitor visitor(this);
Hiroshi Yamauchi5408f232016-07-29 15:07:05 -0700804 if (kUseBakerReadBarrier && kGrayDirtyImmuneObjects && table != nullptr) {
805 table->VisitObjects(ImmuneSpaceScanObjVisitor::Callback, &visitor);
806 } else {
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700807 // TODO: Scan only the aged cards.
Hiroshi Yamauchi5408f232016-07-29 15:07:05 -0700808 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()),
809 reinterpret_cast<uintptr_t>(space->Limit()),
810 visitor);
811 }
Mathieu Chartier21328a12016-07-22 10:47:45 -0700812 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700813 }
814 if (kUseBakerReadBarrier) {
815 // This release fence makes the field updates in the above loop visible before allowing mutator
816 // getting access to immune objects without graying it first.
817 updated_all_immune_objects_.StoreRelease(true);
818 // Now whiten immune objects concurrently accessed and grayed by mutators. We can't do this in
819 // the above loop because we would incorrectly disable the read barrier by whitening an object
820 // which may point to an unscanned, white object, breaking the to-space invariant.
821 //
822 // Make sure no mutators are in the middle of marking an immune object before whitening immune
823 // objects.
824 IssueEmptyCheckpoint();
825 MutexLock mu(Thread::Current(), immune_gray_stack_lock_);
826 if (kVerboseMode) {
827 LOG(INFO) << "immune gray stack size=" << immune_gray_stack_.size();
828 }
829 for (mirror::Object* obj : immune_gray_stack_) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700830 DCHECK(obj->GetReadBarrierState() == ReadBarrier::GrayState());
831 bool success = obj->AtomicSetReadBarrierState(ReadBarrier::GrayState(),
832 ReadBarrier::WhiteState());
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700833 DCHECK(success);
834 }
835 immune_gray_stack_.clear();
836 }
837
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800838 {
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -0700839 TimingLogger::ScopedTiming split2("VisitConcurrentRoots", GetTimings());
840 Runtime::Current()->VisitConcurrentRoots(this, kVisitRootFlagAllRoots);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800841 }
842 {
843 // TODO: don't visit the transaction roots if it's not active.
844 TimingLogger::ScopedTiming split5("VisitNonThreadRoots", GetTimings());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700845 Runtime::Current()->VisitNonThreadRoots(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800846 }
847
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800848 {
Mathieu Chartiera6b1ead2015-10-06 10:32:38 -0700849 TimingLogger::ScopedTiming split7("ProcessMarkStack", GetTimings());
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700850 // We transition through three mark stack modes (thread-local, shared, GC-exclusive). The
851 // primary reasons are the fact that we need to use a checkpoint to process thread-local mark
852 // stacks, but after we disable weak refs accesses, we can't use a checkpoint due to a deadlock
853 // issue because running threads potentially blocking at WaitHoldingLocks, and that once we
854 // reach the point where we process weak references, we can avoid using a lock when accessing
855 // the GC mark stack, which makes mark stack processing more efficient.
856
857 // Process the mark stack once in the thread local stack mode. This marks most of the live
858 // objects, aside from weak ref accesses with read barriers (Reference::GetReferent() and system
859 // weaks) that may happen concurrently while we processing the mark stack and newly mark/gray
860 // objects and push refs on the mark stack.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800861 ProcessMarkStack();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700862 // Switch to the shared mark stack mode. That is, revoke and process thread-local mark stacks
863 // for the last time before transitioning to the shared mark stack mode, which would process new
864 // refs that may have been concurrently pushed onto the mark stack during the ProcessMarkStack()
865 // call above. At the same time, disable weak ref accesses using a per-thread flag. It's
866 // important to do these together in a single checkpoint so that we can ensure that mutators
867 // won't newly gray objects and push new refs onto the mark stack due to weak ref accesses and
868 // mutators safely transition to the shared mark stack mode (without leaving unprocessed refs on
869 // the thread-local mark stacks), without a race. This is why we use a thread-local weak ref
870 // access flag Thread::tls32_.weak_ref_access_enabled_ instead of the global ones.
871 SwitchToSharedMarkStackMode();
872 CHECK(!self->GetWeakRefAccessEnabled());
873 // Now that weak refs accesses are disabled, once we exhaust the shared mark stack again here
874 // (which may be non-empty if there were refs found on thread-local mark stacks during the above
875 // SwitchToSharedMarkStackMode() call), we won't have new refs to process, that is, mutators
876 // (via read barriers) have no way to produce any more refs to process. Marking converges once
877 // before we process weak refs below.
878 ProcessMarkStack();
879 CheckEmptyMarkStack();
880 // Switch to the GC exclusive mark stack mode so that we can process the mark stack without a
881 // lock from this point on.
882 SwitchToGcExclusiveMarkStackMode();
883 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800884 if (kVerboseMode) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800885 LOG(INFO) << "ProcessReferences";
886 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700887 // Process weak references. This may produce new refs to process and have them processed via
Mathieu Chartier97509952015-07-13 14:35:43 -0700888 // ProcessMarkStack (in the GC exclusive mark stack mode).
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700889 ProcessReferences(self);
890 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800891 if (kVerboseMode) {
892 LOG(INFO) << "SweepSystemWeaks";
893 }
894 SweepSystemWeaks(self);
895 if (kVerboseMode) {
896 LOG(INFO) << "SweepSystemWeaks done";
897 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700898 // Process the mark stack here one last time because the above SweepSystemWeaks() call may have
899 // marked some objects (strings alive) as hash_set::Erase() can call the hash function for
900 // arbitrary elements in the weak intern table in InternTable::Table::SweepWeaks().
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800901 ProcessMarkStack();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700902 CheckEmptyMarkStack();
903 // Re-enable weak ref accesses.
904 ReenableWeakRefAccess(self);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -0700905 // Free data for class loaders that we unloaded.
906 Runtime::Current()->GetClassLinker()->CleanupClassLoaders();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700907 // Marking is done. Disable marking.
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700908 DisableMarking();
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800909 if (kUseBakerReadBarrier) {
910 ProcessFalseGrayStack();
911 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700912 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800913 }
914
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -0700915 if (kIsDebugBuild) {
916 MutexLock mu(self, *Locks::thread_list_lock_);
917 CHECK(weak_ref_access_enabled_);
918 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800919 if (kVerboseMode) {
920 LOG(INFO) << "GC end of MarkingPhase";
921 }
922}
923
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700924void ConcurrentCopying::ReenableWeakRefAccess(Thread* self) {
925 if (kVerboseMode) {
926 LOG(INFO) << "ReenableWeakRefAccess";
927 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700928 // Iterate all threads (don't need to or can't use a checkpoint) and re-enable weak ref access.
929 {
930 MutexLock mu(self, *Locks::thread_list_lock_);
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -0700931 weak_ref_access_enabled_ = true; // This is for new threads.
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700932 std::list<Thread*> thread_list = Runtime::Current()->GetThreadList()->GetList();
933 for (Thread* thread : thread_list) {
934 thread->SetWeakRefAccessEnabled(true);
935 }
936 }
937 // Unblock blocking threads.
938 GetHeap()->GetReferenceProcessor()->BroadcastForSlowPath(self);
939 Runtime::Current()->BroadcastForNewSystemWeaks();
940}
941
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700942class ConcurrentCopying::DisableMarkingCheckpoint : public Closure {
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700943 public:
944 explicit DisableMarkingCheckpoint(ConcurrentCopying* concurrent_copying)
945 : concurrent_copying_(concurrent_copying) {
946 }
947
948 void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
949 // Note: self is not necessarily equal to thread since thread may be suspended.
950 Thread* self = Thread::Current();
951 DCHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
952 << thread->GetState() << " thread " << thread << " self " << self;
953 // Disable the thread-local is_gc_marking flag.
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -0700954 // Note a thread that has just started right before this checkpoint may have already this flag
955 // set to false, which is ok.
Mathieu Chartierfe814e82016-11-09 14:32:49 -0800956 thread->SetIsGcMarkingAndUpdateEntrypoints(false);
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700957 // If thread is a running mutator, then act on behalf of the garbage collector.
958 // See the code in ThreadList::RunCheckpoint.
Mathieu Chartier10d25082015-10-28 18:36:09 -0700959 concurrent_copying_->GetBarrier().Pass(self);
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700960 }
961
962 private:
963 ConcurrentCopying* const concurrent_copying_;
964};
965
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -0700966class ConcurrentCopying::DisableMarkingCallback : public Closure {
967 public:
968 explicit DisableMarkingCallback(ConcurrentCopying* concurrent_copying)
969 : concurrent_copying_(concurrent_copying) {
970 }
971
972 void Run(Thread* self ATTRIBUTE_UNUSED) OVERRIDE REQUIRES(Locks::thread_list_lock_) {
973 // This needs to run under the thread_list_lock_ critical section in ThreadList::RunCheckpoint()
974 // to avoid a race with ThreadList::Register().
975 CHECK(concurrent_copying_->is_marking_);
976 concurrent_copying_->is_marking_ = false;
Mathieu Chartiera9a4f5f2017-05-03 18:19:13 -0700977 if (kUseBakerReadBarrier && kGrayDirtyImmuneObjects) {
978 CHECK(concurrent_copying_->is_using_read_barrier_entrypoints_);
979 concurrent_copying_->is_using_read_barrier_entrypoints_ = false;
980 } else {
981 CHECK(!concurrent_copying_->is_using_read_barrier_entrypoints_);
982 }
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -0700983 }
984
985 private:
986 ConcurrentCopying* const concurrent_copying_;
987};
988
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700989void ConcurrentCopying::IssueDisableMarkingCheckpoint() {
990 Thread* self = Thread::Current();
991 DisableMarkingCheckpoint check_point(this);
992 ThreadList* thread_list = Runtime::Current()->GetThreadList();
993 gc_barrier_->Init(self, 0);
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -0700994 DisableMarkingCallback dmc(this);
995 size_t barrier_count = thread_list->RunCheckpoint(&check_point, &dmc);
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700996 // If there are no threads to wait which implies that all the checkpoint functions are finished,
997 // then no need to release the mutator lock.
998 if (barrier_count == 0) {
999 return;
1000 }
1001 // Release locks then wait for all mutator threads to pass the barrier.
1002 Locks::mutator_lock_->SharedUnlock(self);
1003 {
1004 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
1005 gc_barrier_->Increment(self, barrier_count);
1006 }
1007 Locks::mutator_lock_->SharedLock(self);
1008}
1009
1010void ConcurrentCopying::DisableMarking() {
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001011 // Use a checkpoint to turn off the global is_marking and the thread-local is_gc_marking flags and
1012 // to ensure no threads are still in the middle of a read barrier which may have a from-space ref
1013 // cached in a local variable.
Hiroshi Yamauchi00370822015-08-18 14:47:25 -07001014 IssueDisableMarkingCheckpoint();
1015 if (kUseTableLookupReadBarrier) {
1016 heap_->rb_table_->ClearAll();
1017 DCHECK(heap_->rb_table_->IsAllCleared());
1018 }
1019 is_mark_stack_push_disallowed_.StoreSequentiallyConsistent(1);
1020 mark_stack_mode_.StoreSequentiallyConsistent(kMarkStackModeOff);
1021}
1022
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001023void ConcurrentCopying::PushOntoFalseGrayStack(mirror::Object* ref) {
1024 CHECK(kUseBakerReadBarrier);
1025 DCHECK(ref != nullptr);
1026 MutexLock mu(Thread::Current(), mark_stack_lock_);
1027 false_gray_stack_.push_back(ref);
1028}
1029
1030void ConcurrentCopying::ProcessFalseGrayStack() {
1031 CHECK(kUseBakerReadBarrier);
1032 // Change the objects on the false gray stack from gray to white.
1033 MutexLock mu(Thread::Current(), mark_stack_lock_);
1034 for (mirror::Object* obj : false_gray_stack_) {
1035 DCHECK(IsMarked(obj));
1036 // The object could be white here if a thread got preempted after a success at the
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001037 // AtomicSetReadBarrierState in Mark(), GC started marking through it (but not finished so
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001038 // still gray), and the thread ran to register it onto the false gray stack.
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001039 if (obj->GetReadBarrierState() == ReadBarrier::GrayState()) {
1040 bool success = obj->AtomicSetReadBarrierState(ReadBarrier::GrayState(),
1041 ReadBarrier::WhiteState());
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001042 DCHECK(success);
1043 }
1044 }
1045 false_gray_stack_.clear();
1046}
1047
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001048void ConcurrentCopying::IssueEmptyCheckpoint() {
1049 Thread* self = Thread::Current();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001050 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001051 // Release locks then wait for all mutator threads to pass the barrier.
1052 Locks::mutator_lock_->SharedUnlock(self);
Hiroshi Yamauchia2224042017-02-08 16:35:45 -08001053 thread_list->RunEmptyCheckpoint();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001054 Locks::mutator_lock_->SharedLock(self);
1055}
1056
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -07001057void ConcurrentCopying::ExpandGcMarkStack() {
1058 DCHECK(gc_mark_stack_->IsFull());
1059 const size_t new_size = gc_mark_stack_->Capacity() * 2;
1060 std::vector<StackReference<mirror::Object>> temp(gc_mark_stack_->Begin(),
1061 gc_mark_stack_->End());
1062 gc_mark_stack_->Resize(new_size);
1063 for (auto& ref : temp) {
1064 gc_mark_stack_->PushBack(ref.AsMirrorPtr());
1065 }
1066 DCHECK(!gc_mark_stack_->IsFull());
1067}
1068
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001069void ConcurrentCopying::PushOntoMarkStack(mirror::Object* to_ref) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001070 CHECK_EQ(is_mark_stack_push_disallowed_.LoadRelaxed(), 0)
David Sehr709b0702016-10-13 09:12:37 -07001071 << " " << to_ref << " " << mirror::Object::PrettyTypeOf(to_ref);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001072 Thread* self = Thread::Current(); // TODO: pass self as an argument from call sites?
1073 CHECK(thread_running_gc_ != nullptr);
1074 MarkStackMode mark_stack_mode = mark_stack_mode_.LoadRelaxed();
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001075 if (LIKELY(mark_stack_mode == kMarkStackModeThreadLocal)) {
1076 if (LIKELY(self == thread_running_gc_)) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001077 // If GC-running thread, use the GC mark stack instead of a thread-local mark stack.
1078 CHECK(self->GetThreadLocalMarkStack() == nullptr);
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -07001079 if (UNLIKELY(gc_mark_stack_->IsFull())) {
1080 ExpandGcMarkStack();
1081 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001082 gc_mark_stack_->PushBack(to_ref);
1083 } else {
1084 // Otherwise, use a thread-local mark stack.
1085 accounting::AtomicStack<mirror::Object>* tl_mark_stack = self->GetThreadLocalMarkStack();
1086 if (UNLIKELY(tl_mark_stack == nullptr || tl_mark_stack->IsFull())) {
1087 MutexLock mu(self, mark_stack_lock_);
1088 // Get a new thread local mark stack.
1089 accounting::AtomicStack<mirror::Object>* new_tl_mark_stack;
1090 if (!pooled_mark_stacks_.empty()) {
1091 // Use a pooled mark stack.
1092 new_tl_mark_stack = pooled_mark_stacks_.back();
1093 pooled_mark_stacks_.pop_back();
1094 } else {
1095 // None pooled. Create a new one.
1096 new_tl_mark_stack =
1097 accounting::AtomicStack<mirror::Object>::Create(
1098 "thread local mark stack", 4 * KB, 4 * KB);
1099 }
1100 DCHECK(new_tl_mark_stack != nullptr);
1101 DCHECK(new_tl_mark_stack->IsEmpty());
1102 new_tl_mark_stack->PushBack(to_ref);
1103 self->SetThreadLocalMarkStack(new_tl_mark_stack);
1104 if (tl_mark_stack != nullptr) {
1105 // Store the old full stack into a vector.
1106 revoked_mark_stacks_.push_back(tl_mark_stack);
1107 }
1108 } else {
1109 tl_mark_stack->PushBack(to_ref);
1110 }
1111 }
1112 } else if (mark_stack_mode == kMarkStackModeShared) {
1113 // Access the shared GC mark stack with a lock.
1114 MutexLock mu(self, mark_stack_lock_);
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -07001115 if (UNLIKELY(gc_mark_stack_->IsFull())) {
1116 ExpandGcMarkStack();
1117 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001118 gc_mark_stack_->PushBack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001119 } else {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001120 CHECK_EQ(static_cast<uint32_t>(mark_stack_mode),
Hiroshi Yamauchifa755182015-09-30 20:12:11 -07001121 static_cast<uint32_t>(kMarkStackModeGcExclusive))
1122 << "ref=" << to_ref
1123 << " self->gc_marking=" << self->GetIsGcMarking()
1124 << " cc->is_marking=" << is_marking_;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001125 CHECK(self == thread_running_gc_)
1126 << "Only GC-running thread should access the mark stack "
1127 << "in the GC exclusive mark stack mode";
1128 // Access the GC mark stack without a lock.
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -07001129 if (UNLIKELY(gc_mark_stack_->IsFull())) {
1130 ExpandGcMarkStack();
1131 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001132 gc_mark_stack_->PushBack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001133 }
1134}
1135
1136accounting::ObjectStack* ConcurrentCopying::GetAllocationStack() {
1137 return heap_->allocation_stack_.get();
1138}
1139
1140accounting::ObjectStack* ConcurrentCopying::GetLiveStack() {
1141 return heap_->live_stack_.get();
1142}
1143
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001144// The following visitors are used to verify that there's no references to the from-space left after
1145// marking.
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001146class ConcurrentCopying::VerifyNoFromSpaceRefsVisitor : public SingleRootVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001147 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001148 explicit VerifyNoFromSpaceRefsVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001149 : collector_(collector) {}
1150
Mathieu Chartierbc632f02017-04-20 13:31:39 -07001151 void operator()(mirror::Object* ref,
1152 MemberOffset offset = MemberOffset(0),
1153 mirror::Object* holder = nullptr) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001154 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001155 if (ref == nullptr) {
1156 // OK.
1157 return;
1158 }
Mathieu Chartierbc632f02017-04-20 13:31:39 -07001159 collector_->AssertToSpaceInvariant(holder, offset, ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001160 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001161 CHECK_EQ(ref->GetReadBarrierState(), ReadBarrier::WhiteState())
David Sehr709b0702016-10-13 09:12:37 -07001162 << "Ref " << ref << " " << ref->PrettyTypeOf()
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001163 << " has non-white rb_state ";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001164 }
1165 }
1166
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001167 void VisitRoot(mirror::Object* root, const RootInfo& info ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001168 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001169 DCHECK(root != nullptr);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001170 operator()(root);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001171 }
1172
1173 private:
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001174 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001175};
1176
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001177class ConcurrentCopying::VerifyNoFromSpaceRefsFieldVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001178 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001179 explicit VerifyNoFromSpaceRefsFieldVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001180 : collector_(collector) {}
1181
Mathieu Chartier31e88222016-10-14 18:43:19 -07001182 void operator()(ObjPtr<mirror::Object> obj,
1183 MemberOffset offset,
1184 bool is_static ATTRIBUTE_UNUSED) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001185 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001186 mirror::Object* ref =
1187 obj->GetFieldObject<mirror::Object, kDefaultVerifyFlags, kWithoutReadBarrier>(offset);
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001188 VerifyNoFromSpaceRefsVisitor visitor(collector_);
Mathieu Chartierbc632f02017-04-20 13:31:39 -07001189 visitor(ref, offset, obj.Ptr());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001190 }
Mathieu Chartier31e88222016-10-14 18:43:19 -07001191 void operator()(ObjPtr<mirror::Class> klass,
1192 ObjPtr<mirror::Reference> ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001193 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001194 CHECK(klass->IsTypeOfReferenceClass());
1195 this->operator()(ref, mirror::Reference::ReferentOffset(), false);
1196 }
1197
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001198 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001199 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001200 if (!root->IsNull()) {
1201 VisitRoot(root);
1202 }
1203 }
1204
1205 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001206 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001207 VerifyNoFromSpaceRefsVisitor visitor(collector_);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001208 visitor(root->AsMirrorPtr());
1209 }
1210
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001211 private:
Mathieu Chartier97509952015-07-13 14:35:43 -07001212 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001213};
1214
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001215// Verify there's no from-space references left after the marking phase.
1216void ConcurrentCopying::VerifyNoFromSpaceReferences() {
1217 Thread* self = Thread::Current();
1218 DCHECK(Locks::mutator_lock_->IsExclusiveHeld(self));
Hiroshi Yamauchi00370822015-08-18 14:47:25 -07001219 // Verify all threads have is_gc_marking to be false
1220 {
1221 MutexLock mu(self, *Locks::thread_list_lock_);
1222 std::list<Thread*> thread_list = Runtime::Current()->GetThreadList()->GetList();
1223 for (Thread* thread : thread_list) {
1224 CHECK(!thread->GetIsGcMarking());
1225 }
1226 }
Andreas Gampe0c183382017-07-13 22:26:24 -07001227
1228 auto verify_no_from_space_refs_visitor = [&](mirror::Object* obj)
1229 REQUIRES_SHARED(Locks::mutator_lock_) {
1230 CHECK(obj != nullptr);
1231 space::RegionSpace* region_space = RegionSpace();
1232 CHECK(!region_space->IsInFromSpace(obj)) << "Scanning object " << obj << " in from space";
1233 VerifyNoFromSpaceRefsFieldVisitor visitor(this);
1234 obj->VisitReferences</*kVisitNativeRoots*/true, kDefaultVerifyFlags, kWithoutReadBarrier>(
1235 visitor,
1236 visitor);
1237 if (kUseBakerReadBarrier) {
1238 CHECK_EQ(obj->GetReadBarrierState(), ReadBarrier::WhiteState())
1239 << "obj=" << obj << " non-white rb_state " << obj->GetReadBarrierState();
1240 }
1241 };
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001242 // Roots.
1243 {
1244 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001245 VerifyNoFromSpaceRefsVisitor ref_visitor(this);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001246 Runtime::Current()->VisitRoots(&ref_visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001247 }
1248 // The to-space.
Andreas Gampe0c183382017-07-13 22:26:24 -07001249 region_space_->WalkToSpace(verify_no_from_space_refs_visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001250 // Non-moving spaces.
1251 {
1252 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Andreas Gampe0c183382017-07-13 22:26:24 -07001253 heap_->GetMarkBitmap()->Visit(verify_no_from_space_refs_visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001254 }
1255 // The alloc stack.
1256 {
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001257 VerifyNoFromSpaceRefsVisitor ref_visitor(this);
Mathieu Chartiercb535da2015-01-23 13:50:03 -08001258 for (auto* it = heap_->allocation_stack_->Begin(), *end = heap_->allocation_stack_->End();
1259 it < end; ++it) {
1260 mirror::Object* const obj = it->AsMirrorPtr();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001261 if (obj != nullptr && obj->GetClass() != nullptr) {
1262 // TODO: need to call this only if obj is alive?
1263 ref_visitor(obj);
Andreas Gampe0c183382017-07-13 22:26:24 -07001264 verify_no_from_space_refs_visitor(obj);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001265 }
1266 }
1267 }
1268 // TODO: LOS. But only refs in LOS are classes.
1269}
1270
1271// The following visitors are used to assert the to-space invariant.
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001272class ConcurrentCopying::AssertToSpaceInvariantRefsVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001273 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001274 explicit AssertToSpaceInvariantRefsVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001275 : collector_(collector) {}
1276
1277 void operator()(mirror::Object* ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001278 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001279 if (ref == nullptr) {
1280 // OK.
1281 return;
1282 }
1283 collector_->AssertToSpaceInvariant(nullptr, MemberOffset(0), ref);
1284 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001285
1286 private:
Mathieu Chartier97509952015-07-13 14:35:43 -07001287 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001288};
1289
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001290class ConcurrentCopying::AssertToSpaceInvariantFieldVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001291 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001292 explicit AssertToSpaceInvariantFieldVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001293 : collector_(collector) {}
1294
Mathieu Chartier31e88222016-10-14 18:43:19 -07001295 void operator()(ObjPtr<mirror::Object> obj,
1296 MemberOffset offset,
1297 bool is_static ATTRIBUTE_UNUSED) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001298 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001299 mirror::Object* ref =
1300 obj->GetFieldObject<mirror::Object, kDefaultVerifyFlags, kWithoutReadBarrier>(offset);
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001301 AssertToSpaceInvariantRefsVisitor visitor(collector_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001302 visitor(ref);
1303 }
Mathieu Chartier31e88222016-10-14 18:43:19 -07001304 void operator()(ObjPtr<mirror::Class> klass, ObjPtr<mirror::Reference> ref ATTRIBUTE_UNUSED) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001305 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001306 CHECK(klass->IsTypeOfReferenceClass());
1307 }
1308
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001309 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001310 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001311 if (!root->IsNull()) {
1312 VisitRoot(root);
1313 }
1314 }
1315
1316 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001317 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001318 AssertToSpaceInvariantRefsVisitor visitor(collector_);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001319 visitor(root->AsMirrorPtr());
1320 }
1321
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001322 private:
Mathieu Chartier97509952015-07-13 14:35:43 -07001323 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001324};
1325
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001326class ConcurrentCopying::RevokeThreadLocalMarkStackCheckpoint : public Closure {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001327 public:
Roland Levillain3887c462015-08-12 18:15:42 +01001328 RevokeThreadLocalMarkStackCheckpoint(ConcurrentCopying* concurrent_copying,
1329 bool disable_weak_ref_access)
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001330 : concurrent_copying_(concurrent_copying),
1331 disable_weak_ref_access_(disable_weak_ref_access) {
1332 }
1333
1334 virtual void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
1335 // Note: self is not necessarily equal to thread since thread may be suspended.
1336 Thread* self = Thread::Current();
1337 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
1338 << thread->GetState() << " thread " << thread << " self " << self;
1339 // Revoke thread local mark stacks.
1340 accounting::AtomicStack<mirror::Object>* tl_mark_stack = thread->GetThreadLocalMarkStack();
1341 if (tl_mark_stack != nullptr) {
1342 MutexLock mu(self, concurrent_copying_->mark_stack_lock_);
1343 concurrent_copying_->revoked_mark_stacks_.push_back(tl_mark_stack);
1344 thread->SetThreadLocalMarkStack(nullptr);
1345 }
1346 // Disable weak ref access.
1347 if (disable_weak_ref_access_) {
1348 thread->SetWeakRefAccessEnabled(false);
1349 }
1350 // If thread is a running mutator, then act on behalf of the garbage collector.
1351 // See the code in ThreadList::RunCheckpoint.
Mathieu Chartier10d25082015-10-28 18:36:09 -07001352 concurrent_copying_->GetBarrier().Pass(self);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001353 }
1354
1355 private:
1356 ConcurrentCopying* const concurrent_copying_;
1357 const bool disable_weak_ref_access_;
1358};
1359
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001360void ConcurrentCopying::RevokeThreadLocalMarkStacks(bool disable_weak_ref_access,
1361 Closure* checkpoint_callback) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001362 Thread* self = Thread::Current();
1363 RevokeThreadLocalMarkStackCheckpoint check_point(this, disable_weak_ref_access);
1364 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1365 gc_barrier_->Init(self, 0);
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001366 size_t barrier_count = thread_list->RunCheckpoint(&check_point, checkpoint_callback);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001367 // If there are no threads to wait which implys that all the checkpoint functions are finished,
1368 // then no need to release the mutator lock.
1369 if (barrier_count == 0) {
1370 return;
1371 }
1372 Locks::mutator_lock_->SharedUnlock(self);
1373 {
1374 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
1375 gc_barrier_->Increment(self, barrier_count);
1376 }
1377 Locks::mutator_lock_->SharedLock(self);
1378}
1379
1380void ConcurrentCopying::RevokeThreadLocalMarkStack(Thread* thread) {
1381 Thread* self = Thread::Current();
1382 CHECK_EQ(self, thread);
1383 accounting::AtomicStack<mirror::Object>* tl_mark_stack = thread->GetThreadLocalMarkStack();
1384 if (tl_mark_stack != nullptr) {
1385 CHECK(is_marking_);
1386 MutexLock mu(self, mark_stack_lock_);
1387 revoked_mark_stacks_.push_back(tl_mark_stack);
1388 thread->SetThreadLocalMarkStack(nullptr);
1389 }
1390}
1391
1392void ConcurrentCopying::ProcessMarkStack() {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001393 if (kVerboseMode) {
1394 LOG(INFO) << "ProcessMarkStack. ";
1395 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001396 bool empty_prev = false;
1397 while (true) {
1398 bool empty = ProcessMarkStackOnce();
1399 if (empty_prev && empty) {
1400 // Saw empty mark stack for a second time, done.
1401 break;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001402 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001403 empty_prev = empty;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001404 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001405}
1406
1407bool ConcurrentCopying::ProcessMarkStackOnce() {
1408 Thread* self = Thread::Current();
1409 CHECK(thread_running_gc_ != nullptr);
1410 CHECK(self == thread_running_gc_);
1411 CHECK(self->GetThreadLocalMarkStack() == nullptr);
1412 size_t count = 0;
1413 MarkStackMode mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1414 if (mark_stack_mode == kMarkStackModeThreadLocal) {
1415 // Process the thread-local mark stacks and the GC mark stack.
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001416 count += ProcessThreadLocalMarkStacks(false, nullptr);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001417 while (!gc_mark_stack_->IsEmpty()) {
1418 mirror::Object* to_ref = gc_mark_stack_->PopBack();
1419 ProcessMarkStackRef(to_ref);
1420 ++count;
1421 }
1422 gc_mark_stack_->Reset();
1423 } else if (mark_stack_mode == kMarkStackModeShared) {
Hiroshi Yamauchi30493242016-11-03 13:06:52 -07001424 // Do an empty checkpoint to avoid a race with a mutator preempted in the middle of a read
1425 // barrier but before pushing onto the mark stack. b/32508093. Note the weak ref access is
1426 // disabled at this point.
1427 IssueEmptyCheckpoint();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001428 // Process the shared GC mark stack with a lock.
1429 {
1430 MutexLock mu(self, mark_stack_lock_);
1431 CHECK(revoked_mark_stacks_.empty());
1432 }
1433 while (true) {
1434 std::vector<mirror::Object*> refs;
1435 {
1436 // Copy refs with lock. Note the number of refs should be small.
1437 MutexLock mu(self, mark_stack_lock_);
1438 if (gc_mark_stack_->IsEmpty()) {
1439 break;
1440 }
1441 for (StackReference<mirror::Object>* p = gc_mark_stack_->Begin();
1442 p != gc_mark_stack_->End(); ++p) {
1443 refs.push_back(p->AsMirrorPtr());
1444 }
1445 gc_mark_stack_->Reset();
1446 }
1447 for (mirror::Object* ref : refs) {
1448 ProcessMarkStackRef(ref);
1449 ++count;
1450 }
1451 }
1452 } else {
1453 CHECK_EQ(static_cast<uint32_t>(mark_stack_mode),
1454 static_cast<uint32_t>(kMarkStackModeGcExclusive));
1455 {
1456 MutexLock mu(self, mark_stack_lock_);
1457 CHECK(revoked_mark_stacks_.empty());
1458 }
1459 // Process the GC mark stack in the exclusive mode. No need to take the lock.
1460 while (!gc_mark_stack_->IsEmpty()) {
1461 mirror::Object* to_ref = gc_mark_stack_->PopBack();
1462 ProcessMarkStackRef(to_ref);
1463 ++count;
1464 }
1465 gc_mark_stack_->Reset();
1466 }
1467
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001468 // Return true if the stack was empty.
1469 return count == 0;
1470}
1471
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001472size_t ConcurrentCopying::ProcessThreadLocalMarkStacks(bool disable_weak_ref_access,
1473 Closure* checkpoint_callback) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001474 // Run a checkpoint to collect all thread local mark stacks and iterate over them all.
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001475 RevokeThreadLocalMarkStacks(disable_weak_ref_access, checkpoint_callback);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001476 size_t count = 0;
1477 std::vector<accounting::AtomicStack<mirror::Object>*> mark_stacks;
1478 {
1479 MutexLock mu(Thread::Current(), mark_stack_lock_);
1480 // Make a copy of the mark stack vector.
1481 mark_stacks = revoked_mark_stacks_;
1482 revoked_mark_stacks_.clear();
1483 }
1484 for (accounting::AtomicStack<mirror::Object>* mark_stack : mark_stacks) {
1485 for (StackReference<mirror::Object>* p = mark_stack->Begin(); p != mark_stack->End(); ++p) {
1486 mirror::Object* to_ref = p->AsMirrorPtr();
1487 ProcessMarkStackRef(to_ref);
1488 ++count;
1489 }
1490 {
1491 MutexLock mu(Thread::Current(), mark_stack_lock_);
1492 if (pooled_mark_stacks_.size() >= kMarkStackPoolSize) {
1493 // The pool has enough. Delete it.
1494 delete mark_stack;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001495 } else {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001496 // Otherwise, put it into the pool for later reuse.
1497 mark_stack->Reset();
1498 pooled_mark_stacks_.push_back(mark_stack);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001499 }
1500 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001501 }
1502 return count;
1503}
1504
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001505inline void ConcurrentCopying::ProcessMarkStackRef(mirror::Object* to_ref) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001506 DCHECK(!region_space_->IsInFromSpace(to_ref));
1507 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001508 DCHECK(to_ref->GetReadBarrierState() == ReadBarrier::GrayState())
1509 << " " << to_ref << " " << to_ref->GetReadBarrierState()
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001510 << " is_marked=" << IsMarked(to_ref);
1511 }
Mathieu Chartierc381c362016-08-23 13:27:53 -07001512 bool add_to_live_bytes = false;
1513 if (region_space_->IsInUnevacFromSpace(to_ref)) {
1514 // Mark the bitmap only in the GC thread here so that we don't need a CAS.
1515 if (!kUseBakerReadBarrier || !region_space_bitmap_->Set(to_ref)) {
1516 // It may be already marked if we accidentally pushed the same object twice due to the racy
1517 // bitmap read in MarkUnevacFromSpaceRegion.
1518 Scan(to_ref);
1519 // Only add to the live bytes if the object was not already marked.
1520 add_to_live_bytes = true;
1521 }
1522 } else {
1523 Scan(to_ref);
1524 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001525 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001526 DCHECK(to_ref->GetReadBarrierState() == ReadBarrier::GrayState())
1527 << " " << to_ref << " " << to_ref->GetReadBarrierState()
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001528 << " is_marked=" << IsMarked(to_ref);
1529 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001530#ifdef USE_BAKER_OR_BROOKS_READ_BARRIER
Hiroshi Yamauchi39c12d42016-12-06 16:46:37 -08001531 mirror::Object* referent = nullptr;
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001532 if (UNLIKELY((to_ref->GetClass<kVerifyNone, kWithoutReadBarrier>()->IsTypeOfReferenceClass() &&
Hiroshi Yamauchi39c12d42016-12-06 16:46:37 -08001533 (referent = to_ref->AsReference()->GetReferent<kWithoutReadBarrier>()) != nullptr &&
1534 !IsInToSpace(referent)))) {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001535 // Leave this reference gray in the queue so that GetReferent() will trigger a read barrier. We
1536 // will change it to white later in ReferenceQueue::DequeuePendingReference().
Richard Uhlere3627402016-02-02 13:36:55 -08001537 DCHECK(to_ref->AsReference()->GetPendingNext() != nullptr) << "Left unenqueued ref gray " << to_ref;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001538 } else {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001539 // We may occasionally leave a reference white in the queue if its referent happens to be
1540 // concurrently marked after the Scan() call above has enqueued the Reference, in which case the
1541 // above IsInToSpace() evaluates to true and we change the color from gray to white here in this
1542 // else block.
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001543 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001544 bool success = to_ref->AtomicSetReadBarrierState</*kCasRelease*/true>(
1545 ReadBarrier::GrayState(),
1546 ReadBarrier::WhiteState());
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001547 DCHECK(success) << "Must succeed as we won the race.";
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001548 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001549 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001550#else
1551 DCHECK(!kUseBakerReadBarrier);
1552#endif
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001553
Mathieu Chartierc381c362016-08-23 13:27:53 -07001554 if (add_to_live_bytes) {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001555 // Add to the live bytes per unevacuated from space. Note this code is always run by the
1556 // GC-running thread (no synchronization required).
1557 DCHECK(region_space_bitmap_->Test(to_ref));
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07001558 size_t obj_size = to_ref->SizeOf<kDefaultVerifyFlags>();
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001559 size_t alloc_size = RoundUp(obj_size, space::RegionSpace::kAlignment);
1560 region_space_->AddLiveBytes(to_ref, alloc_size);
1561 }
Andreas Gampee3ce7872017-02-22 13:36:21 -08001562 if (ReadBarrier::kEnableToSpaceInvariantChecks) {
Andreas Gampe0c183382017-07-13 22:26:24 -07001563 CHECK(to_ref != nullptr);
1564 space::RegionSpace* region_space = RegionSpace();
1565 CHECK(!region_space->IsInFromSpace(to_ref)) << "Scanning object " << to_ref << " in from space";
1566 AssertToSpaceInvariant(nullptr, MemberOffset(0), to_ref);
1567 AssertToSpaceInvariantFieldVisitor visitor(this);
1568 to_ref->VisitReferences</*kVisitNativeRoots*/true, kDefaultVerifyFlags, kWithoutReadBarrier>(
1569 visitor,
1570 visitor);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001571 }
1572}
1573
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001574class ConcurrentCopying::DisableWeakRefAccessCallback : public Closure {
1575 public:
1576 explicit DisableWeakRefAccessCallback(ConcurrentCopying* concurrent_copying)
1577 : concurrent_copying_(concurrent_copying) {
1578 }
1579
1580 void Run(Thread* self ATTRIBUTE_UNUSED) OVERRIDE REQUIRES(Locks::thread_list_lock_) {
1581 // This needs to run under the thread_list_lock_ critical section in ThreadList::RunCheckpoint()
1582 // to avoid a deadlock b/31500969.
1583 CHECK(concurrent_copying_->weak_ref_access_enabled_);
1584 concurrent_copying_->weak_ref_access_enabled_ = false;
1585 }
1586
1587 private:
1588 ConcurrentCopying* const concurrent_copying_;
1589};
1590
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001591void ConcurrentCopying::SwitchToSharedMarkStackMode() {
1592 Thread* self = Thread::Current();
1593 CHECK(thread_running_gc_ != nullptr);
1594 CHECK_EQ(self, thread_running_gc_);
1595 CHECK(self->GetThreadLocalMarkStack() == nullptr);
1596 MarkStackMode before_mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1597 CHECK_EQ(static_cast<uint32_t>(before_mark_stack_mode),
1598 static_cast<uint32_t>(kMarkStackModeThreadLocal));
1599 mark_stack_mode_.StoreRelaxed(kMarkStackModeShared);
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001600 DisableWeakRefAccessCallback dwrac(this);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001601 // Process the thread local mark stacks one last time after switching to the shared mark stack
1602 // mode and disable weak ref accesses.
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001603 ProcessThreadLocalMarkStacks(true, &dwrac);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001604 if (kVerboseMode) {
1605 LOG(INFO) << "Switched to shared mark stack mode and disabled weak ref access";
1606 }
1607}
1608
1609void ConcurrentCopying::SwitchToGcExclusiveMarkStackMode() {
1610 Thread* self = Thread::Current();
1611 CHECK(thread_running_gc_ != nullptr);
1612 CHECK_EQ(self, thread_running_gc_);
1613 CHECK(self->GetThreadLocalMarkStack() == nullptr);
1614 MarkStackMode before_mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1615 CHECK_EQ(static_cast<uint32_t>(before_mark_stack_mode),
1616 static_cast<uint32_t>(kMarkStackModeShared));
1617 mark_stack_mode_.StoreRelaxed(kMarkStackModeGcExclusive);
1618 QuasiAtomic::ThreadFenceForConstructor();
1619 if (kVerboseMode) {
1620 LOG(INFO) << "Switched to GC exclusive mark stack mode";
1621 }
1622}
1623
1624void ConcurrentCopying::CheckEmptyMarkStack() {
1625 Thread* self = Thread::Current();
1626 CHECK(thread_running_gc_ != nullptr);
1627 CHECK_EQ(self, thread_running_gc_);
1628 CHECK(self->GetThreadLocalMarkStack() == nullptr);
1629 MarkStackMode mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1630 if (mark_stack_mode == kMarkStackModeThreadLocal) {
1631 // Thread-local mark stack mode.
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001632 RevokeThreadLocalMarkStacks(false, nullptr);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001633 MutexLock mu(Thread::Current(), mark_stack_lock_);
1634 if (!revoked_mark_stacks_.empty()) {
1635 for (accounting::AtomicStack<mirror::Object>* mark_stack : revoked_mark_stacks_) {
1636 while (!mark_stack->IsEmpty()) {
1637 mirror::Object* obj = mark_stack->PopBack();
1638 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001639 uint32_t rb_state = obj->GetReadBarrierState();
1640 LOG(INFO) << "On mark queue : " << obj << " " << obj->PrettyTypeOf() << " rb_state="
1641 << rb_state << " is_marked=" << IsMarked(obj);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001642 } else {
David Sehr709b0702016-10-13 09:12:37 -07001643 LOG(INFO) << "On mark queue : " << obj << " " << obj->PrettyTypeOf()
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001644 << " is_marked=" << IsMarked(obj);
1645 }
1646 }
1647 }
1648 LOG(FATAL) << "mark stack is not empty";
1649 }
1650 } else {
1651 // Shared, GC-exclusive, or off.
1652 MutexLock mu(Thread::Current(), mark_stack_lock_);
1653 CHECK(gc_mark_stack_->IsEmpty());
1654 CHECK(revoked_mark_stacks_.empty());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001655 }
1656}
1657
1658void ConcurrentCopying::SweepSystemWeaks(Thread* self) {
1659 TimingLogger::ScopedTiming split("SweepSystemWeaks", GetTimings());
1660 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier97509952015-07-13 14:35:43 -07001661 Runtime::Current()->SweepSystemWeaks(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001662}
1663
1664void ConcurrentCopying::Sweep(bool swap_bitmaps) {
1665 {
1666 TimingLogger::ScopedTiming t("MarkStackAsLive", GetTimings());
1667 accounting::ObjectStack* live_stack = heap_->GetLiveStack();
1668 if (kEnableFromSpaceAccountingCheck) {
1669 CHECK_GE(live_stack_freeze_size_, live_stack->Size());
1670 }
1671 heap_->MarkAllocStackAsLive(live_stack);
1672 live_stack->Reset();
1673 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001674 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001675 TimingLogger::ScopedTiming split("Sweep", GetTimings());
1676 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
1677 if (space->IsContinuousMemMapAllocSpace()) {
1678 space::ContinuousMemMapAllocSpace* alloc_space = space->AsContinuousMemMapAllocSpace();
Mathieu Chartier763a31e2015-11-16 16:05:55 -08001679 if (space == region_space_ || immune_spaces_.ContainsSpace(space)) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001680 continue;
1681 }
1682 TimingLogger::ScopedTiming split2(
1683 alloc_space->IsZygoteSpace() ? "SweepZygoteSpace" : "SweepAllocSpace", GetTimings());
1684 RecordFree(alloc_space->Sweep(swap_bitmaps));
1685 }
1686 }
1687 SweepLargeObjects(swap_bitmaps);
1688}
1689
Mathieu Chartier962cd7a2016-08-16 12:15:59 -07001690void ConcurrentCopying::MarkZygoteLargeObjects() {
1691 TimingLogger::ScopedTiming split(__FUNCTION__, GetTimings());
1692 Thread* const self = Thread::Current();
1693 WriterMutexLock rmu(self, *Locks::heap_bitmap_lock_);
1694 space::LargeObjectSpace* const los = heap_->GetLargeObjectsSpace();
Nicolas Geoffray7acddd82017-05-03 15:04:55 +01001695 if (los != nullptr) {
1696 // Pick the current live bitmap (mark bitmap if swapped).
1697 accounting::LargeObjectBitmap* const live_bitmap = los->GetLiveBitmap();
1698 accounting::LargeObjectBitmap* const mark_bitmap = los->GetMarkBitmap();
1699 // Walk through all of the objects and explicitly mark the zygote ones so they don't get swept.
1700 std::pair<uint8_t*, uint8_t*> range = los->GetBeginEndAtomic();
1701 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(range.first),
1702 reinterpret_cast<uintptr_t>(range.second),
1703 [mark_bitmap, los, self](mirror::Object* obj)
1704 REQUIRES(Locks::heap_bitmap_lock_)
1705 REQUIRES_SHARED(Locks::mutator_lock_) {
1706 if (los->IsZygoteLargeObject(self, obj)) {
1707 mark_bitmap->Set(obj);
1708 }
1709 });
1710 }
Mathieu Chartier962cd7a2016-08-16 12:15:59 -07001711}
1712
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001713void ConcurrentCopying::SweepLargeObjects(bool swap_bitmaps) {
1714 TimingLogger::ScopedTiming split("SweepLargeObjects", GetTimings());
Nicolas Geoffray7acddd82017-05-03 15:04:55 +01001715 if (heap_->GetLargeObjectsSpace() != nullptr) {
1716 RecordFreeLOS(heap_->GetLargeObjectsSpace()->Sweep(swap_bitmaps));
1717 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001718}
1719
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001720void ConcurrentCopying::ReclaimPhase() {
1721 TimingLogger::ScopedTiming split("ReclaimPhase", GetTimings());
1722 if (kVerboseMode) {
1723 LOG(INFO) << "GC ReclaimPhase";
1724 }
1725 Thread* self = Thread::Current();
1726
1727 {
1728 // Double-check that the mark stack is empty.
1729 // Note: need to set this after VerifyNoFromSpaceRef().
1730 is_asserting_to_space_invariant_ = false;
1731 QuasiAtomic::ThreadFenceForConstructor();
1732 if (kVerboseMode) {
1733 LOG(INFO) << "Issue an empty check point. ";
1734 }
1735 IssueEmptyCheckpoint();
1736 // Disable the check.
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001737 is_mark_stack_push_disallowed_.StoreSequentiallyConsistent(0);
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001738 if (kUseBakerReadBarrier) {
1739 updated_all_immune_objects_.StoreSequentiallyConsistent(false);
1740 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001741 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001742 }
1743
1744 {
1745 // Record freed objects.
1746 TimingLogger::ScopedTiming split2("RecordFree", GetTimings());
1747 // Don't include thread-locals that are in the to-space.
Mathieu Chartier371b0472017-02-27 16:37:21 -08001748 const uint64_t from_bytes = region_space_->GetBytesAllocatedInFromSpace();
1749 const uint64_t from_objects = region_space_->GetObjectsAllocatedInFromSpace();
1750 const uint64_t unevac_from_bytes = region_space_->GetBytesAllocatedInUnevacFromSpace();
1751 const uint64_t unevac_from_objects = region_space_->GetObjectsAllocatedInUnevacFromSpace();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001752 uint64_t to_bytes = bytes_moved_.LoadSequentiallyConsistent();
Mathieu Chartiercca44a02016-08-17 10:07:29 -07001753 cumulative_bytes_moved_.FetchAndAddRelaxed(to_bytes);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001754 uint64_t to_objects = objects_moved_.LoadSequentiallyConsistent();
Mathieu Chartiercca44a02016-08-17 10:07:29 -07001755 cumulative_objects_moved_.FetchAndAddRelaxed(to_objects);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001756 if (kEnableFromSpaceAccountingCheck) {
1757 CHECK_EQ(from_space_num_objects_at_first_pause_, from_objects + unevac_from_objects);
1758 CHECK_EQ(from_space_num_bytes_at_first_pause_, from_bytes + unevac_from_bytes);
1759 }
1760 CHECK_LE(to_objects, from_objects);
1761 CHECK_LE(to_bytes, from_bytes);
Mathieu Chartier371b0472017-02-27 16:37:21 -08001762 // cleared_bytes and cleared_objects may be greater than the from space equivalents since
1763 // ClearFromSpace may clear empty unevac regions.
1764 uint64_t cleared_bytes;
1765 uint64_t cleared_objects;
1766 {
1767 TimingLogger::ScopedTiming split4("ClearFromSpace", GetTimings());
1768 region_space_->ClearFromSpace(&cleared_bytes, &cleared_objects);
1769 CHECK_GE(cleared_bytes, from_bytes);
1770 CHECK_GE(cleared_objects, from_objects);
1771 }
1772 int64_t freed_bytes = cleared_bytes - to_bytes;
1773 int64_t freed_objects = cleared_objects - to_objects;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001774 if (kVerboseMode) {
1775 LOG(INFO) << "RecordFree:"
1776 << " from_bytes=" << from_bytes << " from_objects=" << from_objects
1777 << " unevac_from_bytes=" << unevac_from_bytes << " unevac_from_objects=" << unevac_from_objects
1778 << " to_bytes=" << to_bytes << " to_objects=" << to_objects
1779 << " freed_bytes=" << freed_bytes << " freed_objects=" << freed_objects
1780 << " from_space size=" << region_space_->FromSpaceSize()
1781 << " unevac_from_space size=" << region_space_->UnevacFromSpaceSize()
1782 << " to_space size=" << region_space_->ToSpaceSize();
1783 LOG(INFO) << "(before) num_bytes_allocated=" << heap_->num_bytes_allocated_.LoadSequentiallyConsistent();
1784 }
1785 RecordFree(ObjectBytePair(freed_objects, freed_bytes));
1786 if (kVerboseMode) {
1787 LOG(INFO) << "(after) num_bytes_allocated=" << heap_->num_bytes_allocated_.LoadSequentiallyConsistent();
1788 }
1789 }
1790
1791 {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001792 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001793 Sweep(false);
1794 SwapBitmaps();
1795 heap_->UnBindBitmaps();
1796
Mathieu Chartier7ec38dc2016-10-07 15:24:46 -07001797 // 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 -07001798 DCHECK(region_space_bitmap_ != nullptr);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001799 region_space_bitmap_ = nullptr;
1800 }
1801
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001802 CheckEmptyMarkStack();
1803
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001804 if (kVerboseMode) {
1805 LOG(INFO) << "GC end of ReclaimPhase";
1806 }
1807}
1808
Roland Levillain001eff92018-01-24 14:24:33 +00001809std::string ConcurrentCopying::DumpReferenceInfo(mirror::Object* ref,
1810 const char* ref_name,
1811 std::string indent) {
1812 std::ostringstream oss;
1813 oss << indent << heap_->GetVerification()->DumpObjectInfo(ref, ref_name) << '\n';
1814 if (ref != nullptr) {
1815 if (kUseBakerReadBarrier) {
1816 oss << indent << ref_name << "->GetMarkBit()=" << ref->GetMarkBit() << '\n';
1817 oss << indent << ref_name << "->GetReadBarrierState()=" << ref->GetReadBarrierState() << '\n';
1818 }
1819 }
1820 if (region_space_->HasAddress(ref)) {
1821 oss << indent << "Region containing " << ref_name << ":" << '\n';
1822 region_space_->DumpRegionForObject(oss, ref);
1823 if (region_space_bitmap_ != nullptr) {
1824 oss << indent << "region_space_bitmap_->Test(" << ref_name << ")="
1825 << std::boolalpha << region_space_bitmap_->Test(ref) << std::noboolalpha;
1826 }
1827 }
1828 return oss.str();
1829}
1830
1831std::string ConcurrentCopying::DumpHeapReference(mirror::Object* obj,
1832 MemberOffset offset,
1833 mirror::Object* ref) {
1834 std::ostringstream oss;
1835 std::string indent = " ";
1836 oss << indent << "Invalid reference: ref=" << ref
1837 << " referenced from: object=" << obj << " offset= " << offset << '\n';
1838 // Information about `obj`.
1839 oss << DumpReferenceInfo(obj, "obj", indent) << '\n';
1840 // Information about `ref`.
1841 oss << DumpReferenceInfo(ref, "ref", indent);
1842 return oss.str();
1843}
1844
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07001845void ConcurrentCopying::AssertToSpaceInvariant(mirror::Object* obj,
1846 MemberOffset offset,
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001847 mirror::Object* ref) {
Roland Levillain001eff92018-01-24 14:24:33 +00001848 CHECK_EQ(heap_->collector_type_, kCollectorTypeCC) << static_cast<size_t>(heap_->collector_type_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001849 if (is_asserting_to_space_invariant_) {
Roland Levillain001eff92018-01-24 14:24:33 +00001850 if (region_space_->HasAddress(ref)) {
1851 // Check to-space invariant in region space (moving space).
1852 using RegionType = space::RegionSpace::RegionType;
1853 space::RegionSpace::RegionType type = region_space_->GetRegionType(ref);
1854 if (type == RegionType::kRegionTypeToSpace) {
1855 // OK.
1856 return;
1857 } else if (type == RegionType::kRegionTypeUnevacFromSpace) {
1858 if (!IsMarkedInUnevacFromSpace(ref)) {
1859 LOG(FATAL_WITHOUT_ABORT) << "Found unmarked reference in unevac from-space:";
1860 LOG(FATAL_WITHOUT_ABORT) << DumpHeapReference(obj, offset, ref);
1861 }
1862 CHECK(IsMarkedInUnevacFromSpace(ref)) << ref;
1863 } else {
1864 // Not OK: either a from-space ref or a reference in an unused region.
1865 // Do extra logging.
1866 if (type == RegionType::kRegionTypeFromSpace) {
1867 LOG(FATAL_WITHOUT_ABORT) << "Found from-space reference:";
1868 } else {
1869 LOG(FATAL_WITHOUT_ABORT) << "Found reference in region with type " << type << ":";
1870 }
1871 LOG(FATAL_WITHOUT_ABORT) << DumpHeapReference(obj, offset, ref);
1872 if (obj != nullptr) {
1873 LogFromSpaceRefHolder(obj, offset);
1874 }
1875 ref->GetLockWord(false).Dump(LOG_STREAM(FATAL_WITHOUT_ABORT));
1876 LOG(FATAL_WITHOUT_ABORT) << "Non-free regions:";
1877 region_space_->DumpNonFreeRegions(LOG_STREAM(FATAL_WITHOUT_ABORT));
1878 PrintFileToLog("/proc/self/maps", LogSeverity::FATAL_WITHOUT_ABORT);
1879 MemMap::DumpMaps(LOG_STREAM(FATAL_WITHOUT_ABORT), true);
1880 LOG(FATAL) << "Invalid reference " << ref
1881 << " referenced from object " << obj << " at offset " << offset;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001882 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001883 } else {
Roland Levillain001eff92018-01-24 14:24:33 +00001884 // Check to-space invariant in non-moving space.
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001885 AssertToSpaceInvariantInNonMovingSpace(obj, ref);
1886 }
1887 }
1888}
1889
1890class RootPrinter {
1891 public:
1892 RootPrinter() { }
1893
1894 template <class MirrorType>
1895 ALWAYS_INLINE void VisitRootIfNonNull(mirror::CompressedReference<MirrorType>* root)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001896 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001897 if (!root->IsNull()) {
1898 VisitRoot(root);
1899 }
1900 }
1901
1902 template <class MirrorType>
1903 void VisitRoot(mirror::Object** root)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001904 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07001905 LOG(FATAL_WITHOUT_ABORT) << "root=" << root << " ref=" << *root;
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001906 }
1907
1908 template <class MirrorType>
1909 void VisitRoot(mirror::CompressedReference<MirrorType>* root)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001910 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07001911 LOG(FATAL_WITHOUT_ABORT) << "root=" << root << " ref=" << root->AsMirrorPtr();
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001912 }
1913};
1914
Roland Levillain001eff92018-01-24 14:24:33 +00001915std::string ConcurrentCopying::DumpGcRoot(mirror::Object* ref) {
1916 std::ostringstream oss;
1917 std::string indent = " ";
1918 oss << indent << "Invalid GC root: ref=" << ref << '\n';
1919 // Information about `ref`.
1920 oss << DumpReferenceInfo(ref, "ref", indent);
1921 return oss.str();
1922}
1923
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001924void ConcurrentCopying::AssertToSpaceInvariant(GcRootSource* gc_root_source,
1925 mirror::Object* ref) {
Roland Levillain001eff92018-01-24 14:24:33 +00001926 CHECK_EQ(heap_->collector_type_, kCollectorTypeCC) << static_cast<size_t>(heap_->collector_type_);
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001927 if (is_asserting_to_space_invariant_) {
Roland Levillain001eff92018-01-24 14:24:33 +00001928 if (region_space_->HasAddress(ref)) {
1929 // Check to-space invariant in region space (moving space).
1930 using RegionType = space::RegionSpace::RegionType;
1931 space::RegionSpace::RegionType type = region_space_->GetRegionType(ref);
1932 if (type == RegionType::kRegionTypeToSpace) {
1933 // OK.
1934 return;
1935 } else if (type == RegionType::kRegionTypeUnevacFromSpace) {
1936 if (!IsMarkedInUnevacFromSpace(ref)) {
1937 LOG(FATAL_WITHOUT_ABORT) << "Found unmarked reference in unevac from-space:";
1938 LOG(FATAL_WITHOUT_ABORT) << DumpGcRoot(ref);
1939 }
1940 CHECK(IsMarkedInUnevacFromSpace(ref)) << ref;
1941 } else {
1942 // Not OK: either a from-space ref or a reference in an unused region.
1943 // Do extra logging.
1944 if (type == RegionType::kRegionTypeFromSpace) {
1945 LOG(FATAL_WITHOUT_ABORT) << "Found from-space reference:";
1946 } else {
1947 LOG(FATAL_WITHOUT_ABORT) << "Found reference in region with type " << type << ":";
1948 }
1949 LOG(FATAL_WITHOUT_ABORT) << DumpGcRoot(ref);
1950 if (gc_root_source == nullptr) {
1951 // No info.
1952 } else if (gc_root_source->HasArtField()) {
1953 ArtField* field = gc_root_source->GetArtField();
1954 LOG(FATAL_WITHOUT_ABORT) << "gc root in field " << field << " "
1955 << ArtField::PrettyField(field);
1956 RootPrinter root_printer;
1957 field->VisitRoots(root_printer);
1958 } else if (gc_root_source->HasArtMethod()) {
1959 ArtMethod* method = gc_root_source->GetArtMethod();
1960 LOG(FATAL_WITHOUT_ABORT) << "gc root in method " << method << " "
1961 << ArtMethod::PrettyMethod(method);
1962 RootPrinter root_printer;
1963 method->VisitRoots(root_printer, kRuntimePointerSize);
1964 }
1965 ref->GetLockWord(false).Dump(LOG_STREAM(FATAL_WITHOUT_ABORT));
1966 LOG(FATAL_WITHOUT_ABORT) << "Non-free regions:";
1967 region_space_->DumpNonFreeRegions(LOG_STREAM(FATAL_WITHOUT_ABORT));
1968 PrintFileToLog("/proc/self/maps", LogSeverity::FATAL_WITHOUT_ABORT);
1969 MemMap::DumpMaps(LOG_STREAM(FATAL_WITHOUT_ABORT), true);
1970 LOG(FATAL) << "Invalid reference " << ref;
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001971 }
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001972 } else {
Roland Levillain001eff92018-01-24 14:24:33 +00001973 // Check to-space invariant in non-moving space.
1974 AssertToSpaceInvariantInNonMovingSpace(/* obj */ nullptr, ref);
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001975 }
1976 }
1977}
1978
1979void ConcurrentCopying::LogFromSpaceRefHolder(mirror::Object* obj, MemberOffset offset) {
1980 if (kUseBakerReadBarrier) {
David Sehr709b0702016-10-13 09:12:37 -07001981 LOG(INFO) << "holder=" << obj << " " << obj->PrettyTypeOf()
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001982 << " holder rb_state=" << obj->GetReadBarrierState();
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001983 } else {
David Sehr709b0702016-10-13 09:12:37 -07001984 LOG(INFO) << "holder=" << obj << " " << obj->PrettyTypeOf();
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001985 }
1986 if (region_space_->IsInFromSpace(obj)) {
1987 LOG(INFO) << "holder is in the from-space.";
1988 } else if (region_space_->IsInToSpace(obj)) {
1989 LOG(INFO) << "holder is in the to-space.";
1990 } else if (region_space_->IsInUnevacFromSpace(obj)) {
1991 LOG(INFO) << "holder is in the unevac from-space.";
Mathieu Chartierc381c362016-08-23 13:27:53 -07001992 if (IsMarkedInUnevacFromSpace(obj)) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001993 LOG(INFO) << "holder is marked in the region space bitmap.";
1994 } else {
1995 LOG(INFO) << "holder is not marked in the region space bitmap.";
1996 }
1997 } else {
1998 // In a non-moving space.
Mathieu Chartier763a31e2015-11-16 16:05:55 -08001999 if (immune_spaces_.ContainsObject(obj)) {
2000 LOG(INFO) << "holder is in an immune image or the zygote space.";
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002001 } else {
Mathieu Chartier763a31e2015-11-16 16:05:55 -08002002 LOG(INFO) << "holder is in a non-immune, non-moving (or main) space.";
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002003 accounting::ContinuousSpaceBitmap* mark_bitmap =
2004 heap_mark_bitmap_->GetContinuousSpaceBitmap(obj);
2005 accounting::LargeObjectBitmap* los_bitmap =
2006 heap_mark_bitmap_->GetLargeObjectBitmap(obj);
2007 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
2008 bool is_los = mark_bitmap == nullptr;
2009 if (!is_los && mark_bitmap->Test(obj)) {
2010 LOG(INFO) << "holder is marked in the mark bit map.";
2011 } else if (is_los && los_bitmap->Test(obj)) {
2012 LOG(INFO) << "holder is marked in the los bit map.";
2013 } else {
2014 // If ref is on the allocation stack, then it is considered
2015 // mark/alive (but not necessarily on the live stack.)
2016 if (IsOnAllocStack(obj)) {
2017 LOG(INFO) << "holder is on the alloc stack.";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002018 } else {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002019 LOG(INFO) << "holder is not marked or on the alloc stack.";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002020 }
2021 }
2022 }
2023 }
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002024 LOG(INFO) << "offset=" << offset.SizeValue();
2025}
2026
2027void ConcurrentCopying::AssertToSpaceInvariantInNonMovingSpace(mirror::Object* obj,
2028 mirror::Object* ref) {
Roland Levillain001eff92018-01-24 14:24:33 +00002029 CHECK(!region_space_->HasAddress(ref)) << "obj=" << obj << " ref=" << ref;
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002030 // In a non-moving spaces. Check that the ref is marked.
Mathieu Chartier763a31e2015-11-16 16:05:55 -08002031 if (immune_spaces_.ContainsObject(ref)) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002032 if (kUseBakerReadBarrier) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002033 // Immune object may not be gray if called from the GC.
2034 if (Thread::Current() == thread_running_gc_ && !gc_grays_immune_objects_) {
2035 return;
2036 }
2037 bool updated_all_immune_objects = updated_all_immune_objects_.LoadSequentiallyConsistent();
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002038 CHECK(updated_all_immune_objects || ref->GetReadBarrierState() == ReadBarrier::GrayState())
2039 << "Unmarked immune space ref. obj=" << obj << " rb_state="
2040 << (obj != nullptr ? obj->GetReadBarrierState() : 0U)
2041 << " ref=" << ref << " ref rb_state=" << ref->GetReadBarrierState()
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002042 << " updated_all_immune_objects=" << updated_all_immune_objects;
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002043 }
2044 } else {
2045 accounting::ContinuousSpaceBitmap* mark_bitmap =
2046 heap_mark_bitmap_->GetContinuousSpaceBitmap(ref);
2047 accounting::LargeObjectBitmap* los_bitmap =
2048 heap_mark_bitmap_->GetLargeObjectBitmap(ref);
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002049 bool is_los = mark_bitmap == nullptr;
2050 if ((!is_los && mark_bitmap->Test(ref)) ||
2051 (is_los && los_bitmap->Test(ref))) {
2052 // OK.
2053 } else {
2054 // If ref is on the allocation stack, then it may not be
2055 // marked live, but considered marked/alive (but not
2056 // necessarily on the live stack).
2057 CHECK(IsOnAllocStack(ref)) << "Unmarked ref that's not on the allocation stack. "
2058 << "obj=" << obj << " ref=" << ref;
2059 }
2060 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002061}
2062
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002063// Used to scan ref fields of an object.
Mathieu Chartiera07f5592016-06-16 11:44:28 -07002064class ConcurrentCopying::RefFieldsVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002065 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07002066 explicit RefFieldsVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002067 : collector_(collector) {}
2068
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07002069 void operator()(mirror::Object* obj, MemberOffset offset, bool /* is_static */)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002070 const ALWAYS_INLINE REQUIRES_SHARED(Locks::mutator_lock_)
2071 REQUIRES_SHARED(Locks::heap_bitmap_lock_) {
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07002072 collector_->Process(obj, offset);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002073 }
2074
Mathieu Chartier31e88222016-10-14 18:43:19 -07002075 void operator()(ObjPtr<mirror::Class> klass, ObjPtr<mirror::Reference> ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002076 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002077 CHECK(klass->IsTypeOfReferenceClass());
2078 collector_->DelayReferenceReferent(klass, ref);
2079 }
2080
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002081 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002082 ALWAYS_INLINE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002083 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002084 if (!root->IsNull()) {
2085 VisitRoot(root);
2086 }
2087 }
2088
2089 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002090 ALWAYS_INLINE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002091 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002092 collector_->MarkRoot</*kGrayImmuneObject*/false>(root);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002093 }
2094
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002095 private:
2096 ConcurrentCopying* const collector_;
2097};
2098
2099// Scan ref fields of an object.
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002100inline void ConcurrentCopying::Scan(mirror::Object* to_ref) {
Hiroshi Yamauchi9b60d502017-02-03 15:09:26 -08002101 if (kDisallowReadBarrierDuringScan && !Runtime::Current()->IsActiveTransaction()) {
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07002102 // Avoid all read barriers during visit references to help performance.
Hiroshi Yamauchi9b60d502017-02-03 15:09:26 -08002103 // Don't do this in transaction mode because we may read the old value of an field which may
2104 // trigger read barriers.
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07002105 Thread::Current()->ModifyDebugDisallowReadBarrier(1);
2106 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002107 DCHECK(!region_space_->IsInFromSpace(to_ref));
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002108 DCHECK_EQ(Thread::Current(), thread_running_gc_);
Mathieu Chartiera07f5592016-06-16 11:44:28 -07002109 RefFieldsVisitor visitor(this);
Hiroshi Yamauchi5496f692016-02-17 13:29:59 -08002110 // Disable the read barrier for a performance reason.
2111 to_ref->VisitReferences</*kVisitNativeRoots*/true, kDefaultVerifyFlags, kWithoutReadBarrier>(
2112 visitor, visitor);
Hiroshi Yamauchi9b60d502017-02-03 15:09:26 -08002113 if (kDisallowReadBarrierDuringScan && !Runtime::Current()->IsActiveTransaction()) {
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07002114 Thread::Current()->ModifyDebugDisallowReadBarrier(-1);
2115 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002116}
2117
2118// Process a field.
2119inline void ConcurrentCopying::Process(mirror::Object* obj, MemberOffset offset) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002120 DCHECK_EQ(Thread::Current(), thread_running_gc_);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002121 mirror::Object* ref = obj->GetFieldObject<
2122 mirror::Object, kVerifyNone, kWithoutReadBarrier, false>(offset);
Mathieu Chartier4ce0c762017-05-18 10:01:07 -07002123 mirror::Object* to_ref = Mark</*kGrayImmuneObject*/false, /*kFromGCThread*/true>(
2124 ref,
2125 /*holder*/ obj,
2126 offset);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002127 if (to_ref == ref) {
2128 return;
2129 }
2130 // This may fail if the mutator writes to the field at the same time. But it's ok.
2131 mirror::Object* expected_ref = ref;
2132 mirror::Object* new_ref = to_ref;
2133 do {
2134 if (expected_ref !=
2135 obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier, false>(offset)) {
2136 // It was updated by the mutator.
2137 break;
2138 }
Mathieu Chartierfdd513d2017-06-01 11:26:50 -07002139 // Use release cas to make sure threads reading the reference see contents of copied objects.
2140 } while (!obj->CasFieldWeakReleaseObjectWithoutWriteBarrier<false, false, kVerifyNone>(
2141 offset,
2142 expected_ref,
2143 new_ref));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002144}
2145
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002146// Process some roots.
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002147inline void ConcurrentCopying::VisitRoots(
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002148 mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED) {
2149 for (size_t i = 0; i < count; ++i) {
2150 mirror::Object** root = roots[i];
2151 mirror::Object* ref = *root;
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002152 mirror::Object* to_ref = Mark(ref);
2153 if (to_ref == ref) {
Mathieu Chartier4809d0a2015-04-07 10:39:04 -07002154 continue;
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002155 }
2156 Atomic<mirror::Object*>* addr = reinterpret_cast<Atomic<mirror::Object*>*>(root);
2157 mirror::Object* expected_ref = ref;
2158 mirror::Object* new_ref = to_ref;
2159 do {
2160 if (expected_ref != addr->LoadRelaxed()) {
2161 // It was updated by the mutator.
2162 break;
2163 }
Orion Hodson4557b382018-01-03 11:47:54 +00002164 } while (!addr->CompareAndSetWeakRelaxed(expected_ref, new_ref));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002165 }
2166}
2167
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002168template<bool kGrayImmuneObject>
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002169inline void ConcurrentCopying::MarkRoot(mirror::CompressedReference<mirror::Object>* root) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002170 DCHECK(!root->IsNull());
2171 mirror::Object* const ref = root->AsMirrorPtr();
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002172 mirror::Object* to_ref = Mark<kGrayImmuneObject>(ref);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002173 if (to_ref != ref) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002174 auto* addr = reinterpret_cast<Atomic<mirror::CompressedReference<mirror::Object>>*>(root);
2175 auto expected_ref = mirror::CompressedReference<mirror::Object>::FromMirrorPtr(ref);
2176 auto new_ref = mirror::CompressedReference<mirror::Object>::FromMirrorPtr(to_ref);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002177 // If the cas fails, then it was updated by the mutator.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002178 do {
2179 if (ref != addr->LoadRelaxed().AsMirrorPtr()) {
2180 // It was updated by the mutator.
2181 break;
2182 }
Orion Hodson4557b382018-01-03 11:47:54 +00002183 } while (!addr->CompareAndSetWeakRelaxed(expected_ref, new_ref));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002184 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002185}
2186
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002187inline void ConcurrentCopying::VisitRoots(
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002188 mirror::CompressedReference<mirror::Object>** roots, size_t count,
2189 const RootInfo& info ATTRIBUTE_UNUSED) {
2190 for (size_t i = 0; i < count; ++i) {
2191 mirror::CompressedReference<mirror::Object>* const root = roots[i];
2192 if (!root->IsNull()) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002193 // kGrayImmuneObject is true because this is used for the thread flip.
2194 MarkRoot</*kGrayImmuneObject*/true>(root);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002195 }
2196 }
2197}
2198
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002199// Temporary set gc_grays_immune_objects_ to true in a scope if the current thread is GC.
2200class ConcurrentCopying::ScopedGcGraysImmuneObjects {
2201 public:
2202 explicit ScopedGcGraysImmuneObjects(ConcurrentCopying* collector)
2203 : collector_(collector), enabled_(false) {
2204 if (kUseBakerReadBarrier &&
2205 collector_->thread_running_gc_ == Thread::Current() &&
2206 !collector_->gc_grays_immune_objects_) {
2207 collector_->gc_grays_immune_objects_ = true;
2208 enabled_ = true;
2209 }
2210 }
2211
2212 ~ScopedGcGraysImmuneObjects() {
2213 if (kUseBakerReadBarrier &&
2214 collector_->thread_running_gc_ == Thread::Current() &&
2215 enabled_) {
2216 DCHECK(collector_->gc_grays_immune_objects_);
2217 collector_->gc_grays_immune_objects_ = false;
2218 }
2219 }
2220
2221 private:
2222 ConcurrentCopying* const collector_;
2223 bool enabled_;
2224};
2225
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002226// Fill the given memory block with a dummy object. Used to fill in a
2227// copy of objects that was lost in race.
2228void ConcurrentCopying::FillWithDummyObject(mirror::Object* dummy_obj, size_t byte_size) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002229 // GC doesn't gray immune objects while scanning immune objects. But we need to trigger the read
2230 // barriers here because we need the updated reference to the int array class, etc. Temporary set
2231 // gc_grays_immune_objects_ to true so that we won't cause a DCHECK failure in MarkImmuneSpace().
2232 ScopedGcGraysImmuneObjects scoped_gc_gray_immune_objects(this);
Roland Levillain14d90572015-07-16 10:52:26 +01002233 CHECK_ALIGNED(byte_size, kObjectAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002234 memset(dummy_obj, 0, byte_size);
Mathieu Chartierd6636d32016-07-28 11:02:38 -07002235 // Avoid going through read barrier for since kDisallowReadBarrierDuringScan may be enabled.
2236 // Explicitly mark to make sure to get an object in the to-space.
2237 mirror::Class* int_array_class = down_cast<mirror::Class*>(
2238 Mark(mirror::IntArray::GetArrayClass<kWithoutReadBarrier>()));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002239 CHECK(int_array_class != nullptr);
Andreas Gampe6c578712017-10-19 13:00:34 -07002240 if (ReadBarrier::kEnableToSpaceInvariantChecks) {
2241 AssertToSpaceInvariant(nullptr, MemberOffset(0), int_array_class);
2242 }
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07002243 size_t component_size = int_array_class->GetComponentSize<kWithoutReadBarrier>();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002244 CHECK_EQ(component_size, sizeof(int32_t));
2245 size_t data_offset = mirror::Array::DataOffset(component_size).SizeValue();
2246 if (data_offset > byte_size) {
2247 // An int array is too big. Use java.lang.Object.
Mathieu Chartier9aef9922017-04-23 13:53:50 -07002248 CHECK(java_lang_Object_ != nullptr);
Andreas Gampe6c578712017-10-19 13:00:34 -07002249 if (ReadBarrier::kEnableToSpaceInvariantChecks) {
2250 AssertToSpaceInvariant(nullptr, MemberOffset(0), java_lang_Object_);
2251 }
Mathieu Chartier3ed8ec12017-04-20 19:28:54 -07002252 CHECK_EQ(byte_size, (java_lang_Object_->GetObjectSize<kVerifyNone, kWithoutReadBarrier>()));
2253 dummy_obj->SetClass(java_lang_Object_);
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07002254 CHECK_EQ(byte_size, (dummy_obj->SizeOf<kVerifyNone>()));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002255 } else {
2256 // Use an int array.
2257 dummy_obj->SetClass(int_array_class);
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07002258 CHECK((dummy_obj->IsArrayInstance<kVerifyNone, kWithoutReadBarrier>()));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002259 int32_t length = (byte_size - data_offset) / component_size;
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07002260 mirror::Array* dummy_arr = dummy_obj->AsArray<kVerifyNone, kWithoutReadBarrier>();
2261 dummy_arr->SetLength(length);
2262 CHECK_EQ(dummy_arr->GetLength(), length)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002263 << "byte_size=" << byte_size << " length=" << length
2264 << " component_size=" << component_size << " data_offset=" << data_offset;
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07002265 CHECK_EQ(byte_size, (dummy_obj->SizeOf<kVerifyNone>()))
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002266 << "byte_size=" << byte_size << " length=" << length
2267 << " component_size=" << component_size << " data_offset=" << data_offset;
2268 }
2269}
2270
2271// Reuse the memory blocks that were copy of objects that were lost in race.
2272mirror::Object* ConcurrentCopying::AllocateInSkippedBlock(size_t alloc_size) {
2273 // Try to reuse the blocks that were unused due to CAS failures.
Roland Levillain14d90572015-07-16 10:52:26 +01002274 CHECK_ALIGNED(alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002275 Thread* self = Thread::Current();
2276 size_t min_object_size = RoundUp(sizeof(mirror::Object), space::RegionSpace::kAlignment);
Mathieu Chartierd6636d32016-07-28 11:02:38 -07002277 size_t byte_size;
2278 uint8_t* addr;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002279 {
Mathieu Chartierd6636d32016-07-28 11:02:38 -07002280 MutexLock mu(self, skipped_blocks_lock_);
2281 auto it = skipped_blocks_map_.lower_bound(alloc_size);
2282 if (it == skipped_blocks_map_.end()) {
2283 // Not found.
2284 return nullptr;
2285 }
2286 byte_size = it->first;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002287 CHECK_GE(byte_size, alloc_size);
2288 if (byte_size > alloc_size && byte_size - alloc_size < min_object_size) {
2289 // If remainder would be too small for a dummy object, retry with a larger request size.
2290 it = skipped_blocks_map_.lower_bound(alloc_size + min_object_size);
2291 if (it == skipped_blocks_map_.end()) {
2292 // Not found.
2293 return nullptr;
2294 }
Roland Levillain14d90572015-07-16 10:52:26 +01002295 CHECK_ALIGNED(it->first - alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002296 CHECK_GE(it->first - alloc_size, min_object_size)
2297 << "byte_size=" << byte_size << " it->first=" << it->first << " alloc_size=" << alloc_size;
2298 }
Mathieu Chartierd6636d32016-07-28 11:02:38 -07002299 // Found a block.
2300 CHECK(it != skipped_blocks_map_.end());
2301 byte_size = it->first;
2302 addr = it->second;
2303 CHECK_GE(byte_size, alloc_size);
2304 CHECK(region_space_->IsInToSpace(reinterpret_cast<mirror::Object*>(addr)));
2305 CHECK_ALIGNED(byte_size, space::RegionSpace::kAlignment);
2306 if (kVerboseMode) {
2307 LOG(INFO) << "Reusing skipped bytes : " << reinterpret_cast<void*>(addr) << ", " << byte_size;
2308 }
2309 skipped_blocks_map_.erase(it);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002310 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002311 memset(addr, 0, byte_size);
2312 if (byte_size > alloc_size) {
2313 // Return the remainder to the map.
Roland Levillain14d90572015-07-16 10:52:26 +01002314 CHECK_ALIGNED(byte_size - alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002315 CHECK_GE(byte_size - alloc_size, min_object_size);
Mathieu Chartierd6636d32016-07-28 11:02:38 -07002316 // FillWithDummyObject may mark an object, avoid holding skipped_blocks_lock_ to prevent lock
2317 // violation and possible deadlock. The deadlock case is a recursive case:
2318 // FillWithDummyObject -> IntArray::GetArrayClass -> Mark -> Copy -> AllocateInSkippedBlock.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002319 FillWithDummyObject(reinterpret_cast<mirror::Object*>(addr + alloc_size),
2320 byte_size - alloc_size);
2321 CHECK(region_space_->IsInToSpace(reinterpret_cast<mirror::Object*>(addr + alloc_size)));
Mathieu Chartierd6636d32016-07-28 11:02:38 -07002322 {
2323 MutexLock mu(self, skipped_blocks_lock_);
2324 skipped_blocks_map_.insert(std::make_pair(byte_size - alloc_size, addr + alloc_size));
2325 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002326 }
2327 return reinterpret_cast<mirror::Object*>(addr);
2328}
2329
Mathieu Chartieref496d92017-04-28 18:58:59 -07002330mirror::Object* ConcurrentCopying::Copy(mirror::Object* from_ref,
2331 mirror::Object* holder,
2332 MemberOffset offset) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002333 DCHECK(region_space_->IsInFromSpace(from_ref));
Mathieu Chartieref496d92017-04-28 18:58:59 -07002334 // If the class pointer is null, the object is invalid. This could occur for a dangling pointer
2335 // from a previous GC that is either inside or outside the allocated region.
2336 mirror::Class* klass = from_ref->GetClass<kVerifyNone, kWithoutReadBarrier>();
2337 if (UNLIKELY(klass == nullptr)) {
2338 heap_->GetVerification()->LogHeapCorruption(holder, offset, from_ref, /* fatal */ true);
2339 }
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07002340 // There must not be a read barrier to avoid nested RB that might violate the to-space invariant.
2341 // Note that from_ref is a from space ref so the SizeOf() call will access the from-space meta
2342 // objects, but it's ok and necessary.
2343 size_t obj_size = from_ref->SizeOf<kDefaultVerifyFlags>();
Nicolas Geoffray4b361a82017-07-06 15:30:10 +01002344 size_t region_space_alloc_size = (obj_size <= space::RegionSpace::kRegionSize)
2345 ? RoundUp(obj_size, space::RegionSpace::kAlignment)
2346 : RoundUp(obj_size, space::RegionSpace::kRegionSize);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002347 size_t region_space_bytes_allocated = 0U;
2348 size_t non_moving_space_bytes_allocated = 0U;
2349 size_t bytes_allocated = 0U;
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07002350 size_t dummy;
Lokesh Gidrab4f15412018-01-05 18:29:34 -08002351 mirror::Object* to_ref = region_space_->AllocNonvirtual</*kForEvac*/ true>(
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07002352 region_space_alloc_size, &region_space_bytes_allocated, nullptr, &dummy);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002353 bytes_allocated = region_space_bytes_allocated;
2354 if (to_ref != nullptr) {
2355 DCHECK_EQ(region_space_alloc_size, region_space_bytes_allocated);
2356 }
2357 bool fall_back_to_non_moving = false;
2358 if (UNLIKELY(to_ref == nullptr)) {
2359 // Failed to allocate in the region space. Try the skipped blocks.
2360 to_ref = AllocateInSkippedBlock(region_space_alloc_size);
2361 if (to_ref != nullptr) {
2362 // Succeeded to allocate in a skipped block.
2363 if (heap_->use_tlab_) {
2364 // This is necessary for the tlab case as it's not accounted in the space.
2365 region_space_->RecordAlloc(to_ref);
2366 }
2367 bytes_allocated = region_space_alloc_size;
2368 } else {
2369 // Fall back to the non-moving space.
2370 fall_back_to_non_moving = true;
2371 if (kVerboseMode) {
2372 LOG(INFO) << "Out of memory in the to-space. Fall back to non-moving. skipped_bytes="
2373 << to_space_bytes_skipped_.LoadSequentiallyConsistent()
2374 << " skipped_objects=" << to_space_objects_skipped_.LoadSequentiallyConsistent();
2375 }
2376 fall_back_to_non_moving = true;
2377 to_ref = heap_->non_moving_space_->Alloc(Thread::Current(), obj_size,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07002378 &non_moving_space_bytes_allocated, nullptr, &dummy);
Mathieu Chartierb01335c2017-03-22 13:15:01 -07002379 if (UNLIKELY(to_ref == nullptr)) {
2380 LOG(FATAL_WITHOUT_ABORT) << "Fall-back non-moving space allocation failed for a "
2381 << obj_size << " byte object in region type "
2382 << region_space_->GetRegionType(from_ref);
2383 LOG(FATAL) << "Object address=" << from_ref << " type=" << from_ref->PrettyTypeOf();
2384 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002385 bytes_allocated = non_moving_space_bytes_allocated;
2386 // Mark it in the mark bitmap.
2387 accounting::ContinuousSpaceBitmap* mark_bitmap =
2388 heap_mark_bitmap_->GetContinuousSpaceBitmap(to_ref);
2389 CHECK(mark_bitmap != nullptr);
2390 CHECK(!mark_bitmap->AtomicTestAndSet(to_ref));
2391 }
2392 }
2393 DCHECK(to_ref != nullptr);
2394
Mathieu Chartierd818adb2016-09-15 13:12:47 -07002395 // Copy the object excluding the lock word since that is handled in the loop.
Mathieu Chartieref496d92017-04-28 18:58:59 -07002396 to_ref->SetClass(klass);
Mathieu Chartierd818adb2016-09-15 13:12:47 -07002397 const size_t kObjectHeaderSize = sizeof(mirror::Object);
2398 DCHECK_GE(obj_size, kObjectHeaderSize);
2399 static_assert(kObjectHeaderSize == sizeof(mirror::HeapReference<mirror::Class>) +
2400 sizeof(LockWord),
2401 "Object header size does not match");
2402 // Memcpy can tear for words since it may do byte copy. It is only safe to do this since the
2403 // object in the from space is immutable other than the lock word. b/31423258
2404 memcpy(reinterpret_cast<uint8_t*>(to_ref) + kObjectHeaderSize,
2405 reinterpret_cast<const uint8_t*>(from_ref) + kObjectHeaderSize,
2406 obj_size - kObjectHeaderSize);
2407
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002408 // Attempt to install the forward pointer. This is in a loop as the
2409 // lock word atomic write can fail.
2410 while (true) {
Mathieu Chartierd818adb2016-09-15 13:12:47 -07002411 LockWord old_lock_word = from_ref->GetLockWord(false);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002412
2413 if (old_lock_word.GetState() == LockWord::kForwardingAddress) {
2414 // Lost the race. Another thread (either GC or mutator) stored
2415 // the forwarding pointer first. Make the lost copy (to_ref)
2416 // look like a valid but dead (dummy) object and keep it for
2417 // future reuse.
2418 FillWithDummyObject(to_ref, bytes_allocated);
2419 if (!fall_back_to_non_moving) {
2420 DCHECK(region_space_->IsInToSpace(to_ref));
2421 if (bytes_allocated > space::RegionSpace::kRegionSize) {
2422 // Free the large alloc.
Lokesh Gidrab4f15412018-01-05 18:29:34 -08002423 region_space_->FreeLarge</*kForEvac*/ true>(to_ref, bytes_allocated);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002424 } else {
2425 // Record the lost copy for later reuse.
2426 heap_->num_bytes_allocated_.FetchAndAddSequentiallyConsistent(bytes_allocated);
2427 to_space_bytes_skipped_.FetchAndAddSequentiallyConsistent(bytes_allocated);
2428 to_space_objects_skipped_.FetchAndAddSequentiallyConsistent(1);
2429 MutexLock mu(Thread::Current(), skipped_blocks_lock_);
2430 skipped_blocks_map_.insert(std::make_pair(bytes_allocated,
2431 reinterpret_cast<uint8_t*>(to_ref)));
2432 }
2433 } else {
2434 DCHECK(heap_->non_moving_space_->HasAddress(to_ref));
2435 DCHECK_EQ(bytes_allocated, non_moving_space_bytes_allocated);
2436 // Free the non-moving-space chunk.
2437 accounting::ContinuousSpaceBitmap* mark_bitmap =
2438 heap_mark_bitmap_->GetContinuousSpaceBitmap(to_ref);
2439 CHECK(mark_bitmap != nullptr);
2440 CHECK(mark_bitmap->Clear(to_ref));
2441 heap_->non_moving_space_->Free(Thread::Current(), to_ref);
2442 }
2443
2444 // Get the winner's forward ptr.
2445 mirror::Object* lost_fwd_ptr = to_ref;
2446 to_ref = reinterpret_cast<mirror::Object*>(old_lock_word.ForwardingAddress());
2447 CHECK(to_ref != nullptr);
2448 CHECK_NE(to_ref, lost_fwd_ptr);
Mathieu Chartierdfcd6f42016-09-13 10:02:48 -07002449 CHECK(region_space_->IsInToSpace(to_ref) || heap_->non_moving_space_->HasAddress(to_ref))
2450 << "to_ref=" << to_ref << " " << heap_->DumpSpaces();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002451 CHECK_NE(to_ref->GetLockWord(false).GetState(), LockWord::kForwardingAddress);
2452 return to_ref;
2453 }
2454
Mathieu Chartierd818adb2016-09-15 13:12:47 -07002455 // Copy the old lock word over since we did not copy it yet.
2456 to_ref->SetLockWord(old_lock_word, false);
Hiroshi Yamauchi60f63f52015-04-23 16:12:40 -07002457 // Set the gray ptr.
2458 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002459 to_ref->SetReadBarrierState(ReadBarrier::GrayState());
Hiroshi Yamauchi60f63f52015-04-23 16:12:40 -07002460 }
2461
Mathieu Chartiera8131262016-11-29 17:55:19 -08002462 // Do a fence to prevent the field CAS in ConcurrentCopying::Process from possibly reordering
2463 // before the object copy.
2464 QuasiAtomic::ThreadFenceRelease();
2465
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002466 LockWord new_lock_word = LockWord::FromForwardingAddress(reinterpret_cast<size_t>(to_ref));
2467
2468 // Try to atomically write the fwd ptr.
Mathieu Chartiera8131262016-11-29 17:55:19 -08002469 bool success = from_ref->CasLockWordWeakRelaxed(old_lock_word, new_lock_word);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002470 if (LIKELY(success)) {
2471 // The CAS succeeded.
Mathieu Chartiera8131262016-11-29 17:55:19 -08002472 objects_moved_.FetchAndAddRelaxed(1);
2473 bytes_moved_.FetchAndAddRelaxed(region_space_alloc_size);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002474 if (LIKELY(!fall_back_to_non_moving)) {
2475 DCHECK(region_space_->IsInToSpace(to_ref));
2476 } else {
2477 DCHECK(heap_->non_moving_space_->HasAddress(to_ref));
2478 DCHECK_EQ(bytes_allocated, non_moving_space_bytes_allocated);
2479 }
2480 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002481 DCHECK(to_ref->GetReadBarrierState() == ReadBarrier::GrayState());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002482 }
2483 DCHECK(GetFwdPtr(from_ref) == to_ref);
2484 CHECK_NE(to_ref->GetLockWord(false).GetState(), LockWord::kForwardingAddress);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002485 PushOntoMarkStack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002486 return to_ref;
2487 } else {
2488 // The CAS failed. It may have lost the race or may have failed
2489 // due to monitor/hashcode ops. Either way, retry.
2490 }
2491 }
2492}
2493
2494mirror::Object* ConcurrentCopying::IsMarked(mirror::Object* from_ref) {
2495 DCHECK(from_ref != nullptr);
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08002496 space::RegionSpace::RegionType rtype = region_space_->GetRegionType(from_ref);
2497 if (rtype == space::RegionSpace::RegionType::kRegionTypeToSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002498 // It's already marked.
2499 return from_ref;
2500 }
2501 mirror::Object* to_ref;
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08002502 if (rtype == space::RegionSpace::RegionType::kRegionTypeFromSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002503 to_ref = GetFwdPtr(from_ref);
2504 DCHECK(to_ref == nullptr || region_space_->IsInToSpace(to_ref) ||
2505 heap_->non_moving_space_->HasAddress(to_ref))
2506 << "from_ref=" << from_ref << " to_ref=" << to_ref;
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08002507 } else if (rtype == space::RegionSpace::RegionType::kRegionTypeUnevacFromSpace) {
Mathieu Chartierc381c362016-08-23 13:27:53 -07002508 if (IsMarkedInUnevacFromSpace(from_ref)) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002509 to_ref = from_ref;
2510 } else {
2511 to_ref = nullptr;
2512 }
2513 } else {
Roland Levillain001eff92018-01-24 14:24:33 +00002514 // At this point, `from_ref` should not be in the region space
2515 // (i.e. within an "unused" region).
2516 DCHECK(!region_space_->HasAddress(from_ref)) << from_ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002517 // from_ref is in a non-moving space.
Mathieu Chartier763a31e2015-11-16 16:05:55 -08002518 if (immune_spaces_.ContainsObject(from_ref)) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002519 // An immune object is alive.
2520 to_ref = from_ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002521 } else {
2522 // Non-immune non-moving space. Use the mark bitmap.
2523 accounting::ContinuousSpaceBitmap* mark_bitmap =
2524 heap_mark_bitmap_->GetContinuousSpaceBitmap(from_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002525 bool is_los = mark_bitmap == nullptr;
2526 if (!is_los && mark_bitmap->Test(from_ref)) {
2527 // Already marked.
2528 to_ref = from_ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002529 } else {
Mathieu Chartier47863bb2017-08-04 11:30:27 -07002530 accounting::LargeObjectBitmap* los_bitmap =
2531 heap_mark_bitmap_->GetLargeObjectBitmap(from_ref);
2532 // We may not have a large object space for dex2oat, don't assume it exists.
2533 if (los_bitmap == nullptr) {
2534 CHECK(heap_->GetLargeObjectsSpace() == nullptr)
2535 << "LOS bitmap covers the entire address range " << from_ref
2536 << " " << heap_->DumpSpaces();
2537 }
2538 if (los_bitmap != nullptr && is_los && los_bitmap->Test(from_ref)) {
2539 // Already marked in LOS.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002540 to_ref = from_ref;
2541 } else {
2542 // Not marked.
Mathieu Chartier47863bb2017-08-04 11:30:27 -07002543 if (IsOnAllocStack(from_ref)) {
2544 // If on the allocation stack, it's considered marked.
2545 to_ref = from_ref;
2546 } else {
2547 // Not marked.
2548 to_ref = nullptr;
2549 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002550 }
2551 }
2552 }
2553 }
2554 return to_ref;
2555}
2556
2557bool ConcurrentCopying::IsOnAllocStack(mirror::Object* ref) {
Hans Boehmcc55e1d2017-07-27 15:28:07 -07002558 // TODO: Explain why this is here. What release operation does it pair with?
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002559 QuasiAtomic::ThreadFenceAcquire();
2560 accounting::ObjectStack* alloc_stack = GetAllocationStack();
Mathieu Chartiercb535da2015-01-23 13:50:03 -08002561 return alloc_stack->Contains(ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002562}
2563
Mathieu Chartier1ca68902017-04-18 11:26:22 -07002564mirror::Object* ConcurrentCopying::MarkNonMoving(mirror::Object* ref,
2565 mirror::Object* holder,
2566 MemberOffset offset) {
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002567 // ref is in a non-moving space (from_ref == to_ref).
2568 DCHECK(!region_space_->HasAddress(ref)) << ref;
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002569 DCHECK(!immune_spaces_.ContainsObject(ref));
2570 // Use the mark bitmap.
2571 accounting::ContinuousSpaceBitmap* mark_bitmap =
2572 heap_mark_bitmap_->GetContinuousSpaceBitmap(ref);
2573 accounting::LargeObjectBitmap* los_bitmap =
2574 heap_mark_bitmap_->GetLargeObjectBitmap(ref);
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002575 bool is_los = mark_bitmap == nullptr;
2576 if (!is_los && mark_bitmap->Test(ref)) {
2577 // Already marked.
2578 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002579 DCHECK(ref->GetReadBarrierState() == ReadBarrier::GrayState() ||
2580 ref->GetReadBarrierState() == ReadBarrier::WhiteState());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002581 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002582 } else if (is_los && los_bitmap->Test(ref)) {
2583 // Already marked in LOS.
2584 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002585 DCHECK(ref->GetReadBarrierState() == ReadBarrier::GrayState() ||
2586 ref->GetReadBarrierState() == ReadBarrier::WhiteState());
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002587 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002588 } else {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002589 // Not marked.
2590 if (IsOnAllocStack(ref)) {
2591 // If it's on the allocation stack, it's considered marked. Keep it white.
2592 // Objects on the allocation stack need not be marked.
2593 if (!is_los) {
2594 DCHECK(!mark_bitmap->Test(ref));
2595 } else {
2596 DCHECK(!los_bitmap->Test(ref));
Nicolas Geoffrayddeb1722016-06-28 08:25:59 +00002597 }
Nicolas Geoffrayddeb1722016-06-28 08:25:59 +00002598 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002599 DCHECK_EQ(ref->GetReadBarrierState(), ReadBarrier::WhiteState());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002600 }
2601 } else {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002602 // For the baker-style RB, we need to handle 'false-gray' cases. See the
2603 // kRegionTypeUnevacFromSpace-case comment in Mark().
2604 if (kUseBakerReadBarrier) {
2605 // Test the bitmap first to reduce the chance of false gray cases.
2606 if ((!is_los && mark_bitmap->Test(ref)) ||
2607 (is_los && los_bitmap->Test(ref))) {
2608 return ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002609 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002610 }
Mathieu Chartier1ca68902017-04-18 11:26:22 -07002611 if (is_los && !IsAligned<kPageSize>(ref)) {
2612 // Ref is a large object that is not aligned, it must be heap corruption. Dump data before
2613 // AtomicSetReadBarrierState since it will fault if the address is not valid.
Mathieu Chartieref496d92017-04-28 18:58:59 -07002614 heap_->GetVerification()->LogHeapCorruption(holder, offset, ref, /* fatal */ true);
Mathieu Chartier1ca68902017-04-18 11:26:22 -07002615 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002616 // Not marked or on the allocation stack. Try to mark it.
2617 // This may or may not succeed, which is ok.
2618 bool cas_success = false;
2619 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002620 cas_success = ref->AtomicSetReadBarrierState(ReadBarrier::WhiteState(),
2621 ReadBarrier::GrayState());
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002622 }
2623 if (!is_los && mark_bitmap->AtomicTestAndSet(ref)) {
2624 // Already marked.
2625 if (kUseBakerReadBarrier && cas_success &&
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002626 ref->GetReadBarrierState() == ReadBarrier::GrayState()) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002627 PushOntoFalseGrayStack(ref);
2628 }
2629 } else if (is_los && los_bitmap->AtomicTestAndSet(ref)) {
2630 // Already marked in LOS.
2631 if (kUseBakerReadBarrier && cas_success &&
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002632 ref->GetReadBarrierState() == ReadBarrier::GrayState()) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002633 PushOntoFalseGrayStack(ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002634 }
2635 } else {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002636 // Newly marked.
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08002637 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002638 DCHECK_EQ(ref->GetReadBarrierState(), ReadBarrier::GrayState());
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08002639 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002640 PushOntoMarkStack(ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002641 }
2642 }
2643 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002644 return ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002645}
2646
2647void ConcurrentCopying::FinishPhase() {
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -08002648 Thread* const self = Thread::Current();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002649 {
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -08002650 MutexLock mu(self, mark_stack_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002651 CHECK_EQ(pooled_mark_stacks_.size(), kMarkStackPoolSize);
2652 }
Mathieu Chartiera1467d02017-02-22 09:22:50 -08002653 // kVerifyNoMissingCardMarks relies on the region space cards not being cleared to avoid false
2654 // positives.
2655 if (!kVerifyNoMissingCardMarks) {
Mathieu Chartier6e6078a2016-10-24 15:45:41 -07002656 TimingLogger::ScopedTiming split("ClearRegionSpaceCards", GetTimings());
2657 // We do not currently use the region space cards at all, madvise them away to save ram.
2658 heap_->GetCardTable()->ClearCardRange(region_space_->Begin(), region_space_->Limit());
Mathieu Chartier6e6078a2016-10-24 15:45:41 -07002659 }
2660 {
2661 MutexLock mu(self, skipped_blocks_lock_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002662 skipped_blocks_map_.clear();
2663 }
Mathieu Chartier56fe2582016-07-14 13:30:03 -07002664 {
2665 ReaderMutexLock mu(self, *Locks::mutator_lock_);
Mathieu Chartier21328a12016-07-22 10:47:45 -07002666 {
2667 WriterMutexLock mu2(self, *Locks::heap_bitmap_lock_);
2668 heap_->ClearMarkedObjects();
2669 }
2670 if (kUseBakerReadBarrier && kFilterModUnionCards) {
2671 TimingLogger::ScopedTiming split("FilterModUnionCards", GetTimings());
2672 ReaderMutexLock mu2(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier21328a12016-07-22 10:47:45 -07002673 for (space::ContinuousSpace* space : immune_spaces_.GetSpaces()) {
2674 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
Mathieu Chartier6e6078a2016-10-24 15:45:41 -07002675 accounting::ModUnionTable* table = heap_->FindModUnionTableFromSpace(space);
Mathieu Chartier21328a12016-07-22 10:47:45 -07002676 // Filter out cards that don't need to be set.
2677 if (table != nullptr) {
2678 table->FilterCards();
2679 }
2680 }
2681 }
Mathieu Chartier36a270a2016-07-28 18:08:51 -07002682 if (kUseBakerReadBarrier) {
2683 TimingLogger::ScopedTiming split("EmptyRBMarkBitStack", GetTimings());
Mathieu Chartier6e6078a2016-10-24 15:45:41 -07002684 DCHECK(rb_mark_bit_stack_ != nullptr);
Mathieu Chartier36a270a2016-07-28 18:08:51 -07002685 const auto* limit = rb_mark_bit_stack_->End();
2686 for (StackReference<mirror::Object>* it = rb_mark_bit_stack_->Begin(); it != limit; ++it) {
Roland Levillain001eff92018-01-24 14:24:33 +00002687 CHECK(it->AsMirrorPtr()->AtomicSetMarkBit(1, 0))
2688 << "rb_mark_bit_stack_->Begin()" << rb_mark_bit_stack_->Begin() << '\n'
2689 << "rb_mark_bit_stack_->End()" << rb_mark_bit_stack_->End() << '\n'
2690 << "rb_mark_bit_stack_->IsFull()"
2691 << std::boolalpha << rb_mark_bit_stack_->IsFull() << std::noboolalpha << '\n'
2692 << DumpReferenceInfo(it->AsMirrorPtr(), "*it");
Mathieu Chartier36a270a2016-07-28 18:08:51 -07002693 }
2694 rb_mark_bit_stack_->Reset();
2695 }
Mathieu Chartier56fe2582016-07-14 13:30:03 -07002696 }
2697 if (measure_read_barrier_slow_path_) {
2698 MutexLock mu(self, rb_slow_path_histogram_lock_);
2699 rb_slow_path_time_histogram_.AdjustAndAddValue(rb_slow_path_ns_.LoadRelaxed());
2700 rb_slow_path_count_total_ += rb_slow_path_count_.LoadRelaxed();
2701 rb_slow_path_count_gc_total_ += rb_slow_path_count_gc_.LoadRelaxed();
2702 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002703}
2704
Hiroshi Yamauchi65f5f242016-12-19 11:44:47 -08002705bool ConcurrentCopying::IsNullOrMarkedHeapReference(mirror::HeapReference<mirror::Object>* field,
2706 bool do_atomic_update) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002707 mirror::Object* from_ref = field->AsMirrorPtr();
Hiroshi Yamauchi65f5f242016-12-19 11:44:47 -08002708 if (from_ref == nullptr) {
2709 return true;
2710 }
Mathieu Chartier97509952015-07-13 14:35:43 -07002711 mirror::Object* to_ref = IsMarked(from_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002712 if (to_ref == nullptr) {
2713 return false;
2714 }
2715 if (from_ref != to_ref) {
Hiroshi Yamauchi65f5f242016-12-19 11:44:47 -08002716 if (do_atomic_update) {
2717 do {
2718 if (field->AsMirrorPtr() != from_ref) {
2719 // Concurrently overwritten by a mutator.
2720 break;
2721 }
2722 } while (!field->CasWeakRelaxed(from_ref, to_ref));
2723 } else {
Hans Boehmcc55e1d2017-07-27 15:28:07 -07002724 // TODO: Why is this seq_cst when the above is relaxed? Document memory ordering.
2725 field->Assign</* kIsVolatile */ true>(to_ref);
Hiroshi Yamauchi65f5f242016-12-19 11:44:47 -08002726 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002727 }
2728 return true;
2729}
2730
Mathieu Chartier97509952015-07-13 14:35:43 -07002731mirror::Object* ConcurrentCopying::MarkObject(mirror::Object* from_ref) {
2732 return Mark(from_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002733}
2734
Mathieu Chartier31e88222016-10-14 18:43:19 -07002735void ConcurrentCopying::DelayReferenceReferent(ObjPtr<mirror::Class> klass,
2736 ObjPtr<mirror::Reference> reference) {
Mathieu Chartier97509952015-07-13 14:35:43 -07002737 heap_->GetReferenceProcessor()->DelayReferenceReferent(klass, reference, this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002738}
2739
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002740void ConcurrentCopying::ProcessReferences(Thread* self) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002741 TimingLogger::ScopedTiming split("ProcessReferences", GetTimings());
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002742 // 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 -08002743 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
2744 GetHeap()->GetReferenceProcessor()->ProcessReferences(
Mathieu Chartier97509952015-07-13 14:35:43 -07002745 true /*concurrent*/, GetTimings(), GetCurrentIteration()->GetClearSoftReferences(), this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002746}
2747
2748void ConcurrentCopying::RevokeAllThreadLocalBuffers() {
2749 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
2750 region_space_->RevokeAllThreadLocalBuffers();
2751}
2752
Mathieu Chartier56fe2582016-07-14 13:30:03 -07002753mirror::Object* ConcurrentCopying::MarkFromReadBarrierWithMeasurements(mirror::Object* from_ref) {
2754 if (Thread::Current() != thread_running_gc_) {
2755 rb_slow_path_count_.FetchAndAddRelaxed(1u);
2756 } else {
2757 rb_slow_path_count_gc_.FetchAndAddRelaxed(1u);
2758 }
2759 ScopedTrace tr(__FUNCTION__);
2760 const uint64_t start_time = measure_read_barrier_slow_path_ ? NanoTime() : 0u;
2761 mirror::Object* ret = Mark(from_ref);
2762 if (measure_read_barrier_slow_path_) {
2763 rb_slow_path_ns_.FetchAndAddRelaxed(NanoTime() - start_time);
2764 }
2765 return ret;
2766}
2767
2768void ConcurrentCopying::DumpPerformanceInfo(std::ostream& os) {
2769 GarbageCollector::DumpPerformanceInfo(os);
2770 MutexLock mu(Thread::Current(), rb_slow_path_histogram_lock_);
2771 if (rb_slow_path_time_histogram_.SampleSize() > 0) {
2772 Histogram<uint64_t>::CumulativeData cumulative_data;
2773 rb_slow_path_time_histogram_.CreateHistogram(&cumulative_data);
2774 rb_slow_path_time_histogram_.PrintConfidenceIntervals(os, 0.99, cumulative_data);
2775 }
2776 if (rb_slow_path_count_total_ > 0) {
2777 os << "Slow path count " << rb_slow_path_count_total_ << "\n";
2778 }
2779 if (rb_slow_path_count_gc_total_ > 0) {
2780 os << "GC slow path count " << rb_slow_path_count_gc_total_ << "\n";
2781 }
Mathieu Chartiercca44a02016-08-17 10:07:29 -07002782 os << "Cumulative bytes moved " << cumulative_bytes_moved_.LoadRelaxed() << "\n";
2783 os << "Cumulative objects moved " << cumulative_objects_moved_.LoadRelaxed() << "\n";
Lokesh Gidra29895822017-12-15 15:37:40 -08002784
2785 os << "Peak regions allocated "
Lokesh Gidrab4f15412018-01-05 18:29:34 -08002786 << region_space_->GetMaxPeakNumNonFreeRegions() << " ("
2787 << PrettySize(region_space_->GetMaxPeakNumNonFreeRegions() * space::RegionSpace::kRegionSize)
2788 << ") / " << region_space_->GetNumRegions() / 2 << " ("
2789 << PrettySize(region_space_->GetNumRegions() * space::RegionSpace::kRegionSize / 2)
Lokesh Gidra29895822017-12-15 15:37:40 -08002790 << ")\n";
Mathieu Chartier56fe2582016-07-14 13:30:03 -07002791}
2792
Hiroshi Yamauchid5307ec2014-03-27 21:07:51 -07002793} // namespace collector
2794} // namespace gc
2795} // namespace art