blob: a68227e0ebbb2a53219b53ef8ab9058b61a2bbd9 [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 ||
Richard Uhlerda1da8a2017-05-16 13:37:32 +0000303 gc_cause == kGcCauseForNativeAllocBlocking ||
Hiroshi Yamauchi60985b72016-08-24 13:53:12 -0700304 gc_cause == kGcCauseCollectorTransition ||
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800305 GetCurrentIteration()->GetClearSoftReferences()) {
306 force_evacuate_all_ = true;
307 } else {
308 force_evacuate_all_ = false;
309 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700310 if (kUseBakerReadBarrier) {
311 updated_all_immune_objects_.StoreRelaxed(false);
312 // GC may gray immune objects in the thread flip.
313 gc_grays_immune_objects_ = true;
314 if (kIsDebugBuild) {
315 MutexLock mu(Thread::Current(), immune_gray_stack_lock_);
316 DCHECK(immune_gray_stack_.empty());
317 }
318 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800319 BindBitmaps();
320 if (kVerboseMode) {
321 LOG(INFO) << "force_evacuate_all=" << force_evacuate_all_;
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800322 LOG(INFO) << "Largest immune region: " << immune_spaces_.GetLargestImmuneRegion().Begin()
323 << "-" << immune_spaces_.GetLargestImmuneRegion().End();
324 for (space::ContinuousSpace* space : immune_spaces_.GetSpaces()) {
325 LOG(INFO) << "Immune space: " << *space;
326 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800327 LOG(INFO) << "GC end of InitializePhase";
328 }
Mathieu Chartier962cd7a2016-08-16 12:15:59 -0700329 // Mark all of the zygote large objects without graying them.
330 MarkZygoteLargeObjects();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800331}
332
333// Used to switch the thread roots of a thread from from-space refs to to-space refs.
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700334class ConcurrentCopying::ThreadFlipVisitor : public Closure, public RootVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800335 public:
Roland Levillain3887c462015-08-12 18:15:42 +0100336 ThreadFlipVisitor(ConcurrentCopying* concurrent_copying, bool use_tlab)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800337 : concurrent_copying_(concurrent_copying), use_tlab_(use_tlab) {
338 }
339
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700340 virtual void Run(Thread* thread) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800341 // Note: self is not necessarily equal to thread since thread may be suspended.
342 Thread* self = Thread::Current();
343 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
344 << thread->GetState() << " thread " << thread << " self " << self;
Mathieu Chartierfe814e82016-11-09 14:32:49 -0800345 thread->SetIsGcMarkingAndUpdateEntrypoints(true);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800346 if (use_tlab_ && thread->HasTlab()) {
347 if (ConcurrentCopying::kEnableFromSpaceAccountingCheck) {
348 // This must come before the revoke.
349 size_t thread_local_objects = thread->GetThreadLocalObjectsAllocated();
350 concurrent_copying_->region_space_->RevokeThreadLocalBuffers(thread);
351 reinterpret_cast<Atomic<size_t>*>(&concurrent_copying_->from_space_num_objects_at_first_pause_)->
352 FetchAndAddSequentiallyConsistent(thread_local_objects);
353 } else {
354 concurrent_copying_->region_space_->RevokeThreadLocalBuffers(thread);
355 }
356 }
357 if (kUseThreadLocalAllocationStack) {
358 thread->RevokeThreadLocalAllocationStack();
359 }
360 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700361 // We can use the non-CAS VisitRoots functions below because we update thread-local GC roots
362 // only.
Andreas Gampe513061a2017-06-01 09:17:34 -0700363 thread->VisitRoots(this, kVisitRootFlagAllRoots);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800364 concurrent_copying_->GetBarrier().Pass(self);
365 }
366
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700367 void VisitRoots(mirror::Object*** roots,
368 size_t count,
369 const RootInfo& info ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700370 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700371 for (size_t i = 0; i < count; ++i) {
372 mirror::Object** root = roots[i];
373 mirror::Object* ref = *root;
374 if (ref != nullptr) {
375 mirror::Object* to_ref = concurrent_copying_->Mark(ref);
376 if (to_ref != ref) {
377 *root = to_ref;
378 }
379 }
380 }
381 }
382
383 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots,
384 size_t count,
385 const RootInfo& info ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700386 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700387 for (size_t i = 0; i < count; ++i) {
388 mirror::CompressedReference<mirror::Object>* const root = roots[i];
389 if (!root->IsNull()) {
390 mirror::Object* ref = root->AsMirrorPtr();
391 mirror::Object* to_ref = concurrent_copying_->Mark(ref);
392 if (to_ref != ref) {
393 root->Assign(to_ref);
394 }
395 }
396 }
397 }
398
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800399 private:
400 ConcurrentCopying* const concurrent_copying_;
401 const bool use_tlab_;
402};
403
404// Called back from Runtime::FlipThreadRoots() during a pause.
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700405class ConcurrentCopying::FlipCallback : public Closure {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800406 public:
407 explicit FlipCallback(ConcurrentCopying* concurrent_copying)
408 : concurrent_copying_(concurrent_copying) {
409 }
410
Mathieu Chartier90443472015-07-16 20:32:27 -0700411 virtual void Run(Thread* thread) OVERRIDE REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800412 ConcurrentCopying* cc = concurrent_copying_;
413 TimingLogger::ScopedTiming split("(Paused)FlipCallback", cc->GetTimings());
414 // Note: self is not necessarily equal to thread since thread may be suspended.
415 Thread* self = Thread::Current();
Mathieu Chartiera1467d02017-02-22 09:22:50 -0800416 if (kVerifyNoMissingCardMarks) {
417 cc->VerifyNoMissingCardMarks();
418 }
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700419 CHECK_EQ(thread, self);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800420 Locks::mutator_lock_->AssertExclusiveHeld(self);
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700421 {
422 TimingLogger::ScopedTiming split2("(Paused)SetFromSpace", cc->GetTimings());
423 cc->region_space_->SetFromSpace(cc->rb_table_, cc->force_evacuate_all_);
424 }
Mathieu Chartiera4f6af92015-08-11 17:35:25 -0700425 cc->SwapStacks();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800426 if (ConcurrentCopying::kEnableFromSpaceAccountingCheck) {
427 cc->RecordLiveStackFreezeSize(self);
428 cc->from_space_num_objects_at_first_pause_ = cc->region_space_->GetObjectsAllocated();
429 cc->from_space_num_bytes_at_first_pause_ = cc->region_space_->GetBytesAllocated();
430 }
431 cc->is_marking_ = true;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700432 cc->mark_stack_mode_.StoreRelaxed(ConcurrentCopying::kMarkStackModeThreadLocal);
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800433 if (kIsDebugBuild) {
434 cc->region_space_->AssertAllRegionLiveBytesZeroOrCleared();
435 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800436 if (UNLIKELY(Runtime::Current()->IsActiveTransaction())) {
Mathieu Chartier184c9dc2015-03-05 13:20:54 -0800437 CHECK(Runtime::Current()->IsAotCompiler());
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700438 TimingLogger::ScopedTiming split3("(Paused)VisitTransactionRoots", cc->GetTimings());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700439 Runtime::Current()->VisitTransactionRoots(cc);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800440 }
Mathieu Chartier21328a12016-07-22 10:47:45 -0700441 if (kUseBakerReadBarrier && kGrayDirtyImmuneObjects) {
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700442 cc->GrayAllNewlyDirtyImmuneObjects();
Mathieu Chartier21328a12016-07-22 10:47:45 -0700443 if (kIsDebugBuild) {
444 // Check that all non-gray immune objects only refernce immune objects.
445 cc->VerifyGrayImmuneObjects();
446 }
447 }
Mathieu Chartier9aef9922017-04-23 13:53:50 -0700448 // May be null during runtime creation, in this case leave java_lang_Object null.
449 // This is safe since single threaded behavior should mean FillDummyObject does not
450 // happen when java_lang_Object_ is null.
451 if (WellKnownClasses::java_lang_Object != nullptr) {
452 cc->java_lang_Object_ = down_cast<mirror::Class*>(cc->Mark(
453 WellKnownClasses::ToClass(WellKnownClasses::java_lang_Object).Ptr()));
454 } else {
455 cc->java_lang_Object_ = nullptr;
456 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800457 }
458
459 private:
460 ConcurrentCopying* const concurrent_copying_;
461};
462
Mathieu Chartier21328a12016-07-22 10:47:45 -0700463class ConcurrentCopying::VerifyGrayImmuneObjectsVisitor {
464 public:
465 explicit VerifyGrayImmuneObjectsVisitor(ConcurrentCopying* collector)
466 : collector_(collector) {}
467
Mathieu Chartier31e88222016-10-14 18:43:19 -0700468 void operator()(ObjPtr<mirror::Object> obj, MemberOffset offset, bool /* is_static */)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700469 const ALWAYS_INLINE REQUIRES_SHARED(Locks::mutator_lock_)
470 REQUIRES_SHARED(Locks::heap_bitmap_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700471 CheckReference(obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(offset),
472 obj, offset);
473 }
474
Mathieu Chartier31e88222016-10-14 18:43:19 -0700475 void operator()(ObjPtr<mirror::Class> klass, ObjPtr<mirror::Reference> ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700476 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700477 CHECK(klass->IsTypeOfReferenceClass());
478 CheckReference(ref->GetReferent<kWithoutReadBarrier>(),
479 ref,
480 mirror::Reference::ReferentOffset());
481 }
482
483 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
484 ALWAYS_INLINE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700485 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700486 if (!root->IsNull()) {
487 VisitRoot(root);
488 }
489 }
490
491 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
492 ALWAYS_INLINE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700493 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700494 CheckReference(root->AsMirrorPtr(), nullptr, MemberOffset(0));
495 }
496
497 private:
498 ConcurrentCopying* const collector_;
499
Mathieu Chartier31e88222016-10-14 18:43:19 -0700500 void CheckReference(ObjPtr<mirror::Object> ref,
501 ObjPtr<mirror::Object> holder,
502 MemberOffset offset) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700503 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700504 if (ref != nullptr) {
Mathieu Chartier31e88222016-10-14 18:43:19 -0700505 if (!collector_->immune_spaces_.ContainsObject(ref.Ptr())) {
Mathieu Chartier962cd7a2016-08-16 12:15:59 -0700506 // Not immune, must be a zygote large object.
507 CHECK(Runtime::Current()->GetHeap()->GetLargeObjectsSpace()->IsZygoteLargeObject(
Mathieu Chartier31e88222016-10-14 18:43:19 -0700508 Thread::Current(), ref.Ptr()))
Mathieu Chartier962cd7a2016-08-16 12:15:59 -0700509 << "Non gray object references non immune, non zygote large object "<< ref << " "
David Sehr709b0702016-10-13 09:12:37 -0700510 << mirror::Object::PrettyTypeOf(ref) << " in holder " << holder << " "
511 << mirror::Object::PrettyTypeOf(holder) << " offset=" << offset.Uint32Value();
Mathieu Chartier962cd7a2016-08-16 12:15:59 -0700512 } else {
513 // Make sure the large object class is immune since we will never scan the large object.
514 CHECK(collector_->immune_spaces_.ContainsObject(
515 ref->GetClass<kVerifyNone, kWithoutReadBarrier>()));
516 }
Mathieu Chartier21328a12016-07-22 10:47:45 -0700517 }
518 }
519};
520
521void ConcurrentCopying::VerifyGrayImmuneObjects() {
522 TimingLogger::ScopedTiming split(__FUNCTION__, GetTimings());
523 for (auto& space : immune_spaces_.GetSpaces()) {
524 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
525 accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
526 VerifyGrayImmuneObjectsVisitor visitor(this);
527 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()),
528 reinterpret_cast<uintptr_t>(space->Limit()),
529 [&visitor](mirror::Object* obj)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700530 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700531 // If an object is not gray, it should only have references to things in the immune spaces.
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700532 if (obj->GetReadBarrierState() != ReadBarrier::GrayState()) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700533 obj->VisitReferences</*kVisitNativeRoots*/true,
534 kDefaultVerifyFlags,
535 kWithoutReadBarrier>(visitor, visitor);
536 }
537 });
538 }
539}
540
Mathieu Chartiera1467d02017-02-22 09:22:50 -0800541class ConcurrentCopying::VerifyNoMissingCardMarkVisitor {
542 public:
543 VerifyNoMissingCardMarkVisitor(ConcurrentCopying* cc, ObjPtr<mirror::Object> holder)
544 : cc_(cc),
545 holder_(holder) {}
546
547 void operator()(ObjPtr<mirror::Object> obj,
548 MemberOffset offset,
549 bool is_static ATTRIBUTE_UNUSED) const
550 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
551 if (offset.Uint32Value() != mirror::Object::ClassOffset().Uint32Value()) {
552 CheckReference(obj->GetFieldObject<mirror::Object, kDefaultVerifyFlags, kWithoutReadBarrier>(
553 offset), offset.Uint32Value());
554 }
555 }
556 void operator()(ObjPtr<mirror::Class> klass,
557 ObjPtr<mirror::Reference> ref) const
558 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
559 CHECK(klass->IsTypeOfReferenceClass());
560 this->operator()(ref, mirror::Reference::ReferentOffset(), false);
561 }
562
563 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
564 REQUIRES_SHARED(Locks::mutator_lock_) {
565 if (!root->IsNull()) {
566 VisitRoot(root);
567 }
568 }
569
570 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
571 REQUIRES_SHARED(Locks::mutator_lock_) {
572 CheckReference(root->AsMirrorPtr());
573 }
574
575 void CheckReference(mirror::Object* ref, int32_t offset = -1) const
576 REQUIRES_SHARED(Locks::mutator_lock_) {
577 CHECK(ref == nullptr || !cc_->region_space_->IsInNewlyAllocatedRegion(ref))
578 << holder_->PrettyTypeOf() << "(" << holder_.Ptr() << ") references object "
579 << ref->PrettyTypeOf() << "(" << ref << ") in newly allocated region at offset=" << offset;
580 }
581
582 private:
583 ConcurrentCopying* const cc_;
584 ObjPtr<mirror::Object> const holder_;
585};
586
Mathieu Chartiera1467d02017-02-22 09:22:50 -0800587void ConcurrentCopying::VerifyNoMissingCardMarks() {
Andreas Gampe0c183382017-07-13 22:26:24 -0700588 auto visitor = [&](mirror::Object* obj)
589 REQUIRES(Locks::mutator_lock_)
590 REQUIRES(!mark_stack_lock_) {
591 // Objects not on dirty or aged cards should never have references to newly allocated regions.
592 if (heap_->GetCardTable()->GetCard(obj) == gc::accounting::CardTable::kCardClean) {
593 VerifyNoMissingCardMarkVisitor internal_visitor(this, /*holder*/ obj);
594 obj->VisitReferences</*kVisitNativeRoots*/true, kVerifyNone, kWithoutReadBarrier>(
595 internal_visitor, internal_visitor);
596 }
597 };
Mathieu Chartiera1467d02017-02-22 09:22:50 -0800598 TimingLogger::ScopedTiming split(__FUNCTION__, GetTimings());
Andreas Gampe0c183382017-07-13 22:26:24 -0700599 region_space_->Walk(visitor);
Mathieu Chartiera1467d02017-02-22 09:22:50 -0800600 {
601 ReaderMutexLock rmu(Thread::Current(), *Locks::heap_bitmap_lock_);
Andreas Gampe0c183382017-07-13 22:26:24 -0700602 heap_->GetLiveBitmap()->Visit(visitor);
Mathieu Chartiera1467d02017-02-22 09:22:50 -0800603 }
604}
605
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800606// Switch threads that from from-space to to-space refs. Forward/mark the thread roots.
607void ConcurrentCopying::FlipThreadRoots() {
608 TimingLogger::ScopedTiming split("FlipThreadRoots", GetTimings());
609 if (kVerboseMode) {
610 LOG(INFO) << "time=" << region_space_->Time();
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700611 region_space_->DumpNonFreeRegions(LOG_STREAM(INFO));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800612 }
613 Thread* self = Thread::Current();
614 Locks::mutator_lock_->AssertNotHeld(self);
615 gc_barrier_->Init(self, 0);
616 ThreadFlipVisitor thread_flip_visitor(this, heap_->use_tlab_);
617 FlipCallback flip_callback(this);
Andreas Gampe4934eb12017-01-30 13:15:26 -0800618
Andreas Gampe6e644452017-05-09 16:30:27 -0700619 size_t barrier_count = Runtime::Current()->GetThreadList()->FlipThreadRoots(
620 &thread_flip_visitor, &flip_callback, this, GetHeap()->GetGcPauseListener());
Andreas Gampe4934eb12017-01-30 13:15:26 -0800621
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800622 {
623 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
624 gc_barrier_->Increment(self, barrier_count);
625 }
626 is_asserting_to_space_invariant_ = true;
627 QuasiAtomic::ThreadFenceForConstructor();
628 if (kVerboseMode) {
629 LOG(INFO) << "time=" << region_space_->Time();
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700630 region_space_->DumpNonFreeRegions(LOG_STREAM(INFO));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800631 LOG(INFO) << "GC end of FlipThreadRoots";
632 }
633}
634
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700635template <bool kConcurrent>
Mathieu Chartier21328a12016-07-22 10:47:45 -0700636class ConcurrentCopying::GrayImmuneObjectVisitor {
637 public:
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700638 explicit GrayImmuneObjectVisitor(Thread* self) : self_(self) {}
Mathieu Chartier21328a12016-07-22 10:47:45 -0700639
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700640 ALWAYS_INLINE void operator()(mirror::Object* obj) const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700641 if (kUseBakerReadBarrier && obj->GetReadBarrierState() == ReadBarrier::WhiteState()) {
642 if (kConcurrent) {
643 Locks::mutator_lock_->AssertSharedHeld(self_);
644 obj->AtomicSetReadBarrierState(ReadBarrier::WhiteState(), ReadBarrier::GrayState());
645 // Mod union table VisitObjects may visit the same object multiple times so we can't check
646 // the result of the atomic set.
647 } else {
648 Locks::mutator_lock_->AssertExclusiveHeld(self_);
649 obj->SetReadBarrierState(ReadBarrier::GrayState());
Mathieu Chartier21328a12016-07-22 10:47:45 -0700650 }
Mathieu Chartier21328a12016-07-22 10:47:45 -0700651 }
652 }
653
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700654 static void Callback(mirror::Object* obj, void* arg) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700655 reinterpret_cast<GrayImmuneObjectVisitor<kConcurrent>*>(arg)->operator()(obj);
Mathieu Chartier21328a12016-07-22 10:47:45 -0700656 }
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700657
658 private:
659 Thread* const self_;
Mathieu Chartier21328a12016-07-22 10:47:45 -0700660};
661
662void ConcurrentCopying::GrayAllDirtyImmuneObjects() {
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700663 TimingLogger::ScopedTiming split("GrayAllDirtyImmuneObjects", GetTimings());
664 accounting::CardTable* const card_table = heap_->GetCardTable();
665 Thread* const self = Thread::Current();
666 using VisitorType = GrayImmuneObjectVisitor</* kIsConcurrent */ true>;
667 VisitorType visitor(self);
668 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier21328a12016-07-22 10:47:45 -0700669 for (space::ContinuousSpace* space : immune_spaces_.GetSpaces()) {
670 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700671 accounting::ModUnionTable* table = heap_->FindModUnionTableFromSpace(space);
Mathieu Chartier21328a12016-07-22 10:47:45 -0700672 // Mark all the objects on dirty cards since these may point to objects in other space.
673 // Once these are marked, the GC will eventually clear them later.
674 // Table is non null for boot image and zygote spaces. It is only null for application image
675 // spaces.
676 if (table != nullptr) {
Mathieu Chartier6e6078a2016-10-24 15:45:41 -0700677 table->ProcessCards();
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700678 table->VisitObjects(&VisitorType::Callback, &visitor);
679 // Don't clear cards here since we need to rescan in the pause. If we cleared the cards here,
680 // there would be races with the mutator marking new cards.
681 } else {
682 // Keep cards aged if we don't have a mod-union table since we may need to scan them in future
683 // GCs. This case is for app images.
684 card_table->ModifyCardsAtomic(
685 space->Begin(),
686 space->End(),
687 [](uint8_t card) {
688 return (card != gc::accounting::CardTable::kCardClean)
689 ? gc::accounting::CardTable::kCardAged
690 : card;
691 },
692 /* card modified visitor */ VoidFunctor());
693 card_table->Scan</* kClearCard */ false>(space->GetMarkBitmap(),
694 space->Begin(),
695 space->End(),
696 visitor,
697 gc::accounting::CardTable::kCardAged);
698 }
699 }
700}
701
702void ConcurrentCopying::GrayAllNewlyDirtyImmuneObjects() {
703 TimingLogger::ScopedTiming split("(Paused)GrayAllNewlyDirtyImmuneObjects", GetTimings());
704 accounting::CardTable* const card_table = heap_->GetCardTable();
705 using VisitorType = GrayImmuneObjectVisitor</* kIsConcurrent */ false>;
706 Thread* const self = Thread::Current();
707 VisitorType visitor(self);
708 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
709 for (space::ContinuousSpace* space : immune_spaces_.GetSpaces()) {
710 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
711 accounting::ModUnionTable* table = heap_->FindModUnionTableFromSpace(space);
712
713 // Don't need to scan aged cards since we did these before the pause. Note that scanning cards
714 // also handles the mod-union table cards.
715 card_table->Scan</* kClearCard */ false>(space->GetMarkBitmap(),
716 space->Begin(),
717 space->End(),
718 visitor,
719 gc::accounting::CardTable::kCardDirty);
720 if (table != nullptr) {
721 // Add the cards to the mod-union table so that we can clear cards to save RAM.
722 table->ProcessCards();
Mathieu Chartier6e6078a2016-10-24 15:45:41 -0700723 TimingLogger::ScopedTiming split2("(Paused)ClearCards", GetTimings());
724 card_table->ClearCardRange(space->Begin(),
725 AlignDown(space->End(), accounting::CardTable::kCardSize));
Mathieu Chartier21328a12016-07-22 10:47:45 -0700726 }
727 }
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700728 // 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 -0700729 // barriers in the immune spaces.
730 updated_all_immune_objects_.StoreRelaxed(true);
731}
732
Mathieu Chartiera4f6af92015-08-11 17:35:25 -0700733void ConcurrentCopying::SwapStacks() {
734 heap_->SwapStacks();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800735}
736
737void ConcurrentCopying::RecordLiveStackFreezeSize(Thread* self) {
738 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
739 live_stack_freeze_size_ = heap_->GetLiveStack()->Size();
740}
741
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700742// Used to visit objects in the immune spaces.
743inline void ConcurrentCopying::ScanImmuneObject(mirror::Object* obj) {
744 DCHECK(obj != nullptr);
745 DCHECK(immune_spaces_.ContainsObject(obj));
746 // Update the fields without graying it or pushing it onto the mark stack.
747 Scan(obj);
748}
749
750class ConcurrentCopying::ImmuneSpaceScanObjVisitor {
751 public:
752 explicit ImmuneSpaceScanObjVisitor(ConcurrentCopying* cc)
753 : collector_(cc) {}
754
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700755 ALWAYS_INLINE void operator()(mirror::Object* obj) const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700756 if (kUseBakerReadBarrier && kGrayDirtyImmuneObjects) {
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700757 // Only need to scan gray objects.
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700758 if (obj->GetReadBarrierState() == ReadBarrier::GrayState()) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700759 collector_->ScanImmuneObject(obj);
760 // Done scanning the object, go back to white.
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700761 bool success = obj->AtomicSetReadBarrierState(ReadBarrier::GrayState(),
762 ReadBarrier::WhiteState());
Mathieu Chartier2af7a3e2017-12-14 18:36:05 -0800763 CHECK(success)
764 << Runtime::Current()->GetHeap()->GetVerification()->DumpObjectInfo(obj, "failed CAS");
Mathieu Chartier21328a12016-07-22 10:47:45 -0700765 }
766 } else {
767 collector_->ScanImmuneObject(obj);
768 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700769 }
770
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700771 static void Callback(mirror::Object* obj, void* arg) REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi5408f232016-07-29 15:07:05 -0700772 reinterpret_cast<ImmuneSpaceScanObjVisitor*>(arg)->operator()(obj);
773 }
774
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700775 private:
776 ConcurrentCopying* const collector_;
777};
778
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800779// Concurrently mark roots that are guarded by read barriers and process the mark stack.
780void ConcurrentCopying::MarkingPhase() {
781 TimingLogger::ScopedTiming split("MarkingPhase", GetTimings());
782 if (kVerboseMode) {
783 LOG(INFO) << "GC MarkingPhase";
784 }
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -0700785 Thread* self = Thread::Current();
786 if (kIsDebugBuild) {
787 MutexLock mu(self, *Locks::thread_list_lock_);
788 CHECK(weak_ref_access_enabled_);
789 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700790
791 // Scan immune spaces.
792 // Update all the fields in the immune spaces first without graying the objects so that we
793 // minimize dirty pages in the immune spaces. Note mutators can concurrently access and gray some
794 // of the objects.
795 if (kUseBakerReadBarrier) {
796 gc_grays_immune_objects_ = false;
Hiroshi Yamauchi16292fc2016-06-20 20:23:34 -0700797 }
Mathieu Chartier21328a12016-07-22 10:47:45 -0700798 {
799 TimingLogger::ScopedTiming split2("ScanImmuneSpaces", GetTimings());
800 for (auto& space : immune_spaces_.GetSpaces()) {
801 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
802 accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
Hiroshi Yamauchi5408f232016-07-29 15:07:05 -0700803 accounting::ModUnionTable* table = heap_->FindModUnionTableFromSpace(space);
Mathieu Chartier21328a12016-07-22 10:47:45 -0700804 ImmuneSpaceScanObjVisitor visitor(this);
Hiroshi Yamauchi5408f232016-07-29 15:07:05 -0700805 if (kUseBakerReadBarrier && kGrayDirtyImmuneObjects && table != nullptr) {
806 table->VisitObjects(ImmuneSpaceScanObjVisitor::Callback, &visitor);
807 } else {
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700808 // TODO: Scan only the aged cards.
Hiroshi Yamauchi5408f232016-07-29 15:07:05 -0700809 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()),
810 reinterpret_cast<uintptr_t>(space->Limit()),
811 visitor);
812 }
Mathieu Chartier21328a12016-07-22 10:47:45 -0700813 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700814 }
815 if (kUseBakerReadBarrier) {
816 // This release fence makes the field updates in the above loop visible before allowing mutator
817 // getting access to immune objects without graying it first.
818 updated_all_immune_objects_.StoreRelease(true);
819 // Now whiten immune objects concurrently accessed and grayed by mutators. We can't do this in
820 // the above loop because we would incorrectly disable the read barrier by whitening an object
821 // which may point to an unscanned, white object, breaking the to-space invariant.
822 //
823 // Make sure no mutators are in the middle of marking an immune object before whitening immune
824 // objects.
825 IssueEmptyCheckpoint();
826 MutexLock mu(Thread::Current(), immune_gray_stack_lock_);
827 if (kVerboseMode) {
828 LOG(INFO) << "immune gray stack size=" << immune_gray_stack_.size();
829 }
830 for (mirror::Object* obj : immune_gray_stack_) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700831 DCHECK(obj->GetReadBarrierState() == ReadBarrier::GrayState());
832 bool success = obj->AtomicSetReadBarrierState(ReadBarrier::GrayState(),
833 ReadBarrier::WhiteState());
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700834 DCHECK(success);
835 }
836 immune_gray_stack_.clear();
837 }
838
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800839 {
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -0700840 TimingLogger::ScopedTiming split2("VisitConcurrentRoots", GetTimings());
841 Runtime::Current()->VisitConcurrentRoots(this, kVisitRootFlagAllRoots);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800842 }
843 {
844 // TODO: don't visit the transaction roots if it's not active.
845 TimingLogger::ScopedTiming split5("VisitNonThreadRoots", GetTimings());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700846 Runtime::Current()->VisitNonThreadRoots(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800847 }
848
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800849 {
Mathieu Chartiera6b1ead2015-10-06 10:32:38 -0700850 TimingLogger::ScopedTiming split7("ProcessMarkStack", GetTimings());
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700851 // We transition through three mark stack modes (thread-local, shared, GC-exclusive). The
852 // primary reasons are the fact that we need to use a checkpoint to process thread-local mark
853 // stacks, but after we disable weak refs accesses, we can't use a checkpoint due to a deadlock
854 // issue because running threads potentially blocking at WaitHoldingLocks, and that once we
855 // reach the point where we process weak references, we can avoid using a lock when accessing
856 // the GC mark stack, which makes mark stack processing more efficient.
857
858 // Process the mark stack once in the thread local stack mode. This marks most of the live
859 // objects, aside from weak ref accesses with read barriers (Reference::GetReferent() and system
860 // weaks) that may happen concurrently while we processing the mark stack and newly mark/gray
861 // objects and push refs on the mark stack.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800862 ProcessMarkStack();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700863 // Switch to the shared mark stack mode. That is, revoke and process thread-local mark stacks
864 // for the last time before transitioning to the shared mark stack mode, which would process new
865 // refs that may have been concurrently pushed onto the mark stack during the ProcessMarkStack()
866 // call above. At the same time, disable weak ref accesses using a per-thread flag. It's
867 // important to do these together in a single checkpoint so that we can ensure that mutators
868 // won't newly gray objects and push new refs onto the mark stack due to weak ref accesses and
869 // mutators safely transition to the shared mark stack mode (without leaving unprocessed refs on
870 // the thread-local mark stacks), without a race. This is why we use a thread-local weak ref
871 // access flag Thread::tls32_.weak_ref_access_enabled_ instead of the global ones.
872 SwitchToSharedMarkStackMode();
873 CHECK(!self->GetWeakRefAccessEnabled());
874 // Now that weak refs accesses are disabled, once we exhaust the shared mark stack again here
875 // (which may be non-empty if there were refs found on thread-local mark stacks during the above
876 // SwitchToSharedMarkStackMode() call), we won't have new refs to process, that is, mutators
877 // (via read barriers) have no way to produce any more refs to process. Marking converges once
878 // before we process weak refs below.
879 ProcessMarkStack();
880 CheckEmptyMarkStack();
881 // Switch to the GC exclusive mark stack mode so that we can process the mark stack without a
882 // lock from this point on.
883 SwitchToGcExclusiveMarkStackMode();
884 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800885 if (kVerboseMode) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800886 LOG(INFO) << "ProcessReferences";
887 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700888 // Process weak references. This may produce new refs to process and have them processed via
Mathieu Chartier97509952015-07-13 14:35:43 -0700889 // ProcessMarkStack (in the GC exclusive mark stack mode).
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700890 ProcessReferences(self);
891 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800892 if (kVerboseMode) {
893 LOG(INFO) << "SweepSystemWeaks";
894 }
895 SweepSystemWeaks(self);
896 if (kVerboseMode) {
897 LOG(INFO) << "SweepSystemWeaks done";
898 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700899 // Process the mark stack here one last time because the above SweepSystemWeaks() call may have
900 // marked some objects (strings alive) as hash_set::Erase() can call the hash function for
901 // arbitrary elements in the weak intern table in InternTable::Table::SweepWeaks().
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800902 ProcessMarkStack();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700903 CheckEmptyMarkStack();
904 // Re-enable weak ref accesses.
905 ReenableWeakRefAccess(self);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -0700906 // Free data for class loaders that we unloaded.
907 Runtime::Current()->GetClassLinker()->CleanupClassLoaders();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700908 // Marking is done. Disable marking.
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700909 DisableMarking();
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800910 if (kUseBakerReadBarrier) {
911 ProcessFalseGrayStack();
912 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700913 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800914 }
915
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -0700916 if (kIsDebugBuild) {
917 MutexLock mu(self, *Locks::thread_list_lock_);
918 CHECK(weak_ref_access_enabled_);
919 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800920 if (kVerboseMode) {
921 LOG(INFO) << "GC end of MarkingPhase";
922 }
923}
924
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700925void ConcurrentCopying::ReenableWeakRefAccess(Thread* self) {
926 if (kVerboseMode) {
927 LOG(INFO) << "ReenableWeakRefAccess";
928 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700929 // Iterate all threads (don't need to or can't use a checkpoint) and re-enable weak ref access.
930 {
931 MutexLock mu(self, *Locks::thread_list_lock_);
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -0700932 weak_ref_access_enabled_ = true; // This is for new threads.
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700933 std::list<Thread*> thread_list = Runtime::Current()->GetThreadList()->GetList();
934 for (Thread* thread : thread_list) {
935 thread->SetWeakRefAccessEnabled(true);
936 }
937 }
938 // Unblock blocking threads.
939 GetHeap()->GetReferenceProcessor()->BroadcastForSlowPath(self);
940 Runtime::Current()->BroadcastForNewSystemWeaks();
941}
942
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700943class ConcurrentCopying::DisableMarkingCheckpoint : public Closure {
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700944 public:
945 explicit DisableMarkingCheckpoint(ConcurrentCopying* concurrent_copying)
946 : concurrent_copying_(concurrent_copying) {
947 }
948
949 void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
950 // Note: self is not necessarily equal to thread since thread may be suspended.
951 Thread* self = Thread::Current();
952 DCHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
953 << thread->GetState() << " thread " << thread << " self " << self;
954 // Disable the thread-local is_gc_marking flag.
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -0700955 // Note a thread that has just started right before this checkpoint may have already this flag
956 // set to false, which is ok.
Mathieu Chartierfe814e82016-11-09 14:32:49 -0800957 thread->SetIsGcMarkingAndUpdateEntrypoints(false);
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700958 // If thread is a running mutator, then act on behalf of the garbage collector.
959 // See the code in ThreadList::RunCheckpoint.
Mathieu Chartier10d25082015-10-28 18:36:09 -0700960 concurrent_copying_->GetBarrier().Pass(self);
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700961 }
962
963 private:
964 ConcurrentCopying* const concurrent_copying_;
965};
966
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -0700967class ConcurrentCopying::DisableMarkingCallback : public Closure {
968 public:
969 explicit DisableMarkingCallback(ConcurrentCopying* concurrent_copying)
970 : concurrent_copying_(concurrent_copying) {
971 }
972
973 void Run(Thread* self ATTRIBUTE_UNUSED) OVERRIDE REQUIRES(Locks::thread_list_lock_) {
974 // This needs to run under the thread_list_lock_ critical section in ThreadList::RunCheckpoint()
975 // to avoid a race with ThreadList::Register().
976 CHECK(concurrent_copying_->is_marking_);
977 concurrent_copying_->is_marking_ = false;
Mathieu Chartiera9a4f5f2017-05-03 18:19:13 -0700978 if (kUseBakerReadBarrier && kGrayDirtyImmuneObjects) {
979 CHECK(concurrent_copying_->is_using_read_barrier_entrypoints_);
980 concurrent_copying_->is_using_read_barrier_entrypoints_ = false;
981 } else {
982 CHECK(!concurrent_copying_->is_using_read_barrier_entrypoints_);
983 }
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -0700984 }
985
986 private:
987 ConcurrentCopying* const concurrent_copying_;
988};
989
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700990void ConcurrentCopying::IssueDisableMarkingCheckpoint() {
991 Thread* self = Thread::Current();
992 DisableMarkingCheckpoint check_point(this);
993 ThreadList* thread_list = Runtime::Current()->GetThreadList();
994 gc_barrier_->Init(self, 0);
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -0700995 DisableMarkingCallback dmc(this);
996 size_t barrier_count = thread_list->RunCheckpoint(&check_point, &dmc);
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700997 // If there are no threads to wait which implies that all the checkpoint functions are finished,
998 // then no need to release the mutator lock.
999 if (barrier_count == 0) {
1000 return;
1001 }
1002 // Release locks then wait for all mutator threads to pass the barrier.
1003 Locks::mutator_lock_->SharedUnlock(self);
1004 {
1005 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
1006 gc_barrier_->Increment(self, barrier_count);
1007 }
1008 Locks::mutator_lock_->SharedLock(self);
1009}
1010
1011void ConcurrentCopying::DisableMarking() {
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001012 // Use a checkpoint to turn off the global is_marking and the thread-local is_gc_marking flags and
1013 // to ensure no threads are still in the middle of a read barrier which may have a from-space ref
1014 // cached in a local variable.
Hiroshi Yamauchi00370822015-08-18 14:47:25 -07001015 IssueDisableMarkingCheckpoint();
1016 if (kUseTableLookupReadBarrier) {
1017 heap_->rb_table_->ClearAll();
1018 DCHECK(heap_->rb_table_->IsAllCleared());
1019 }
1020 is_mark_stack_push_disallowed_.StoreSequentiallyConsistent(1);
1021 mark_stack_mode_.StoreSequentiallyConsistent(kMarkStackModeOff);
1022}
1023
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001024void ConcurrentCopying::PushOntoFalseGrayStack(mirror::Object* ref) {
1025 CHECK(kUseBakerReadBarrier);
1026 DCHECK(ref != nullptr);
1027 MutexLock mu(Thread::Current(), mark_stack_lock_);
1028 false_gray_stack_.push_back(ref);
1029}
1030
1031void ConcurrentCopying::ProcessFalseGrayStack() {
1032 CHECK(kUseBakerReadBarrier);
1033 // Change the objects on the false gray stack from gray to white.
1034 MutexLock mu(Thread::Current(), mark_stack_lock_);
1035 for (mirror::Object* obj : false_gray_stack_) {
1036 DCHECK(IsMarked(obj));
1037 // The object could be white here if a thread got preempted after a success at the
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001038 // AtomicSetReadBarrierState in Mark(), GC started marking through it (but not finished so
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001039 // still gray), and the thread ran to register it onto the false gray stack.
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001040 if (obj->GetReadBarrierState() == ReadBarrier::GrayState()) {
1041 bool success = obj->AtomicSetReadBarrierState(ReadBarrier::GrayState(),
1042 ReadBarrier::WhiteState());
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001043 DCHECK(success);
1044 }
1045 }
1046 false_gray_stack_.clear();
1047}
1048
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001049void ConcurrentCopying::IssueEmptyCheckpoint() {
1050 Thread* self = Thread::Current();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001051 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001052 // Release locks then wait for all mutator threads to pass the barrier.
1053 Locks::mutator_lock_->SharedUnlock(self);
Hiroshi Yamauchia2224042017-02-08 16:35:45 -08001054 thread_list->RunEmptyCheckpoint();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001055 Locks::mutator_lock_->SharedLock(self);
1056}
1057
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -07001058void ConcurrentCopying::ExpandGcMarkStack() {
1059 DCHECK(gc_mark_stack_->IsFull());
1060 const size_t new_size = gc_mark_stack_->Capacity() * 2;
1061 std::vector<StackReference<mirror::Object>> temp(gc_mark_stack_->Begin(),
1062 gc_mark_stack_->End());
1063 gc_mark_stack_->Resize(new_size);
1064 for (auto& ref : temp) {
1065 gc_mark_stack_->PushBack(ref.AsMirrorPtr());
1066 }
1067 DCHECK(!gc_mark_stack_->IsFull());
1068}
1069
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001070void ConcurrentCopying::PushOntoMarkStack(mirror::Object* to_ref) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001071 CHECK_EQ(is_mark_stack_push_disallowed_.LoadRelaxed(), 0)
David Sehr709b0702016-10-13 09:12:37 -07001072 << " " << to_ref << " " << mirror::Object::PrettyTypeOf(to_ref);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001073 Thread* self = Thread::Current(); // TODO: pass self as an argument from call sites?
1074 CHECK(thread_running_gc_ != nullptr);
1075 MarkStackMode mark_stack_mode = mark_stack_mode_.LoadRelaxed();
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001076 if (LIKELY(mark_stack_mode == kMarkStackModeThreadLocal)) {
1077 if (LIKELY(self == thread_running_gc_)) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001078 // If GC-running thread, use the GC mark stack instead of a thread-local mark stack.
1079 CHECK(self->GetThreadLocalMarkStack() == nullptr);
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -07001080 if (UNLIKELY(gc_mark_stack_->IsFull())) {
1081 ExpandGcMarkStack();
1082 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001083 gc_mark_stack_->PushBack(to_ref);
1084 } else {
1085 // Otherwise, use a thread-local mark stack.
1086 accounting::AtomicStack<mirror::Object>* tl_mark_stack = self->GetThreadLocalMarkStack();
1087 if (UNLIKELY(tl_mark_stack == nullptr || tl_mark_stack->IsFull())) {
1088 MutexLock mu(self, mark_stack_lock_);
1089 // Get a new thread local mark stack.
1090 accounting::AtomicStack<mirror::Object>* new_tl_mark_stack;
1091 if (!pooled_mark_stacks_.empty()) {
1092 // Use a pooled mark stack.
1093 new_tl_mark_stack = pooled_mark_stacks_.back();
1094 pooled_mark_stacks_.pop_back();
1095 } else {
1096 // None pooled. Create a new one.
1097 new_tl_mark_stack =
1098 accounting::AtomicStack<mirror::Object>::Create(
1099 "thread local mark stack", 4 * KB, 4 * KB);
1100 }
1101 DCHECK(new_tl_mark_stack != nullptr);
1102 DCHECK(new_tl_mark_stack->IsEmpty());
1103 new_tl_mark_stack->PushBack(to_ref);
1104 self->SetThreadLocalMarkStack(new_tl_mark_stack);
1105 if (tl_mark_stack != nullptr) {
1106 // Store the old full stack into a vector.
1107 revoked_mark_stacks_.push_back(tl_mark_stack);
1108 }
1109 } else {
1110 tl_mark_stack->PushBack(to_ref);
1111 }
1112 }
1113 } else if (mark_stack_mode == kMarkStackModeShared) {
1114 // Access the shared GC mark stack with a lock.
1115 MutexLock mu(self, mark_stack_lock_);
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -07001116 if (UNLIKELY(gc_mark_stack_->IsFull())) {
1117 ExpandGcMarkStack();
1118 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001119 gc_mark_stack_->PushBack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001120 } else {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001121 CHECK_EQ(static_cast<uint32_t>(mark_stack_mode),
Hiroshi Yamauchifa755182015-09-30 20:12:11 -07001122 static_cast<uint32_t>(kMarkStackModeGcExclusive))
1123 << "ref=" << to_ref
1124 << " self->gc_marking=" << self->GetIsGcMarking()
1125 << " cc->is_marking=" << is_marking_;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001126 CHECK(self == thread_running_gc_)
1127 << "Only GC-running thread should access the mark stack "
1128 << "in the GC exclusive mark stack mode";
1129 // Access the GC mark stack without a lock.
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -07001130 if (UNLIKELY(gc_mark_stack_->IsFull())) {
1131 ExpandGcMarkStack();
1132 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001133 gc_mark_stack_->PushBack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001134 }
1135}
1136
1137accounting::ObjectStack* ConcurrentCopying::GetAllocationStack() {
1138 return heap_->allocation_stack_.get();
1139}
1140
1141accounting::ObjectStack* ConcurrentCopying::GetLiveStack() {
1142 return heap_->live_stack_.get();
1143}
1144
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001145// The following visitors are used to verify that there's no references to the from-space left after
1146// marking.
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001147class ConcurrentCopying::VerifyNoFromSpaceRefsVisitor : public SingleRootVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001148 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001149 explicit VerifyNoFromSpaceRefsVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001150 : collector_(collector) {}
1151
Mathieu Chartierbc632f02017-04-20 13:31:39 -07001152 void operator()(mirror::Object* ref,
1153 MemberOffset offset = MemberOffset(0),
1154 mirror::Object* holder = nullptr) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001155 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001156 if (ref == nullptr) {
1157 // OK.
1158 return;
1159 }
Mathieu Chartierbc632f02017-04-20 13:31:39 -07001160 collector_->AssertToSpaceInvariant(holder, offset, ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001161 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001162 CHECK_EQ(ref->GetReadBarrierState(), ReadBarrier::WhiteState())
David Sehr709b0702016-10-13 09:12:37 -07001163 << "Ref " << ref << " " << ref->PrettyTypeOf()
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001164 << " has non-white rb_state ";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001165 }
1166 }
1167
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001168 void VisitRoot(mirror::Object* root, const RootInfo& info ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001169 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001170 DCHECK(root != nullptr);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001171 operator()(root);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001172 }
1173
1174 private:
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001175 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001176};
1177
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001178class ConcurrentCopying::VerifyNoFromSpaceRefsFieldVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001179 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001180 explicit VerifyNoFromSpaceRefsFieldVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001181 : collector_(collector) {}
1182
Mathieu Chartier31e88222016-10-14 18:43:19 -07001183 void operator()(ObjPtr<mirror::Object> obj,
1184 MemberOffset offset,
1185 bool is_static ATTRIBUTE_UNUSED) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001186 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001187 mirror::Object* ref =
1188 obj->GetFieldObject<mirror::Object, kDefaultVerifyFlags, kWithoutReadBarrier>(offset);
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001189 VerifyNoFromSpaceRefsVisitor visitor(collector_);
Mathieu Chartierbc632f02017-04-20 13:31:39 -07001190 visitor(ref, offset, obj.Ptr());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001191 }
Mathieu Chartier31e88222016-10-14 18:43:19 -07001192 void operator()(ObjPtr<mirror::Class> klass,
1193 ObjPtr<mirror::Reference> ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001194 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001195 CHECK(klass->IsTypeOfReferenceClass());
1196 this->operator()(ref, mirror::Reference::ReferentOffset(), false);
1197 }
1198
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001199 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001200 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001201 if (!root->IsNull()) {
1202 VisitRoot(root);
1203 }
1204 }
1205
1206 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001207 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001208 VerifyNoFromSpaceRefsVisitor visitor(collector_);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001209 visitor(root->AsMirrorPtr());
1210 }
1211
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001212 private:
Mathieu Chartier97509952015-07-13 14:35:43 -07001213 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001214};
1215
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001216// Verify there's no from-space references left after the marking phase.
1217void ConcurrentCopying::VerifyNoFromSpaceReferences() {
1218 Thread* self = Thread::Current();
1219 DCHECK(Locks::mutator_lock_->IsExclusiveHeld(self));
Hiroshi Yamauchi00370822015-08-18 14:47:25 -07001220 // Verify all threads have is_gc_marking to be false
1221 {
1222 MutexLock mu(self, *Locks::thread_list_lock_);
1223 std::list<Thread*> thread_list = Runtime::Current()->GetThreadList()->GetList();
1224 for (Thread* thread : thread_list) {
1225 CHECK(!thread->GetIsGcMarking());
1226 }
1227 }
Andreas Gampe0c183382017-07-13 22:26:24 -07001228
1229 auto verify_no_from_space_refs_visitor = [&](mirror::Object* obj)
1230 REQUIRES_SHARED(Locks::mutator_lock_) {
1231 CHECK(obj != nullptr);
1232 space::RegionSpace* region_space = RegionSpace();
1233 CHECK(!region_space->IsInFromSpace(obj)) << "Scanning object " << obj << " in from space";
1234 VerifyNoFromSpaceRefsFieldVisitor visitor(this);
1235 obj->VisitReferences</*kVisitNativeRoots*/true, kDefaultVerifyFlags, kWithoutReadBarrier>(
1236 visitor,
1237 visitor);
1238 if (kUseBakerReadBarrier) {
1239 CHECK_EQ(obj->GetReadBarrierState(), ReadBarrier::WhiteState())
1240 << "obj=" << obj << " non-white rb_state " << obj->GetReadBarrierState();
1241 }
1242 };
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001243 // Roots.
1244 {
1245 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001246 VerifyNoFromSpaceRefsVisitor ref_visitor(this);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001247 Runtime::Current()->VisitRoots(&ref_visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001248 }
1249 // The to-space.
Andreas Gampe0c183382017-07-13 22:26:24 -07001250 region_space_->WalkToSpace(verify_no_from_space_refs_visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001251 // Non-moving spaces.
1252 {
1253 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Andreas Gampe0c183382017-07-13 22:26:24 -07001254 heap_->GetMarkBitmap()->Visit(verify_no_from_space_refs_visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001255 }
1256 // The alloc stack.
1257 {
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001258 VerifyNoFromSpaceRefsVisitor ref_visitor(this);
Mathieu Chartiercb535da2015-01-23 13:50:03 -08001259 for (auto* it = heap_->allocation_stack_->Begin(), *end = heap_->allocation_stack_->End();
1260 it < end; ++it) {
1261 mirror::Object* const obj = it->AsMirrorPtr();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001262 if (obj != nullptr && obj->GetClass() != nullptr) {
1263 // TODO: need to call this only if obj is alive?
1264 ref_visitor(obj);
Andreas Gampe0c183382017-07-13 22:26:24 -07001265 verify_no_from_space_refs_visitor(obj);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001266 }
1267 }
1268 }
1269 // TODO: LOS. But only refs in LOS are classes.
1270}
1271
1272// The following visitors are used to assert the to-space invariant.
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001273class ConcurrentCopying::AssertToSpaceInvariantRefsVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001274 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001275 explicit AssertToSpaceInvariantRefsVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001276 : collector_(collector) {}
1277
1278 void operator()(mirror::Object* ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001279 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001280 if (ref == nullptr) {
1281 // OK.
1282 return;
1283 }
1284 collector_->AssertToSpaceInvariant(nullptr, MemberOffset(0), ref);
1285 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001286
1287 private:
Mathieu Chartier97509952015-07-13 14:35:43 -07001288 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001289};
1290
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001291class ConcurrentCopying::AssertToSpaceInvariantFieldVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001292 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001293 explicit AssertToSpaceInvariantFieldVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001294 : collector_(collector) {}
1295
Mathieu Chartier31e88222016-10-14 18:43:19 -07001296 void operator()(ObjPtr<mirror::Object> obj,
1297 MemberOffset offset,
1298 bool is_static ATTRIBUTE_UNUSED) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001299 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001300 mirror::Object* ref =
1301 obj->GetFieldObject<mirror::Object, kDefaultVerifyFlags, kWithoutReadBarrier>(offset);
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001302 AssertToSpaceInvariantRefsVisitor visitor(collector_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001303 visitor(ref);
1304 }
Mathieu Chartier31e88222016-10-14 18:43:19 -07001305 void operator()(ObjPtr<mirror::Class> klass, ObjPtr<mirror::Reference> ref ATTRIBUTE_UNUSED) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001306 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001307 CHECK(klass->IsTypeOfReferenceClass());
1308 }
1309
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001310 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001311 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001312 if (!root->IsNull()) {
1313 VisitRoot(root);
1314 }
1315 }
1316
1317 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001318 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001319 AssertToSpaceInvariantRefsVisitor visitor(collector_);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001320 visitor(root->AsMirrorPtr());
1321 }
1322
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001323 private:
Mathieu Chartier97509952015-07-13 14:35:43 -07001324 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001325};
1326
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001327class ConcurrentCopying::RevokeThreadLocalMarkStackCheckpoint : public Closure {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001328 public:
Roland Levillain3887c462015-08-12 18:15:42 +01001329 RevokeThreadLocalMarkStackCheckpoint(ConcurrentCopying* concurrent_copying,
1330 bool disable_weak_ref_access)
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001331 : concurrent_copying_(concurrent_copying),
1332 disable_weak_ref_access_(disable_weak_ref_access) {
1333 }
1334
1335 virtual void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
1336 // Note: self is not necessarily equal to thread since thread may be suspended.
1337 Thread* self = Thread::Current();
1338 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
1339 << thread->GetState() << " thread " << thread << " self " << self;
1340 // Revoke thread local mark stacks.
1341 accounting::AtomicStack<mirror::Object>* tl_mark_stack = thread->GetThreadLocalMarkStack();
1342 if (tl_mark_stack != nullptr) {
1343 MutexLock mu(self, concurrent_copying_->mark_stack_lock_);
1344 concurrent_copying_->revoked_mark_stacks_.push_back(tl_mark_stack);
1345 thread->SetThreadLocalMarkStack(nullptr);
1346 }
1347 // Disable weak ref access.
1348 if (disable_weak_ref_access_) {
1349 thread->SetWeakRefAccessEnabled(false);
1350 }
1351 // If thread is a running mutator, then act on behalf of the garbage collector.
1352 // See the code in ThreadList::RunCheckpoint.
Mathieu Chartier10d25082015-10-28 18:36:09 -07001353 concurrent_copying_->GetBarrier().Pass(self);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001354 }
1355
1356 private:
1357 ConcurrentCopying* const concurrent_copying_;
1358 const bool disable_weak_ref_access_;
1359};
1360
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001361void ConcurrentCopying::RevokeThreadLocalMarkStacks(bool disable_weak_ref_access,
1362 Closure* checkpoint_callback) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001363 Thread* self = Thread::Current();
1364 RevokeThreadLocalMarkStackCheckpoint check_point(this, disable_weak_ref_access);
1365 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1366 gc_barrier_->Init(self, 0);
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001367 size_t barrier_count = thread_list->RunCheckpoint(&check_point, checkpoint_callback);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001368 // If there are no threads to wait which implys that all the checkpoint functions are finished,
1369 // then no need to release the mutator lock.
1370 if (barrier_count == 0) {
1371 return;
1372 }
1373 Locks::mutator_lock_->SharedUnlock(self);
1374 {
1375 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
1376 gc_barrier_->Increment(self, barrier_count);
1377 }
1378 Locks::mutator_lock_->SharedLock(self);
1379}
1380
1381void ConcurrentCopying::RevokeThreadLocalMarkStack(Thread* thread) {
1382 Thread* self = Thread::Current();
1383 CHECK_EQ(self, thread);
1384 accounting::AtomicStack<mirror::Object>* tl_mark_stack = thread->GetThreadLocalMarkStack();
1385 if (tl_mark_stack != nullptr) {
1386 CHECK(is_marking_);
1387 MutexLock mu(self, mark_stack_lock_);
1388 revoked_mark_stacks_.push_back(tl_mark_stack);
1389 thread->SetThreadLocalMarkStack(nullptr);
1390 }
1391}
1392
1393void ConcurrentCopying::ProcessMarkStack() {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001394 if (kVerboseMode) {
1395 LOG(INFO) << "ProcessMarkStack. ";
1396 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001397 bool empty_prev = false;
1398 while (true) {
1399 bool empty = ProcessMarkStackOnce();
1400 if (empty_prev && empty) {
1401 // Saw empty mark stack for a second time, done.
1402 break;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001403 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001404 empty_prev = empty;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001405 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001406}
1407
1408bool ConcurrentCopying::ProcessMarkStackOnce() {
1409 Thread* self = Thread::Current();
1410 CHECK(thread_running_gc_ != nullptr);
1411 CHECK(self == thread_running_gc_);
1412 CHECK(self->GetThreadLocalMarkStack() == nullptr);
1413 size_t count = 0;
1414 MarkStackMode mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1415 if (mark_stack_mode == kMarkStackModeThreadLocal) {
1416 // Process the thread-local mark stacks and the GC mark stack.
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001417 count += ProcessThreadLocalMarkStacks(false, nullptr);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001418 while (!gc_mark_stack_->IsEmpty()) {
1419 mirror::Object* to_ref = gc_mark_stack_->PopBack();
1420 ProcessMarkStackRef(to_ref);
1421 ++count;
1422 }
1423 gc_mark_stack_->Reset();
1424 } else if (mark_stack_mode == kMarkStackModeShared) {
Hiroshi Yamauchi30493242016-11-03 13:06:52 -07001425 // Do an empty checkpoint to avoid a race with a mutator preempted in the middle of a read
1426 // barrier but before pushing onto the mark stack. b/32508093. Note the weak ref access is
1427 // disabled at this point.
1428 IssueEmptyCheckpoint();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001429 // Process the shared GC mark stack with a lock.
1430 {
1431 MutexLock mu(self, mark_stack_lock_);
1432 CHECK(revoked_mark_stacks_.empty());
1433 }
1434 while (true) {
1435 std::vector<mirror::Object*> refs;
1436 {
1437 // Copy refs with lock. Note the number of refs should be small.
1438 MutexLock mu(self, mark_stack_lock_);
1439 if (gc_mark_stack_->IsEmpty()) {
1440 break;
1441 }
1442 for (StackReference<mirror::Object>* p = gc_mark_stack_->Begin();
1443 p != gc_mark_stack_->End(); ++p) {
1444 refs.push_back(p->AsMirrorPtr());
1445 }
1446 gc_mark_stack_->Reset();
1447 }
1448 for (mirror::Object* ref : refs) {
1449 ProcessMarkStackRef(ref);
1450 ++count;
1451 }
1452 }
1453 } else {
1454 CHECK_EQ(static_cast<uint32_t>(mark_stack_mode),
1455 static_cast<uint32_t>(kMarkStackModeGcExclusive));
1456 {
1457 MutexLock mu(self, mark_stack_lock_);
1458 CHECK(revoked_mark_stacks_.empty());
1459 }
1460 // Process the GC mark stack in the exclusive mode. No need to take the lock.
1461 while (!gc_mark_stack_->IsEmpty()) {
1462 mirror::Object* to_ref = gc_mark_stack_->PopBack();
1463 ProcessMarkStackRef(to_ref);
1464 ++count;
1465 }
1466 gc_mark_stack_->Reset();
1467 }
1468
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001469 // Return true if the stack was empty.
1470 return count == 0;
1471}
1472
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001473size_t ConcurrentCopying::ProcessThreadLocalMarkStacks(bool disable_weak_ref_access,
1474 Closure* checkpoint_callback) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001475 // Run a checkpoint to collect all thread local mark stacks and iterate over them all.
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001476 RevokeThreadLocalMarkStacks(disable_weak_ref_access, checkpoint_callback);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001477 size_t count = 0;
1478 std::vector<accounting::AtomicStack<mirror::Object>*> mark_stacks;
1479 {
1480 MutexLock mu(Thread::Current(), mark_stack_lock_);
1481 // Make a copy of the mark stack vector.
1482 mark_stacks = revoked_mark_stacks_;
1483 revoked_mark_stacks_.clear();
1484 }
1485 for (accounting::AtomicStack<mirror::Object>* mark_stack : mark_stacks) {
1486 for (StackReference<mirror::Object>* p = mark_stack->Begin(); p != mark_stack->End(); ++p) {
1487 mirror::Object* to_ref = p->AsMirrorPtr();
1488 ProcessMarkStackRef(to_ref);
1489 ++count;
1490 }
1491 {
1492 MutexLock mu(Thread::Current(), mark_stack_lock_);
1493 if (pooled_mark_stacks_.size() >= kMarkStackPoolSize) {
1494 // The pool has enough. Delete it.
1495 delete mark_stack;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001496 } else {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001497 // Otherwise, put it into the pool for later reuse.
1498 mark_stack->Reset();
1499 pooled_mark_stacks_.push_back(mark_stack);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001500 }
1501 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001502 }
1503 return count;
1504}
1505
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001506inline void ConcurrentCopying::ProcessMarkStackRef(mirror::Object* to_ref) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001507 DCHECK(!region_space_->IsInFromSpace(to_ref));
1508 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001509 DCHECK(to_ref->GetReadBarrierState() == ReadBarrier::GrayState())
1510 << " " << to_ref << " " << to_ref->GetReadBarrierState()
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001511 << " is_marked=" << IsMarked(to_ref);
1512 }
Mathieu Chartierc381c362016-08-23 13:27:53 -07001513 bool add_to_live_bytes = false;
1514 if (region_space_->IsInUnevacFromSpace(to_ref)) {
1515 // Mark the bitmap only in the GC thread here so that we don't need a CAS.
1516 if (!kUseBakerReadBarrier || !region_space_bitmap_->Set(to_ref)) {
1517 // It may be already marked if we accidentally pushed the same object twice due to the racy
1518 // bitmap read in MarkUnevacFromSpaceRegion.
1519 Scan(to_ref);
1520 // Only add to the live bytes if the object was not already marked.
1521 add_to_live_bytes = true;
1522 }
1523 } else {
1524 Scan(to_ref);
1525 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001526 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001527 DCHECK(to_ref->GetReadBarrierState() == ReadBarrier::GrayState())
1528 << " " << to_ref << " " << to_ref->GetReadBarrierState()
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001529 << " is_marked=" << IsMarked(to_ref);
1530 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001531#ifdef USE_BAKER_OR_BROOKS_READ_BARRIER
Hiroshi Yamauchi39c12d42016-12-06 16:46:37 -08001532 mirror::Object* referent = nullptr;
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001533 if (UNLIKELY((to_ref->GetClass<kVerifyNone, kWithoutReadBarrier>()->IsTypeOfReferenceClass() &&
Hiroshi Yamauchi39c12d42016-12-06 16:46:37 -08001534 (referent = to_ref->AsReference()->GetReferent<kWithoutReadBarrier>()) != nullptr &&
1535 !IsInToSpace(referent)))) {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001536 // Leave this reference gray in the queue so that GetReferent() will trigger a read barrier. We
1537 // will change it to white later in ReferenceQueue::DequeuePendingReference().
Richard Uhlere3627402016-02-02 13:36:55 -08001538 DCHECK(to_ref->AsReference()->GetPendingNext() != nullptr) << "Left unenqueued ref gray " << to_ref;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001539 } else {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001540 // We may occasionally leave a reference white in the queue if its referent happens to be
1541 // concurrently marked after the Scan() call above has enqueued the Reference, in which case the
1542 // above IsInToSpace() evaluates to true and we change the color from gray to white here in this
1543 // else block.
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001544 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001545 bool success = to_ref->AtomicSetReadBarrierState</*kCasRelease*/true>(
1546 ReadBarrier::GrayState(),
1547 ReadBarrier::WhiteState());
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001548 DCHECK(success) << "Must succeed as we won the race.";
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001549 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001550 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001551#else
1552 DCHECK(!kUseBakerReadBarrier);
1553#endif
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001554
Mathieu Chartierc381c362016-08-23 13:27:53 -07001555 if (add_to_live_bytes) {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001556 // Add to the live bytes per unevacuated from space. Note this code is always run by the
1557 // GC-running thread (no synchronization required).
1558 DCHECK(region_space_bitmap_->Test(to_ref));
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07001559 size_t obj_size = to_ref->SizeOf<kDefaultVerifyFlags>();
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001560 size_t alloc_size = RoundUp(obj_size, space::RegionSpace::kAlignment);
1561 region_space_->AddLiveBytes(to_ref, alloc_size);
1562 }
Andreas Gampee3ce7872017-02-22 13:36:21 -08001563 if (ReadBarrier::kEnableToSpaceInvariantChecks) {
Andreas Gampe0c183382017-07-13 22:26:24 -07001564 CHECK(to_ref != nullptr);
1565 space::RegionSpace* region_space = RegionSpace();
1566 CHECK(!region_space->IsInFromSpace(to_ref)) << "Scanning object " << to_ref << " in from space";
1567 AssertToSpaceInvariant(nullptr, MemberOffset(0), to_ref);
1568 AssertToSpaceInvariantFieldVisitor visitor(this);
1569 to_ref->VisitReferences</*kVisitNativeRoots*/true, kDefaultVerifyFlags, kWithoutReadBarrier>(
1570 visitor,
1571 visitor);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001572 }
1573}
1574
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001575class ConcurrentCopying::DisableWeakRefAccessCallback : public Closure {
1576 public:
1577 explicit DisableWeakRefAccessCallback(ConcurrentCopying* concurrent_copying)
1578 : concurrent_copying_(concurrent_copying) {
1579 }
1580
1581 void Run(Thread* self ATTRIBUTE_UNUSED) OVERRIDE REQUIRES(Locks::thread_list_lock_) {
1582 // This needs to run under the thread_list_lock_ critical section in ThreadList::RunCheckpoint()
1583 // to avoid a deadlock b/31500969.
1584 CHECK(concurrent_copying_->weak_ref_access_enabled_);
1585 concurrent_copying_->weak_ref_access_enabled_ = false;
1586 }
1587
1588 private:
1589 ConcurrentCopying* const concurrent_copying_;
1590};
1591
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001592void ConcurrentCopying::SwitchToSharedMarkStackMode() {
1593 Thread* self = Thread::Current();
1594 CHECK(thread_running_gc_ != nullptr);
1595 CHECK_EQ(self, thread_running_gc_);
1596 CHECK(self->GetThreadLocalMarkStack() == nullptr);
1597 MarkStackMode before_mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1598 CHECK_EQ(static_cast<uint32_t>(before_mark_stack_mode),
1599 static_cast<uint32_t>(kMarkStackModeThreadLocal));
1600 mark_stack_mode_.StoreRelaxed(kMarkStackModeShared);
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001601 DisableWeakRefAccessCallback dwrac(this);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001602 // Process the thread local mark stacks one last time after switching to the shared mark stack
1603 // mode and disable weak ref accesses.
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001604 ProcessThreadLocalMarkStacks(true, &dwrac);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001605 if (kVerboseMode) {
1606 LOG(INFO) << "Switched to shared mark stack mode and disabled weak ref access";
1607 }
1608}
1609
1610void ConcurrentCopying::SwitchToGcExclusiveMarkStackMode() {
1611 Thread* self = Thread::Current();
1612 CHECK(thread_running_gc_ != nullptr);
1613 CHECK_EQ(self, thread_running_gc_);
1614 CHECK(self->GetThreadLocalMarkStack() == nullptr);
1615 MarkStackMode before_mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1616 CHECK_EQ(static_cast<uint32_t>(before_mark_stack_mode),
1617 static_cast<uint32_t>(kMarkStackModeShared));
1618 mark_stack_mode_.StoreRelaxed(kMarkStackModeGcExclusive);
1619 QuasiAtomic::ThreadFenceForConstructor();
1620 if (kVerboseMode) {
1621 LOG(INFO) << "Switched to GC exclusive mark stack mode";
1622 }
1623}
1624
1625void ConcurrentCopying::CheckEmptyMarkStack() {
1626 Thread* self = Thread::Current();
1627 CHECK(thread_running_gc_ != nullptr);
1628 CHECK_EQ(self, thread_running_gc_);
1629 CHECK(self->GetThreadLocalMarkStack() == nullptr);
1630 MarkStackMode mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1631 if (mark_stack_mode == kMarkStackModeThreadLocal) {
1632 // Thread-local mark stack mode.
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001633 RevokeThreadLocalMarkStacks(false, nullptr);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001634 MutexLock mu(Thread::Current(), mark_stack_lock_);
1635 if (!revoked_mark_stacks_.empty()) {
1636 for (accounting::AtomicStack<mirror::Object>* mark_stack : revoked_mark_stacks_) {
1637 while (!mark_stack->IsEmpty()) {
1638 mirror::Object* obj = mark_stack->PopBack();
1639 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001640 uint32_t rb_state = obj->GetReadBarrierState();
1641 LOG(INFO) << "On mark queue : " << obj << " " << obj->PrettyTypeOf() << " rb_state="
1642 << rb_state << " is_marked=" << IsMarked(obj);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001643 } else {
David Sehr709b0702016-10-13 09:12:37 -07001644 LOG(INFO) << "On mark queue : " << obj << " " << obj->PrettyTypeOf()
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001645 << " is_marked=" << IsMarked(obj);
1646 }
1647 }
1648 }
1649 LOG(FATAL) << "mark stack is not empty";
1650 }
1651 } else {
1652 // Shared, GC-exclusive, or off.
1653 MutexLock mu(Thread::Current(), mark_stack_lock_);
1654 CHECK(gc_mark_stack_->IsEmpty());
1655 CHECK(revoked_mark_stacks_.empty());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001656 }
1657}
1658
1659void ConcurrentCopying::SweepSystemWeaks(Thread* self) {
1660 TimingLogger::ScopedTiming split("SweepSystemWeaks", GetTimings());
1661 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier97509952015-07-13 14:35:43 -07001662 Runtime::Current()->SweepSystemWeaks(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001663}
1664
1665void ConcurrentCopying::Sweep(bool swap_bitmaps) {
1666 {
1667 TimingLogger::ScopedTiming t("MarkStackAsLive", GetTimings());
1668 accounting::ObjectStack* live_stack = heap_->GetLiveStack();
1669 if (kEnableFromSpaceAccountingCheck) {
1670 CHECK_GE(live_stack_freeze_size_, live_stack->Size());
1671 }
1672 heap_->MarkAllocStackAsLive(live_stack);
1673 live_stack->Reset();
1674 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001675 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001676 TimingLogger::ScopedTiming split("Sweep", GetTimings());
1677 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
1678 if (space->IsContinuousMemMapAllocSpace()) {
1679 space::ContinuousMemMapAllocSpace* alloc_space = space->AsContinuousMemMapAllocSpace();
Mathieu Chartier763a31e2015-11-16 16:05:55 -08001680 if (space == region_space_ || immune_spaces_.ContainsSpace(space)) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001681 continue;
1682 }
1683 TimingLogger::ScopedTiming split2(
1684 alloc_space->IsZygoteSpace() ? "SweepZygoteSpace" : "SweepAllocSpace", GetTimings());
1685 RecordFree(alloc_space->Sweep(swap_bitmaps));
1686 }
1687 }
1688 SweepLargeObjects(swap_bitmaps);
1689}
1690
Mathieu Chartier962cd7a2016-08-16 12:15:59 -07001691void ConcurrentCopying::MarkZygoteLargeObjects() {
1692 TimingLogger::ScopedTiming split(__FUNCTION__, GetTimings());
1693 Thread* const self = Thread::Current();
1694 WriterMutexLock rmu(self, *Locks::heap_bitmap_lock_);
1695 space::LargeObjectSpace* const los = heap_->GetLargeObjectsSpace();
Nicolas Geoffray7acddd82017-05-03 15:04:55 +01001696 if (los != nullptr) {
1697 // Pick the current live bitmap (mark bitmap if swapped).
1698 accounting::LargeObjectBitmap* const live_bitmap = los->GetLiveBitmap();
1699 accounting::LargeObjectBitmap* const mark_bitmap = los->GetMarkBitmap();
1700 // Walk through all of the objects and explicitly mark the zygote ones so they don't get swept.
1701 std::pair<uint8_t*, uint8_t*> range = los->GetBeginEndAtomic();
1702 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(range.first),
1703 reinterpret_cast<uintptr_t>(range.second),
1704 [mark_bitmap, los, self](mirror::Object* obj)
1705 REQUIRES(Locks::heap_bitmap_lock_)
1706 REQUIRES_SHARED(Locks::mutator_lock_) {
1707 if (los->IsZygoteLargeObject(self, obj)) {
1708 mark_bitmap->Set(obj);
1709 }
1710 });
1711 }
Mathieu Chartier962cd7a2016-08-16 12:15:59 -07001712}
1713
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001714void ConcurrentCopying::SweepLargeObjects(bool swap_bitmaps) {
1715 TimingLogger::ScopedTiming split("SweepLargeObjects", GetTimings());
Nicolas Geoffray7acddd82017-05-03 15:04:55 +01001716 if (heap_->GetLargeObjectsSpace() != nullptr) {
1717 RecordFreeLOS(heap_->GetLargeObjectsSpace()->Sweep(swap_bitmaps));
1718 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001719}
1720
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001721void ConcurrentCopying::ReclaimPhase() {
1722 TimingLogger::ScopedTiming split("ReclaimPhase", GetTimings());
1723 if (kVerboseMode) {
1724 LOG(INFO) << "GC ReclaimPhase";
1725 }
1726 Thread* self = Thread::Current();
1727
1728 {
1729 // Double-check that the mark stack is empty.
1730 // Note: need to set this after VerifyNoFromSpaceRef().
1731 is_asserting_to_space_invariant_ = false;
1732 QuasiAtomic::ThreadFenceForConstructor();
1733 if (kVerboseMode) {
1734 LOG(INFO) << "Issue an empty check point. ";
1735 }
1736 IssueEmptyCheckpoint();
1737 // Disable the check.
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001738 is_mark_stack_push_disallowed_.StoreSequentiallyConsistent(0);
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001739 if (kUseBakerReadBarrier) {
1740 updated_all_immune_objects_.StoreSequentiallyConsistent(false);
1741 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001742 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001743 }
1744
1745 {
1746 // Record freed objects.
1747 TimingLogger::ScopedTiming split2("RecordFree", GetTimings());
1748 // Don't include thread-locals that are in the to-space.
Mathieu Chartier371b0472017-02-27 16:37:21 -08001749 const uint64_t from_bytes = region_space_->GetBytesAllocatedInFromSpace();
1750 const uint64_t from_objects = region_space_->GetObjectsAllocatedInFromSpace();
1751 const uint64_t unevac_from_bytes = region_space_->GetBytesAllocatedInUnevacFromSpace();
1752 const uint64_t unevac_from_objects = region_space_->GetObjectsAllocatedInUnevacFromSpace();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001753 uint64_t to_bytes = bytes_moved_.LoadSequentiallyConsistent();
Mathieu Chartiercca44a02016-08-17 10:07:29 -07001754 cumulative_bytes_moved_.FetchAndAddRelaxed(to_bytes);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001755 uint64_t to_objects = objects_moved_.LoadSequentiallyConsistent();
Mathieu Chartiercca44a02016-08-17 10:07:29 -07001756 cumulative_objects_moved_.FetchAndAddRelaxed(to_objects);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001757 if (kEnableFromSpaceAccountingCheck) {
1758 CHECK_EQ(from_space_num_objects_at_first_pause_, from_objects + unevac_from_objects);
1759 CHECK_EQ(from_space_num_bytes_at_first_pause_, from_bytes + unevac_from_bytes);
1760 }
1761 CHECK_LE(to_objects, from_objects);
1762 CHECK_LE(to_bytes, from_bytes);
Mathieu Chartier371b0472017-02-27 16:37:21 -08001763 // cleared_bytes and cleared_objects may be greater than the from space equivalents since
1764 // ClearFromSpace may clear empty unevac regions.
1765 uint64_t cleared_bytes;
1766 uint64_t cleared_objects;
1767 {
1768 TimingLogger::ScopedTiming split4("ClearFromSpace", GetTimings());
1769 region_space_->ClearFromSpace(&cleared_bytes, &cleared_objects);
1770 CHECK_GE(cleared_bytes, from_bytes);
1771 CHECK_GE(cleared_objects, from_objects);
1772 }
1773 int64_t freed_bytes = cleared_bytes - to_bytes;
1774 int64_t freed_objects = cleared_objects - to_objects;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001775 if (kVerboseMode) {
1776 LOG(INFO) << "RecordFree:"
1777 << " from_bytes=" << from_bytes << " from_objects=" << from_objects
1778 << " unevac_from_bytes=" << unevac_from_bytes << " unevac_from_objects=" << unevac_from_objects
1779 << " to_bytes=" << to_bytes << " to_objects=" << to_objects
1780 << " freed_bytes=" << freed_bytes << " freed_objects=" << freed_objects
1781 << " from_space size=" << region_space_->FromSpaceSize()
1782 << " unevac_from_space size=" << region_space_->UnevacFromSpaceSize()
1783 << " to_space size=" << region_space_->ToSpaceSize();
1784 LOG(INFO) << "(before) num_bytes_allocated=" << heap_->num_bytes_allocated_.LoadSequentiallyConsistent();
1785 }
1786 RecordFree(ObjectBytePair(freed_objects, freed_bytes));
1787 if (kVerboseMode) {
1788 LOG(INFO) << "(after) num_bytes_allocated=" << heap_->num_bytes_allocated_.LoadSequentiallyConsistent();
1789 }
1790 }
1791
1792 {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001793 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001794 Sweep(false);
1795 SwapBitmaps();
1796 heap_->UnBindBitmaps();
1797
Mathieu Chartier7ec38dc2016-10-07 15:24:46 -07001798 // 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 -07001799 DCHECK(region_space_bitmap_ != nullptr);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001800 region_space_bitmap_ = nullptr;
1801 }
1802
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001803 CheckEmptyMarkStack();
1804
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001805 if (kVerboseMode) {
1806 LOG(INFO) << "GC end of ReclaimPhase";
1807 }
1808}
1809
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001810// Assert the to-space invariant.
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07001811void ConcurrentCopying::AssertToSpaceInvariant(mirror::Object* obj,
1812 MemberOffset offset,
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001813 mirror::Object* ref) {
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07001814 CHECK_EQ(heap_->collector_type_, kCollectorTypeCC);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001815 if (is_asserting_to_space_invariant_) {
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07001816 using RegionType = space::RegionSpace::RegionType;
1817 space::RegionSpace::RegionType type = region_space_->GetRegionType(ref);
1818 if (type == RegionType::kRegionTypeToSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001819 // OK.
1820 return;
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07001821 } else if (type == RegionType::kRegionTypeUnevacFromSpace) {
Mathieu Chartierc381c362016-08-23 13:27:53 -07001822 CHECK(IsMarkedInUnevacFromSpace(ref)) << ref;
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07001823 } else if (UNLIKELY(type == RegionType::kRegionTypeFromSpace)) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001824 // Not OK. Do extra logging.
1825 if (obj != nullptr) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001826 LogFromSpaceRefHolder(obj, offset);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001827 }
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07001828 ref->GetLockWord(false).Dump(LOG_STREAM(FATAL_WITHOUT_ABORT));
David Sehr709b0702016-10-13 09:12:37 -07001829 CHECK(false) << "Found from-space ref " << ref << " " << ref->PrettyTypeOf();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001830 } else {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001831 AssertToSpaceInvariantInNonMovingSpace(obj, ref);
1832 }
1833 }
1834}
1835
1836class RootPrinter {
1837 public:
1838 RootPrinter() { }
1839
1840 template <class MirrorType>
1841 ALWAYS_INLINE void VisitRootIfNonNull(mirror::CompressedReference<MirrorType>* root)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001842 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001843 if (!root->IsNull()) {
1844 VisitRoot(root);
1845 }
1846 }
1847
1848 template <class MirrorType>
1849 void VisitRoot(mirror::Object** root)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001850 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07001851 LOG(FATAL_WITHOUT_ABORT) << "root=" << root << " ref=" << *root;
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001852 }
1853
1854 template <class MirrorType>
1855 void VisitRoot(mirror::CompressedReference<MirrorType>* root)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001856 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07001857 LOG(FATAL_WITHOUT_ABORT) << "root=" << root << " ref=" << root->AsMirrorPtr();
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001858 }
1859};
1860
1861void ConcurrentCopying::AssertToSpaceInvariant(GcRootSource* gc_root_source,
1862 mirror::Object* ref) {
1863 CHECK(heap_->collector_type_ == kCollectorTypeCC) << static_cast<size_t>(heap_->collector_type_);
1864 if (is_asserting_to_space_invariant_) {
1865 if (region_space_->IsInToSpace(ref)) {
1866 // OK.
1867 return;
1868 } else if (region_space_->IsInUnevacFromSpace(ref)) {
Mathieu Chartierc381c362016-08-23 13:27:53 -07001869 CHECK(IsMarkedInUnevacFromSpace(ref)) << ref;
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001870 } else if (region_space_->IsInFromSpace(ref)) {
1871 // Not OK. Do extra logging.
1872 if (gc_root_source == nullptr) {
1873 // No info.
1874 } else if (gc_root_source->HasArtField()) {
1875 ArtField* field = gc_root_source->GetArtField();
David Sehr709b0702016-10-13 09:12:37 -07001876 LOG(FATAL_WITHOUT_ABORT) << "gc root in field " << field << " "
1877 << ArtField::PrettyField(field);
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001878 RootPrinter root_printer;
1879 field->VisitRoots(root_printer);
1880 } else if (gc_root_source->HasArtMethod()) {
1881 ArtMethod* method = gc_root_source->GetArtMethod();
David Sehr709b0702016-10-13 09:12:37 -07001882 LOG(FATAL_WITHOUT_ABORT) << "gc root in method " << method << " "
1883 << ArtMethod::PrettyMethod(method);
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001884 RootPrinter root_printer;
Andreas Gampe542451c2016-07-26 09:02:02 -07001885 method->VisitRoots(root_printer, kRuntimePointerSize);
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001886 }
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07001887 ref->GetLockWord(false).Dump(LOG_STREAM(FATAL_WITHOUT_ABORT));
1888 region_space_->DumpNonFreeRegions(LOG_STREAM(FATAL_WITHOUT_ABORT));
1889 PrintFileToLog("/proc/self/maps", LogSeverity::FATAL_WITHOUT_ABORT);
1890 MemMap::DumpMaps(LOG_STREAM(FATAL_WITHOUT_ABORT), true);
David Sehr709b0702016-10-13 09:12:37 -07001891 CHECK(false) << "Found from-space ref " << ref << " " << ref->PrettyTypeOf();
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001892 } else {
1893 AssertToSpaceInvariantInNonMovingSpace(nullptr, ref);
1894 }
1895 }
1896}
1897
1898void ConcurrentCopying::LogFromSpaceRefHolder(mirror::Object* obj, MemberOffset offset) {
1899 if (kUseBakerReadBarrier) {
David Sehr709b0702016-10-13 09:12:37 -07001900 LOG(INFO) << "holder=" << obj << " " << obj->PrettyTypeOf()
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001901 << " holder rb_state=" << obj->GetReadBarrierState();
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001902 } else {
David Sehr709b0702016-10-13 09:12:37 -07001903 LOG(INFO) << "holder=" << obj << " " << obj->PrettyTypeOf();
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001904 }
1905 if (region_space_->IsInFromSpace(obj)) {
1906 LOG(INFO) << "holder is in the from-space.";
1907 } else if (region_space_->IsInToSpace(obj)) {
1908 LOG(INFO) << "holder is in the to-space.";
1909 } else if (region_space_->IsInUnevacFromSpace(obj)) {
1910 LOG(INFO) << "holder is in the unevac from-space.";
Mathieu Chartierc381c362016-08-23 13:27:53 -07001911 if (IsMarkedInUnevacFromSpace(obj)) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001912 LOG(INFO) << "holder is marked in the region space bitmap.";
1913 } else {
1914 LOG(INFO) << "holder is not marked in the region space bitmap.";
1915 }
1916 } else {
1917 // In a non-moving space.
Mathieu Chartier763a31e2015-11-16 16:05:55 -08001918 if (immune_spaces_.ContainsObject(obj)) {
1919 LOG(INFO) << "holder is in an immune image or the zygote space.";
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001920 } else {
Mathieu Chartier763a31e2015-11-16 16:05:55 -08001921 LOG(INFO) << "holder is in a non-immune, non-moving (or main) space.";
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001922 accounting::ContinuousSpaceBitmap* mark_bitmap =
1923 heap_mark_bitmap_->GetContinuousSpaceBitmap(obj);
1924 accounting::LargeObjectBitmap* los_bitmap =
1925 heap_mark_bitmap_->GetLargeObjectBitmap(obj);
1926 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
1927 bool is_los = mark_bitmap == nullptr;
1928 if (!is_los && mark_bitmap->Test(obj)) {
1929 LOG(INFO) << "holder is marked in the mark bit map.";
1930 } else if (is_los && los_bitmap->Test(obj)) {
1931 LOG(INFO) << "holder is marked in the los bit map.";
1932 } else {
1933 // If ref is on the allocation stack, then it is considered
1934 // mark/alive (but not necessarily on the live stack.)
1935 if (IsOnAllocStack(obj)) {
1936 LOG(INFO) << "holder is on the alloc stack.";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001937 } else {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001938 LOG(INFO) << "holder is not marked or on the alloc stack.";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001939 }
1940 }
1941 }
1942 }
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001943 LOG(INFO) << "offset=" << offset.SizeValue();
1944}
1945
1946void ConcurrentCopying::AssertToSpaceInvariantInNonMovingSpace(mirror::Object* obj,
1947 mirror::Object* ref) {
1948 // In a non-moving spaces. Check that the ref is marked.
Mathieu Chartier763a31e2015-11-16 16:05:55 -08001949 if (immune_spaces_.ContainsObject(ref)) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001950 if (kUseBakerReadBarrier) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001951 // Immune object may not be gray if called from the GC.
1952 if (Thread::Current() == thread_running_gc_ && !gc_grays_immune_objects_) {
1953 return;
1954 }
1955 bool updated_all_immune_objects = updated_all_immune_objects_.LoadSequentiallyConsistent();
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001956 CHECK(updated_all_immune_objects || ref->GetReadBarrierState() == ReadBarrier::GrayState())
1957 << "Unmarked immune space ref. obj=" << obj << " rb_state="
1958 << (obj != nullptr ? obj->GetReadBarrierState() : 0U)
1959 << " ref=" << ref << " ref rb_state=" << ref->GetReadBarrierState()
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001960 << " updated_all_immune_objects=" << updated_all_immune_objects;
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001961 }
1962 } else {
1963 accounting::ContinuousSpaceBitmap* mark_bitmap =
1964 heap_mark_bitmap_->GetContinuousSpaceBitmap(ref);
1965 accounting::LargeObjectBitmap* los_bitmap =
1966 heap_mark_bitmap_->GetLargeObjectBitmap(ref);
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001967 bool is_los = mark_bitmap == nullptr;
1968 if ((!is_los && mark_bitmap->Test(ref)) ||
1969 (is_los && los_bitmap->Test(ref))) {
1970 // OK.
1971 } else {
1972 // If ref is on the allocation stack, then it may not be
1973 // marked live, but considered marked/alive (but not
1974 // necessarily on the live stack).
1975 CHECK(IsOnAllocStack(ref)) << "Unmarked ref that's not on the allocation stack. "
1976 << "obj=" << obj << " ref=" << ref;
1977 }
1978 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001979}
1980
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001981// Used to scan ref fields of an object.
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001982class ConcurrentCopying::RefFieldsVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001983 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001984 explicit RefFieldsVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001985 : collector_(collector) {}
1986
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07001987 void operator()(mirror::Object* obj, MemberOffset offset, bool /* is_static */)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001988 const ALWAYS_INLINE REQUIRES_SHARED(Locks::mutator_lock_)
1989 REQUIRES_SHARED(Locks::heap_bitmap_lock_) {
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07001990 collector_->Process(obj, offset);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001991 }
1992
Mathieu Chartier31e88222016-10-14 18:43:19 -07001993 void operator()(ObjPtr<mirror::Class> klass, ObjPtr<mirror::Reference> ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001994 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001995 CHECK(klass->IsTypeOfReferenceClass());
1996 collector_->DelayReferenceReferent(klass, ref);
1997 }
1998
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001999 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002000 ALWAYS_INLINE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002001 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002002 if (!root->IsNull()) {
2003 VisitRoot(root);
2004 }
2005 }
2006
2007 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002008 ALWAYS_INLINE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002009 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002010 collector_->MarkRoot</*kGrayImmuneObject*/false>(root);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002011 }
2012
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002013 private:
2014 ConcurrentCopying* const collector_;
2015};
2016
2017// Scan ref fields of an object.
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002018inline void ConcurrentCopying::Scan(mirror::Object* to_ref) {
Hiroshi Yamauchi9b60d502017-02-03 15:09:26 -08002019 if (kDisallowReadBarrierDuringScan && !Runtime::Current()->IsActiveTransaction()) {
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07002020 // Avoid all read barriers during visit references to help performance.
Hiroshi Yamauchi9b60d502017-02-03 15:09:26 -08002021 // Don't do this in transaction mode because we may read the old value of an field which may
2022 // trigger read barriers.
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07002023 Thread::Current()->ModifyDebugDisallowReadBarrier(1);
2024 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002025 DCHECK(!region_space_->IsInFromSpace(to_ref));
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002026 DCHECK_EQ(Thread::Current(), thread_running_gc_);
Mathieu Chartiera07f5592016-06-16 11:44:28 -07002027 RefFieldsVisitor visitor(this);
Hiroshi Yamauchi5496f692016-02-17 13:29:59 -08002028 // Disable the read barrier for a performance reason.
2029 to_ref->VisitReferences</*kVisitNativeRoots*/true, kDefaultVerifyFlags, kWithoutReadBarrier>(
2030 visitor, visitor);
Hiroshi Yamauchi9b60d502017-02-03 15:09:26 -08002031 if (kDisallowReadBarrierDuringScan && !Runtime::Current()->IsActiveTransaction()) {
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07002032 Thread::Current()->ModifyDebugDisallowReadBarrier(-1);
2033 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002034}
2035
2036// Process a field.
2037inline void ConcurrentCopying::Process(mirror::Object* obj, MemberOffset offset) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002038 DCHECK_EQ(Thread::Current(), thread_running_gc_);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002039 mirror::Object* ref = obj->GetFieldObject<
2040 mirror::Object, kVerifyNone, kWithoutReadBarrier, false>(offset);
Mathieu Chartier4ce0c762017-05-18 10:01:07 -07002041 mirror::Object* to_ref = Mark</*kGrayImmuneObject*/false, /*kFromGCThread*/true>(
2042 ref,
2043 /*holder*/ obj,
2044 offset);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002045 if (to_ref == ref) {
2046 return;
2047 }
2048 // This may fail if the mutator writes to the field at the same time. But it's ok.
2049 mirror::Object* expected_ref = ref;
2050 mirror::Object* new_ref = to_ref;
2051 do {
2052 if (expected_ref !=
2053 obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier, false>(offset)) {
2054 // It was updated by the mutator.
2055 break;
2056 }
Mathieu Chartierfdd513d2017-06-01 11:26:50 -07002057 // Use release cas to make sure threads reading the reference see contents of copied objects.
2058 } while (!obj->CasFieldWeakReleaseObjectWithoutWriteBarrier<false, false, kVerifyNone>(
2059 offset,
2060 expected_ref,
2061 new_ref));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002062}
2063
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002064// Process some roots.
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002065inline void ConcurrentCopying::VisitRoots(
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002066 mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED) {
2067 for (size_t i = 0; i < count; ++i) {
2068 mirror::Object** root = roots[i];
2069 mirror::Object* ref = *root;
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002070 mirror::Object* to_ref = Mark(ref);
2071 if (to_ref == ref) {
Mathieu Chartier4809d0a2015-04-07 10:39:04 -07002072 continue;
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002073 }
2074 Atomic<mirror::Object*>* addr = reinterpret_cast<Atomic<mirror::Object*>*>(root);
2075 mirror::Object* expected_ref = ref;
2076 mirror::Object* new_ref = to_ref;
2077 do {
2078 if (expected_ref != addr->LoadRelaxed()) {
2079 // It was updated by the mutator.
2080 break;
2081 }
Orion Hodson4557b382018-01-03 11:47:54 +00002082 } while (!addr->CompareAndSetWeakRelaxed(expected_ref, new_ref));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002083 }
2084}
2085
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002086template<bool kGrayImmuneObject>
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002087inline void ConcurrentCopying::MarkRoot(mirror::CompressedReference<mirror::Object>* root) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002088 DCHECK(!root->IsNull());
2089 mirror::Object* const ref = root->AsMirrorPtr();
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002090 mirror::Object* to_ref = Mark<kGrayImmuneObject>(ref);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002091 if (to_ref != ref) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002092 auto* addr = reinterpret_cast<Atomic<mirror::CompressedReference<mirror::Object>>*>(root);
2093 auto expected_ref = mirror::CompressedReference<mirror::Object>::FromMirrorPtr(ref);
2094 auto new_ref = mirror::CompressedReference<mirror::Object>::FromMirrorPtr(to_ref);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002095 // If the cas fails, then it was updated by the mutator.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002096 do {
2097 if (ref != addr->LoadRelaxed().AsMirrorPtr()) {
2098 // It was updated by the mutator.
2099 break;
2100 }
Orion Hodson4557b382018-01-03 11:47:54 +00002101 } while (!addr->CompareAndSetWeakRelaxed(expected_ref, new_ref));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002102 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002103}
2104
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002105inline void ConcurrentCopying::VisitRoots(
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002106 mirror::CompressedReference<mirror::Object>** roots, size_t count,
2107 const RootInfo& info ATTRIBUTE_UNUSED) {
2108 for (size_t i = 0; i < count; ++i) {
2109 mirror::CompressedReference<mirror::Object>* const root = roots[i];
2110 if (!root->IsNull()) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002111 // kGrayImmuneObject is true because this is used for the thread flip.
2112 MarkRoot</*kGrayImmuneObject*/true>(root);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002113 }
2114 }
2115}
2116
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002117// Temporary set gc_grays_immune_objects_ to true in a scope if the current thread is GC.
2118class ConcurrentCopying::ScopedGcGraysImmuneObjects {
2119 public:
2120 explicit ScopedGcGraysImmuneObjects(ConcurrentCopying* collector)
2121 : collector_(collector), enabled_(false) {
2122 if (kUseBakerReadBarrier &&
2123 collector_->thread_running_gc_ == Thread::Current() &&
2124 !collector_->gc_grays_immune_objects_) {
2125 collector_->gc_grays_immune_objects_ = true;
2126 enabled_ = true;
2127 }
2128 }
2129
2130 ~ScopedGcGraysImmuneObjects() {
2131 if (kUseBakerReadBarrier &&
2132 collector_->thread_running_gc_ == Thread::Current() &&
2133 enabled_) {
2134 DCHECK(collector_->gc_grays_immune_objects_);
2135 collector_->gc_grays_immune_objects_ = false;
2136 }
2137 }
2138
2139 private:
2140 ConcurrentCopying* const collector_;
2141 bool enabled_;
2142};
2143
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002144// Fill the given memory block with a dummy object. Used to fill in a
2145// copy of objects that was lost in race.
2146void ConcurrentCopying::FillWithDummyObject(mirror::Object* dummy_obj, size_t byte_size) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002147 // GC doesn't gray immune objects while scanning immune objects. But we need to trigger the read
2148 // barriers here because we need the updated reference to the int array class, etc. Temporary set
2149 // gc_grays_immune_objects_ to true so that we won't cause a DCHECK failure in MarkImmuneSpace().
2150 ScopedGcGraysImmuneObjects scoped_gc_gray_immune_objects(this);
Roland Levillain14d90572015-07-16 10:52:26 +01002151 CHECK_ALIGNED(byte_size, kObjectAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002152 memset(dummy_obj, 0, byte_size);
Mathieu Chartierd6636d32016-07-28 11:02:38 -07002153 // Avoid going through read barrier for since kDisallowReadBarrierDuringScan may be enabled.
2154 // Explicitly mark to make sure to get an object in the to-space.
2155 mirror::Class* int_array_class = down_cast<mirror::Class*>(
2156 Mark(mirror::IntArray::GetArrayClass<kWithoutReadBarrier>()));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002157 CHECK(int_array_class != nullptr);
Andreas Gampe6c578712017-10-19 13:00:34 -07002158 if (ReadBarrier::kEnableToSpaceInvariantChecks) {
2159 AssertToSpaceInvariant(nullptr, MemberOffset(0), int_array_class);
2160 }
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07002161 size_t component_size = int_array_class->GetComponentSize<kWithoutReadBarrier>();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002162 CHECK_EQ(component_size, sizeof(int32_t));
2163 size_t data_offset = mirror::Array::DataOffset(component_size).SizeValue();
2164 if (data_offset > byte_size) {
2165 // An int array is too big. Use java.lang.Object.
Mathieu Chartier9aef9922017-04-23 13:53:50 -07002166 CHECK(java_lang_Object_ != nullptr);
Andreas Gampe6c578712017-10-19 13:00:34 -07002167 if (ReadBarrier::kEnableToSpaceInvariantChecks) {
2168 AssertToSpaceInvariant(nullptr, MemberOffset(0), java_lang_Object_);
2169 }
Mathieu Chartier3ed8ec12017-04-20 19:28:54 -07002170 CHECK_EQ(byte_size, (java_lang_Object_->GetObjectSize<kVerifyNone, kWithoutReadBarrier>()));
2171 dummy_obj->SetClass(java_lang_Object_);
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07002172 CHECK_EQ(byte_size, (dummy_obj->SizeOf<kVerifyNone>()));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002173 } else {
2174 // Use an int array.
2175 dummy_obj->SetClass(int_array_class);
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07002176 CHECK((dummy_obj->IsArrayInstance<kVerifyNone, kWithoutReadBarrier>()));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002177 int32_t length = (byte_size - data_offset) / component_size;
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07002178 mirror::Array* dummy_arr = dummy_obj->AsArray<kVerifyNone, kWithoutReadBarrier>();
2179 dummy_arr->SetLength(length);
2180 CHECK_EQ(dummy_arr->GetLength(), length)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002181 << "byte_size=" << byte_size << " length=" << length
2182 << " component_size=" << component_size << " data_offset=" << data_offset;
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07002183 CHECK_EQ(byte_size, (dummy_obj->SizeOf<kVerifyNone>()))
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002184 << "byte_size=" << byte_size << " length=" << length
2185 << " component_size=" << component_size << " data_offset=" << data_offset;
2186 }
2187}
2188
2189// Reuse the memory blocks that were copy of objects that were lost in race.
2190mirror::Object* ConcurrentCopying::AllocateInSkippedBlock(size_t alloc_size) {
2191 // Try to reuse the blocks that were unused due to CAS failures.
Roland Levillain14d90572015-07-16 10:52:26 +01002192 CHECK_ALIGNED(alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002193 Thread* self = Thread::Current();
2194 size_t min_object_size = RoundUp(sizeof(mirror::Object), space::RegionSpace::kAlignment);
Mathieu Chartierd6636d32016-07-28 11:02:38 -07002195 size_t byte_size;
2196 uint8_t* addr;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002197 {
Mathieu Chartierd6636d32016-07-28 11:02:38 -07002198 MutexLock mu(self, skipped_blocks_lock_);
2199 auto it = skipped_blocks_map_.lower_bound(alloc_size);
2200 if (it == skipped_blocks_map_.end()) {
2201 // Not found.
2202 return nullptr;
2203 }
2204 byte_size = it->first;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002205 CHECK_GE(byte_size, alloc_size);
2206 if (byte_size > alloc_size && byte_size - alloc_size < min_object_size) {
2207 // If remainder would be too small for a dummy object, retry with a larger request size.
2208 it = skipped_blocks_map_.lower_bound(alloc_size + min_object_size);
2209 if (it == skipped_blocks_map_.end()) {
2210 // Not found.
2211 return nullptr;
2212 }
Roland Levillain14d90572015-07-16 10:52:26 +01002213 CHECK_ALIGNED(it->first - alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002214 CHECK_GE(it->first - alloc_size, min_object_size)
2215 << "byte_size=" << byte_size << " it->first=" << it->first << " alloc_size=" << alloc_size;
2216 }
Mathieu Chartierd6636d32016-07-28 11:02:38 -07002217 // Found a block.
2218 CHECK(it != skipped_blocks_map_.end());
2219 byte_size = it->first;
2220 addr = it->second;
2221 CHECK_GE(byte_size, alloc_size);
2222 CHECK(region_space_->IsInToSpace(reinterpret_cast<mirror::Object*>(addr)));
2223 CHECK_ALIGNED(byte_size, space::RegionSpace::kAlignment);
2224 if (kVerboseMode) {
2225 LOG(INFO) << "Reusing skipped bytes : " << reinterpret_cast<void*>(addr) << ", " << byte_size;
2226 }
2227 skipped_blocks_map_.erase(it);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002228 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002229 memset(addr, 0, byte_size);
2230 if (byte_size > alloc_size) {
2231 // Return the remainder to the map.
Roland Levillain14d90572015-07-16 10:52:26 +01002232 CHECK_ALIGNED(byte_size - alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002233 CHECK_GE(byte_size - alloc_size, min_object_size);
Mathieu Chartierd6636d32016-07-28 11:02:38 -07002234 // FillWithDummyObject may mark an object, avoid holding skipped_blocks_lock_ to prevent lock
2235 // violation and possible deadlock. The deadlock case is a recursive case:
2236 // FillWithDummyObject -> IntArray::GetArrayClass -> Mark -> Copy -> AllocateInSkippedBlock.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002237 FillWithDummyObject(reinterpret_cast<mirror::Object*>(addr + alloc_size),
2238 byte_size - alloc_size);
2239 CHECK(region_space_->IsInToSpace(reinterpret_cast<mirror::Object*>(addr + alloc_size)));
Mathieu Chartierd6636d32016-07-28 11:02:38 -07002240 {
2241 MutexLock mu(self, skipped_blocks_lock_);
2242 skipped_blocks_map_.insert(std::make_pair(byte_size - alloc_size, addr + alloc_size));
2243 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002244 }
2245 return reinterpret_cast<mirror::Object*>(addr);
2246}
2247
Mathieu Chartieref496d92017-04-28 18:58:59 -07002248mirror::Object* ConcurrentCopying::Copy(mirror::Object* from_ref,
2249 mirror::Object* holder,
2250 MemberOffset offset) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002251 DCHECK(region_space_->IsInFromSpace(from_ref));
Mathieu Chartieref496d92017-04-28 18:58:59 -07002252 // If the class pointer is null, the object is invalid. This could occur for a dangling pointer
2253 // from a previous GC that is either inside or outside the allocated region.
2254 mirror::Class* klass = from_ref->GetClass<kVerifyNone, kWithoutReadBarrier>();
2255 if (UNLIKELY(klass == nullptr)) {
2256 heap_->GetVerification()->LogHeapCorruption(holder, offset, from_ref, /* fatal */ true);
2257 }
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07002258 // There must not be a read barrier to avoid nested RB that might violate the to-space invariant.
2259 // Note that from_ref is a from space ref so the SizeOf() call will access the from-space meta
2260 // objects, but it's ok and necessary.
2261 size_t obj_size = from_ref->SizeOf<kDefaultVerifyFlags>();
Nicolas Geoffray4b361a82017-07-06 15:30:10 +01002262 size_t region_space_alloc_size = (obj_size <= space::RegionSpace::kRegionSize)
2263 ? RoundUp(obj_size, space::RegionSpace::kAlignment)
2264 : RoundUp(obj_size, space::RegionSpace::kRegionSize);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002265 size_t region_space_bytes_allocated = 0U;
2266 size_t non_moving_space_bytes_allocated = 0U;
2267 size_t bytes_allocated = 0U;
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07002268 size_t dummy;
Lokesh Gidrab4f15412018-01-05 18:29:34 -08002269 mirror::Object* to_ref = region_space_->AllocNonvirtual</*kForEvac*/ true>(
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07002270 region_space_alloc_size, &region_space_bytes_allocated, nullptr, &dummy);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002271 bytes_allocated = region_space_bytes_allocated;
2272 if (to_ref != nullptr) {
2273 DCHECK_EQ(region_space_alloc_size, region_space_bytes_allocated);
2274 }
2275 bool fall_back_to_non_moving = false;
2276 if (UNLIKELY(to_ref == nullptr)) {
2277 // Failed to allocate in the region space. Try the skipped blocks.
2278 to_ref = AllocateInSkippedBlock(region_space_alloc_size);
2279 if (to_ref != nullptr) {
2280 // Succeeded to allocate in a skipped block.
2281 if (heap_->use_tlab_) {
2282 // This is necessary for the tlab case as it's not accounted in the space.
2283 region_space_->RecordAlloc(to_ref);
2284 }
2285 bytes_allocated = region_space_alloc_size;
2286 } else {
2287 // Fall back to the non-moving space.
2288 fall_back_to_non_moving = true;
2289 if (kVerboseMode) {
2290 LOG(INFO) << "Out of memory in the to-space. Fall back to non-moving. skipped_bytes="
2291 << to_space_bytes_skipped_.LoadSequentiallyConsistent()
2292 << " skipped_objects=" << to_space_objects_skipped_.LoadSequentiallyConsistent();
2293 }
2294 fall_back_to_non_moving = true;
2295 to_ref = heap_->non_moving_space_->Alloc(Thread::Current(), obj_size,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07002296 &non_moving_space_bytes_allocated, nullptr, &dummy);
Mathieu Chartierb01335c2017-03-22 13:15:01 -07002297 if (UNLIKELY(to_ref == nullptr)) {
2298 LOG(FATAL_WITHOUT_ABORT) << "Fall-back non-moving space allocation failed for a "
2299 << obj_size << " byte object in region type "
2300 << region_space_->GetRegionType(from_ref);
2301 LOG(FATAL) << "Object address=" << from_ref << " type=" << from_ref->PrettyTypeOf();
2302 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002303 bytes_allocated = non_moving_space_bytes_allocated;
2304 // Mark it in the mark bitmap.
2305 accounting::ContinuousSpaceBitmap* mark_bitmap =
2306 heap_mark_bitmap_->GetContinuousSpaceBitmap(to_ref);
2307 CHECK(mark_bitmap != nullptr);
2308 CHECK(!mark_bitmap->AtomicTestAndSet(to_ref));
2309 }
2310 }
2311 DCHECK(to_ref != nullptr);
2312
Mathieu Chartierd818adb2016-09-15 13:12:47 -07002313 // Copy the object excluding the lock word since that is handled in the loop.
Mathieu Chartieref496d92017-04-28 18:58:59 -07002314 to_ref->SetClass(klass);
Mathieu Chartierd818adb2016-09-15 13:12:47 -07002315 const size_t kObjectHeaderSize = sizeof(mirror::Object);
2316 DCHECK_GE(obj_size, kObjectHeaderSize);
2317 static_assert(kObjectHeaderSize == sizeof(mirror::HeapReference<mirror::Class>) +
2318 sizeof(LockWord),
2319 "Object header size does not match");
2320 // Memcpy can tear for words since it may do byte copy. It is only safe to do this since the
2321 // object in the from space is immutable other than the lock word. b/31423258
2322 memcpy(reinterpret_cast<uint8_t*>(to_ref) + kObjectHeaderSize,
2323 reinterpret_cast<const uint8_t*>(from_ref) + kObjectHeaderSize,
2324 obj_size - kObjectHeaderSize);
2325
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002326 // Attempt to install the forward pointer. This is in a loop as the
2327 // lock word atomic write can fail.
2328 while (true) {
Mathieu Chartierd818adb2016-09-15 13:12:47 -07002329 LockWord old_lock_word = from_ref->GetLockWord(false);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002330
2331 if (old_lock_word.GetState() == LockWord::kForwardingAddress) {
2332 // Lost the race. Another thread (either GC or mutator) stored
2333 // the forwarding pointer first. Make the lost copy (to_ref)
2334 // look like a valid but dead (dummy) object and keep it for
2335 // future reuse.
2336 FillWithDummyObject(to_ref, bytes_allocated);
2337 if (!fall_back_to_non_moving) {
2338 DCHECK(region_space_->IsInToSpace(to_ref));
2339 if (bytes_allocated > space::RegionSpace::kRegionSize) {
2340 // Free the large alloc.
Lokesh Gidrab4f15412018-01-05 18:29:34 -08002341 region_space_->FreeLarge</*kForEvac*/ true>(to_ref, bytes_allocated);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002342 } else {
2343 // Record the lost copy for later reuse.
2344 heap_->num_bytes_allocated_.FetchAndAddSequentiallyConsistent(bytes_allocated);
2345 to_space_bytes_skipped_.FetchAndAddSequentiallyConsistent(bytes_allocated);
2346 to_space_objects_skipped_.FetchAndAddSequentiallyConsistent(1);
2347 MutexLock mu(Thread::Current(), skipped_blocks_lock_);
2348 skipped_blocks_map_.insert(std::make_pair(bytes_allocated,
2349 reinterpret_cast<uint8_t*>(to_ref)));
2350 }
2351 } else {
2352 DCHECK(heap_->non_moving_space_->HasAddress(to_ref));
2353 DCHECK_EQ(bytes_allocated, non_moving_space_bytes_allocated);
2354 // Free the non-moving-space chunk.
2355 accounting::ContinuousSpaceBitmap* mark_bitmap =
2356 heap_mark_bitmap_->GetContinuousSpaceBitmap(to_ref);
2357 CHECK(mark_bitmap != nullptr);
2358 CHECK(mark_bitmap->Clear(to_ref));
2359 heap_->non_moving_space_->Free(Thread::Current(), to_ref);
2360 }
2361
2362 // Get the winner's forward ptr.
2363 mirror::Object* lost_fwd_ptr = to_ref;
2364 to_ref = reinterpret_cast<mirror::Object*>(old_lock_word.ForwardingAddress());
2365 CHECK(to_ref != nullptr);
2366 CHECK_NE(to_ref, lost_fwd_ptr);
Mathieu Chartierdfcd6f42016-09-13 10:02:48 -07002367 CHECK(region_space_->IsInToSpace(to_ref) || heap_->non_moving_space_->HasAddress(to_ref))
2368 << "to_ref=" << to_ref << " " << heap_->DumpSpaces();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002369 CHECK_NE(to_ref->GetLockWord(false).GetState(), LockWord::kForwardingAddress);
2370 return to_ref;
2371 }
2372
Mathieu Chartierd818adb2016-09-15 13:12:47 -07002373 // Copy the old lock word over since we did not copy it yet.
2374 to_ref->SetLockWord(old_lock_word, false);
Hiroshi Yamauchi60f63f52015-04-23 16:12:40 -07002375 // Set the gray ptr.
2376 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002377 to_ref->SetReadBarrierState(ReadBarrier::GrayState());
Hiroshi Yamauchi60f63f52015-04-23 16:12:40 -07002378 }
2379
Mathieu Chartiera8131262016-11-29 17:55:19 -08002380 // Do a fence to prevent the field CAS in ConcurrentCopying::Process from possibly reordering
2381 // before the object copy.
2382 QuasiAtomic::ThreadFenceRelease();
2383
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002384 LockWord new_lock_word = LockWord::FromForwardingAddress(reinterpret_cast<size_t>(to_ref));
2385
2386 // Try to atomically write the fwd ptr.
Mathieu Chartiera8131262016-11-29 17:55:19 -08002387 bool success = from_ref->CasLockWordWeakRelaxed(old_lock_word, new_lock_word);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002388 if (LIKELY(success)) {
2389 // The CAS succeeded.
Mathieu Chartiera8131262016-11-29 17:55:19 -08002390 objects_moved_.FetchAndAddRelaxed(1);
2391 bytes_moved_.FetchAndAddRelaxed(region_space_alloc_size);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002392 if (LIKELY(!fall_back_to_non_moving)) {
2393 DCHECK(region_space_->IsInToSpace(to_ref));
2394 } else {
2395 DCHECK(heap_->non_moving_space_->HasAddress(to_ref));
2396 DCHECK_EQ(bytes_allocated, non_moving_space_bytes_allocated);
2397 }
2398 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002399 DCHECK(to_ref->GetReadBarrierState() == ReadBarrier::GrayState());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002400 }
2401 DCHECK(GetFwdPtr(from_ref) == to_ref);
2402 CHECK_NE(to_ref->GetLockWord(false).GetState(), LockWord::kForwardingAddress);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002403 PushOntoMarkStack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002404 return to_ref;
2405 } else {
2406 // The CAS failed. It may have lost the race or may have failed
2407 // due to monitor/hashcode ops. Either way, retry.
2408 }
2409 }
2410}
2411
2412mirror::Object* ConcurrentCopying::IsMarked(mirror::Object* from_ref) {
2413 DCHECK(from_ref != nullptr);
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08002414 space::RegionSpace::RegionType rtype = region_space_->GetRegionType(from_ref);
2415 if (rtype == space::RegionSpace::RegionType::kRegionTypeToSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002416 // It's already marked.
2417 return from_ref;
2418 }
2419 mirror::Object* to_ref;
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08002420 if (rtype == space::RegionSpace::RegionType::kRegionTypeFromSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002421 to_ref = GetFwdPtr(from_ref);
2422 DCHECK(to_ref == nullptr || region_space_->IsInToSpace(to_ref) ||
2423 heap_->non_moving_space_->HasAddress(to_ref))
2424 << "from_ref=" << from_ref << " to_ref=" << to_ref;
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08002425 } else if (rtype == space::RegionSpace::RegionType::kRegionTypeUnevacFromSpace) {
Mathieu Chartierc381c362016-08-23 13:27:53 -07002426 if (IsMarkedInUnevacFromSpace(from_ref)) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002427 to_ref = from_ref;
2428 } else {
2429 to_ref = nullptr;
2430 }
2431 } else {
2432 // from_ref is in a non-moving space.
Mathieu Chartier763a31e2015-11-16 16:05:55 -08002433 if (immune_spaces_.ContainsObject(from_ref)) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002434 // An immune object is alive.
2435 to_ref = from_ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002436 } else {
2437 // Non-immune non-moving space. Use the mark bitmap.
2438 accounting::ContinuousSpaceBitmap* mark_bitmap =
2439 heap_mark_bitmap_->GetContinuousSpaceBitmap(from_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002440 bool is_los = mark_bitmap == nullptr;
2441 if (!is_los && mark_bitmap->Test(from_ref)) {
2442 // Already marked.
2443 to_ref = from_ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002444 } else {
Mathieu Chartier47863bb2017-08-04 11:30:27 -07002445 accounting::LargeObjectBitmap* los_bitmap =
2446 heap_mark_bitmap_->GetLargeObjectBitmap(from_ref);
2447 // We may not have a large object space for dex2oat, don't assume it exists.
2448 if (los_bitmap == nullptr) {
2449 CHECK(heap_->GetLargeObjectsSpace() == nullptr)
2450 << "LOS bitmap covers the entire address range " << from_ref
2451 << " " << heap_->DumpSpaces();
2452 }
2453 if (los_bitmap != nullptr && is_los && los_bitmap->Test(from_ref)) {
2454 // Already marked in LOS.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002455 to_ref = from_ref;
2456 } else {
2457 // Not marked.
Mathieu Chartier47863bb2017-08-04 11:30:27 -07002458 if (IsOnAllocStack(from_ref)) {
2459 // If on the allocation stack, it's considered marked.
2460 to_ref = from_ref;
2461 } else {
2462 // Not marked.
2463 to_ref = nullptr;
2464 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002465 }
2466 }
2467 }
2468 }
2469 return to_ref;
2470}
2471
2472bool ConcurrentCopying::IsOnAllocStack(mirror::Object* ref) {
Hans Boehmcc55e1d2017-07-27 15:28:07 -07002473 // TODO: Explain why this is here. What release operation does it pair with?
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002474 QuasiAtomic::ThreadFenceAcquire();
2475 accounting::ObjectStack* alloc_stack = GetAllocationStack();
Mathieu Chartiercb535da2015-01-23 13:50:03 -08002476 return alloc_stack->Contains(ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002477}
2478
Mathieu Chartier1ca68902017-04-18 11:26:22 -07002479mirror::Object* ConcurrentCopying::MarkNonMoving(mirror::Object* ref,
2480 mirror::Object* holder,
2481 MemberOffset offset) {
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002482 // ref is in a non-moving space (from_ref == to_ref).
2483 DCHECK(!region_space_->HasAddress(ref)) << ref;
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002484 DCHECK(!immune_spaces_.ContainsObject(ref));
2485 // Use the mark bitmap.
2486 accounting::ContinuousSpaceBitmap* mark_bitmap =
2487 heap_mark_bitmap_->GetContinuousSpaceBitmap(ref);
2488 accounting::LargeObjectBitmap* los_bitmap =
2489 heap_mark_bitmap_->GetLargeObjectBitmap(ref);
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002490 bool is_los = mark_bitmap == nullptr;
2491 if (!is_los && mark_bitmap->Test(ref)) {
2492 // Already marked.
2493 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002494 DCHECK(ref->GetReadBarrierState() == ReadBarrier::GrayState() ||
2495 ref->GetReadBarrierState() == ReadBarrier::WhiteState());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002496 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002497 } else if (is_los && los_bitmap->Test(ref)) {
2498 // Already marked in LOS.
2499 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002500 DCHECK(ref->GetReadBarrierState() == ReadBarrier::GrayState() ||
2501 ref->GetReadBarrierState() == ReadBarrier::WhiteState());
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002502 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002503 } else {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002504 // Not marked.
2505 if (IsOnAllocStack(ref)) {
2506 // If it's on the allocation stack, it's considered marked. Keep it white.
2507 // Objects on the allocation stack need not be marked.
2508 if (!is_los) {
2509 DCHECK(!mark_bitmap->Test(ref));
2510 } else {
2511 DCHECK(!los_bitmap->Test(ref));
Nicolas Geoffrayddeb1722016-06-28 08:25:59 +00002512 }
Nicolas Geoffrayddeb1722016-06-28 08:25:59 +00002513 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002514 DCHECK_EQ(ref->GetReadBarrierState(), ReadBarrier::WhiteState());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002515 }
2516 } else {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002517 // For the baker-style RB, we need to handle 'false-gray' cases. See the
2518 // kRegionTypeUnevacFromSpace-case comment in Mark().
2519 if (kUseBakerReadBarrier) {
2520 // Test the bitmap first to reduce the chance of false gray cases.
2521 if ((!is_los && mark_bitmap->Test(ref)) ||
2522 (is_los && los_bitmap->Test(ref))) {
2523 return ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002524 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002525 }
Mathieu Chartier1ca68902017-04-18 11:26:22 -07002526 if (is_los && !IsAligned<kPageSize>(ref)) {
2527 // Ref is a large object that is not aligned, it must be heap corruption. Dump data before
2528 // AtomicSetReadBarrierState since it will fault if the address is not valid.
Mathieu Chartieref496d92017-04-28 18:58:59 -07002529 heap_->GetVerification()->LogHeapCorruption(holder, offset, ref, /* fatal */ true);
Mathieu Chartier1ca68902017-04-18 11:26:22 -07002530 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002531 // Not marked or on the allocation stack. Try to mark it.
2532 // This may or may not succeed, which is ok.
2533 bool cas_success = false;
2534 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002535 cas_success = ref->AtomicSetReadBarrierState(ReadBarrier::WhiteState(),
2536 ReadBarrier::GrayState());
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002537 }
2538 if (!is_los && mark_bitmap->AtomicTestAndSet(ref)) {
2539 // Already marked.
2540 if (kUseBakerReadBarrier && cas_success &&
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002541 ref->GetReadBarrierState() == ReadBarrier::GrayState()) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002542 PushOntoFalseGrayStack(ref);
2543 }
2544 } else if (is_los && los_bitmap->AtomicTestAndSet(ref)) {
2545 // Already marked in LOS.
2546 if (kUseBakerReadBarrier && cas_success &&
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002547 ref->GetReadBarrierState() == ReadBarrier::GrayState()) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002548 PushOntoFalseGrayStack(ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002549 }
2550 } else {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002551 // Newly marked.
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08002552 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002553 DCHECK_EQ(ref->GetReadBarrierState(), ReadBarrier::GrayState());
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08002554 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002555 PushOntoMarkStack(ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002556 }
2557 }
2558 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002559 return ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002560}
2561
2562void ConcurrentCopying::FinishPhase() {
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -08002563 Thread* const self = Thread::Current();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002564 {
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -08002565 MutexLock mu(self, mark_stack_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002566 CHECK_EQ(pooled_mark_stacks_.size(), kMarkStackPoolSize);
2567 }
Mathieu Chartiera1467d02017-02-22 09:22:50 -08002568 // kVerifyNoMissingCardMarks relies on the region space cards not being cleared to avoid false
2569 // positives.
2570 if (!kVerifyNoMissingCardMarks) {
Mathieu Chartier6e6078a2016-10-24 15:45:41 -07002571 TimingLogger::ScopedTiming split("ClearRegionSpaceCards", GetTimings());
2572 // We do not currently use the region space cards at all, madvise them away to save ram.
2573 heap_->GetCardTable()->ClearCardRange(region_space_->Begin(), region_space_->Limit());
Mathieu Chartier6e6078a2016-10-24 15:45:41 -07002574 }
2575 {
2576 MutexLock mu(self, skipped_blocks_lock_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002577 skipped_blocks_map_.clear();
2578 }
Mathieu Chartier56fe2582016-07-14 13:30:03 -07002579 {
2580 ReaderMutexLock mu(self, *Locks::mutator_lock_);
Mathieu Chartier21328a12016-07-22 10:47:45 -07002581 {
2582 WriterMutexLock mu2(self, *Locks::heap_bitmap_lock_);
2583 heap_->ClearMarkedObjects();
2584 }
2585 if (kUseBakerReadBarrier && kFilterModUnionCards) {
2586 TimingLogger::ScopedTiming split("FilterModUnionCards", GetTimings());
2587 ReaderMutexLock mu2(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier21328a12016-07-22 10:47:45 -07002588 for (space::ContinuousSpace* space : immune_spaces_.GetSpaces()) {
2589 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
Mathieu Chartier6e6078a2016-10-24 15:45:41 -07002590 accounting::ModUnionTable* table = heap_->FindModUnionTableFromSpace(space);
Mathieu Chartier21328a12016-07-22 10:47:45 -07002591 // Filter out cards that don't need to be set.
2592 if (table != nullptr) {
2593 table->FilterCards();
2594 }
2595 }
2596 }
Mathieu Chartier36a270a2016-07-28 18:08:51 -07002597 if (kUseBakerReadBarrier) {
2598 TimingLogger::ScopedTiming split("EmptyRBMarkBitStack", GetTimings());
Mathieu Chartier6e6078a2016-10-24 15:45:41 -07002599 DCHECK(rb_mark_bit_stack_ != nullptr);
Mathieu Chartier36a270a2016-07-28 18:08:51 -07002600 const auto* limit = rb_mark_bit_stack_->End();
2601 for (StackReference<mirror::Object>* it = rb_mark_bit_stack_->Begin(); it != limit; ++it) {
2602 CHECK(it->AsMirrorPtr()->AtomicSetMarkBit(1, 0));
2603 }
2604 rb_mark_bit_stack_->Reset();
2605 }
Mathieu Chartier56fe2582016-07-14 13:30:03 -07002606 }
2607 if (measure_read_barrier_slow_path_) {
2608 MutexLock mu(self, rb_slow_path_histogram_lock_);
2609 rb_slow_path_time_histogram_.AdjustAndAddValue(rb_slow_path_ns_.LoadRelaxed());
2610 rb_slow_path_count_total_ += rb_slow_path_count_.LoadRelaxed();
2611 rb_slow_path_count_gc_total_ += rb_slow_path_count_gc_.LoadRelaxed();
2612 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002613}
2614
Hiroshi Yamauchi65f5f242016-12-19 11:44:47 -08002615bool ConcurrentCopying::IsNullOrMarkedHeapReference(mirror::HeapReference<mirror::Object>* field,
2616 bool do_atomic_update) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002617 mirror::Object* from_ref = field->AsMirrorPtr();
Hiroshi Yamauchi65f5f242016-12-19 11:44:47 -08002618 if (from_ref == nullptr) {
2619 return true;
2620 }
Mathieu Chartier97509952015-07-13 14:35:43 -07002621 mirror::Object* to_ref = IsMarked(from_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002622 if (to_ref == nullptr) {
2623 return false;
2624 }
2625 if (from_ref != to_ref) {
Hiroshi Yamauchi65f5f242016-12-19 11:44:47 -08002626 if (do_atomic_update) {
2627 do {
2628 if (field->AsMirrorPtr() != from_ref) {
2629 // Concurrently overwritten by a mutator.
2630 break;
2631 }
2632 } while (!field->CasWeakRelaxed(from_ref, to_ref));
2633 } else {
Hans Boehmcc55e1d2017-07-27 15:28:07 -07002634 // TODO: Why is this seq_cst when the above is relaxed? Document memory ordering.
2635 field->Assign</* kIsVolatile */ true>(to_ref);
Hiroshi Yamauchi65f5f242016-12-19 11:44:47 -08002636 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002637 }
2638 return true;
2639}
2640
Mathieu Chartier97509952015-07-13 14:35:43 -07002641mirror::Object* ConcurrentCopying::MarkObject(mirror::Object* from_ref) {
2642 return Mark(from_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002643}
2644
Mathieu Chartier31e88222016-10-14 18:43:19 -07002645void ConcurrentCopying::DelayReferenceReferent(ObjPtr<mirror::Class> klass,
2646 ObjPtr<mirror::Reference> reference) {
Mathieu Chartier97509952015-07-13 14:35:43 -07002647 heap_->GetReferenceProcessor()->DelayReferenceReferent(klass, reference, this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002648}
2649
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002650void ConcurrentCopying::ProcessReferences(Thread* self) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002651 TimingLogger::ScopedTiming split("ProcessReferences", GetTimings());
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002652 // 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 -08002653 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
2654 GetHeap()->GetReferenceProcessor()->ProcessReferences(
Mathieu Chartier97509952015-07-13 14:35:43 -07002655 true /*concurrent*/, GetTimings(), GetCurrentIteration()->GetClearSoftReferences(), this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002656}
2657
2658void ConcurrentCopying::RevokeAllThreadLocalBuffers() {
2659 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
2660 region_space_->RevokeAllThreadLocalBuffers();
2661}
2662
Mathieu Chartier56fe2582016-07-14 13:30:03 -07002663mirror::Object* ConcurrentCopying::MarkFromReadBarrierWithMeasurements(mirror::Object* from_ref) {
2664 if (Thread::Current() != thread_running_gc_) {
2665 rb_slow_path_count_.FetchAndAddRelaxed(1u);
2666 } else {
2667 rb_slow_path_count_gc_.FetchAndAddRelaxed(1u);
2668 }
2669 ScopedTrace tr(__FUNCTION__);
2670 const uint64_t start_time = measure_read_barrier_slow_path_ ? NanoTime() : 0u;
2671 mirror::Object* ret = Mark(from_ref);
2672 if (measure_read_barrier_slow_path_) {
2673 rb_slow_path_ns_.FetchAndAddRelaxed(NanoTime() - start_time);
2674 }
2675 return ret;
2676}
2677
2678void ConcurrentCopying::DumpPerformanceInfo(std::ostream& os) {
2679 GarbageCollector::DumpPerformanceInfo(os);
2680 MutexLock mu(Thread::Current(), rb_slow_path_histogram_lock_);
2681 if (rb_slow_path_time_histogram_.SampleSize() > 0) {
2682 Histogram<uint64_t>::CumulativeData cumulative_data;
2683 rb_slow_path_time_histogram_.CreateHistogram(&cumulative_data);
2684 rb_slow_path_time_histogram_.PrintConfidenceIntervals(os, 0.99, cumulative_data);
2685 }
2686 if (rb_slow_path_count_total_ > 0) {
2687 os << "Slow path count " << rb_slow_path_count_total_ << "\n";
2688 }
2689 if (rb_slow_path_count_gc_total_ > 0) {
2690 os << "GC slow path count " << rb_slow_path_count_gc_total_ << "\n";
2691 }
Mathieu Chartiercca44a02016-08-17 10:07:29 -07002692 os << "Cumulative bytes moved " << cumulative_bytes_moved_.LoadRelaxed() << "\n";
2693 os << "Cumulative objects moved " << cumulative_objects_moved_.LoadRelaxed() << "\n";
Lokesh Gidra29895822017-12-15 15:37:40 -08002694
2695 os << "Peak regions allocated "
Lokesh Gidrab4f15412018-01-05 18:29:34 -08002696 << region_space_->GetMaxPeakNumNonFreeRegions() << " ("
2697 << PrettySize(region_space_->GetMaxPeakNumNonFreeRegions() * space::RegionSpace::kRegionSize)
2698 << ") / " << region_space_->GetNumRegions() / 2 << " ("
2699 << PrettySize(region_space_->GetNumRegions() * space::RegionSpace::kRegionSize / 2)
Lokesh Gidra29895822017-12-15 15:37:40 -08002700 << ")\n";
Mathieu Chartier56fe2582016-07-14 13:30:03 -07002701}
2702
Hiroshi Yamauchid5307ec2014-03-27 21:07:51 -07002703} // namespace collector
2704} // namespace gc
2705} // namespace art