blob: 7beff960cc3b8499d4f56f93d64410f3bcb669d1 [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 Chartier21328a12016-07-22 10:47:45 -0700763 CHECK(success);
764 }
765 } else {
766 collector_->ScanImmuneObject(obj);
767 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700768 }
769
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700770 static void Callback(mirror::Object* obj, void* arg) REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi5408f232016-07-29 15:07:05 -0700771 reinterpret_cast<ImmuneSpaceScanObjVisitor*>(arg)->operator()(obj);
772 }
773
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700774 private:
775 ConcurrentCopying* const collector_;
776};
777
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800778// Concurrently mark roots that are guarded by read barriers and process the mark stack.
779void ConcurrentCopying::MarkingPhase() {
780 TimingLogger::ScopedTiming split("MarkingPhase", GetTimings());
781 if (kVerboseMode) {
782 LOG(INFO) << "GC MarkingPhase";
783 }
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -0700784 Thread* self = Thread::Current();
785 if (kIsDebugBuild) {
786 MutexLock mu(self, *Locks::thread_list_lock_);
787 CHECK(weak_ref_access_enabled_);
788 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700789
790 // Scan immune spaces.
791 // Update all the fields in the immune spaces first without graying the objects so that we
792 // minimize dirty pages in the immune spaces. Note mutators can concurrently access and gray some
793 // of the objects.
794 if (kUseBakerReadBarrier) {
795 gc_grays_immune_objects_ = false;
Hiroshi Yamauchi16292fc2016-06-20 20:23:34 -0700796 }
Mathieu Chartier21328a12016-07-22 10:47:45 -0700797 {
798 TimingLogger::ScopedTiming split2("ScanImmuneSpaces", GetTimings());
799 for (auto& space : immune_spaces_.GetSpaces()) {
800 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
801 accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
Hiroshi Yamauchi5408f232016-07-29 15:07:05 -0700802 accounting::ModUnionTable* table = heap_->FindModUnionTableFromSpace(space);
Mathieu Chartier21328a12016-07-22 10:47:45 -0700803 ImmuneSpaceScanObjVisitor visitor(this);
Hiroshi Yamauchi5408f232016-07-29 15:07:05 -0700804 if (kUseBakerReadBarrier && kGrayDirtyImmuneObjects && table != nullptr) {
805 table->VisitObjects(ImmuneSpaceScanObjVisitor::Callback, &visitor);
806 } else {
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700807 // TODO: Scan only the aged cards.
Hiroshi Yamauchi5408f232016-07-29 15:07:05 -0700808 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()),
809 reinterpret_cast<uintptr_t>(space->Limit()),
810 visitor);
811 }
Mathieu Chartier21328a12016-07-22 10:47:45 -0700812 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700813 }
814 if (kUseBakerReadBarrier) {
815 // This release fence makes the field updates in the above loop visible before allowing mutator
816 // getting access to immune objects without graying it first.
817 updated_all_immune_objects_.StoreRelease(true);
818 // Now whiten immune objects concurrently accessed and grayed by mutators. We can't do this in
819 // the above loop because we would incorrectly disable the read barrier by whitening an object
820 // which may point to an unscanned, white object, breaking the to-space invariant.
821 //
822 // Make sure no mutators are in the middle of marking an immune object before whitening immune
823 // objects.
824 IssueEmptyCheckpoint();
825 MutexLock mu(Thread::Current(), immune_gray_stack_lock_);
826 if (kVerboseMode) {
827 LOG(INFO) << "immune gray stack size=" << immune_gray_stack_.size();
828 }
829 for (mirror::Object* obj : immune_gray_stack_) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700830 DCHECK(obj->GetReadBarrierState() == ReadBarrier::GrayState());
831 bool success = obj->AtomicSetReadBarrierState(ReadBarrier::GrayState(),
832 ReadBarrier::WhiteState());
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700833 DCHECK(success);
834 }
835 immune_gray_stack_.clear();
836 }
837
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800838 {
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -0700839 TimingLogger::ScopedTiming split2("VisitConcurrentRoots", GetTimings());
840 Runtime::Current()->VisitConcurrentRoots(this, kVisitRootFlagAllRoots);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800841 }
842 {
843 // TODO: don't visit the transaction roots if it's not active.
844 TimingLogger::ScopedTiming split5("VisitNonThreadRoots", GetTimings());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700845 Runtime::Current()->VisitNonThreadRoots(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800846 }
847
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800848 {
Mathieu Chartiera6b1ead2015-10-06 10:32:38 -0700849 TimingLogger::ScopedTiming split7("ProcessMarkStack", GetTimings());
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700850 // We transition through three mark stack modes (thread-local, shared, GC-exclusive). The
851 // primary reasons are the fact that we need to use a checkpoint to process thread-local mark
852 // stacks, but after we disable weak refs accesses, we can't use a checkpoint due to a deadlock
853 // issue because running threads potentially blocking at WaitHoldingLocks, and that once we
854 // reach the point where we process weak references, we can avoid using a lock when accessing
855 // the GC mark stack, which makes mark stack processing more efficient.
856
857 // Process the mark stack once in the thread local stack mode. This marks most of the live
858 // objects, aside from weak ref accesses with read barriers (Reference::GetReferent() and system
859 // weaks) that may happen concurrently while we processing the mark stack and newly mark/gray
860 // objects and push refs on the mark stack.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800861 ProcessMarkStack();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700862 // Switch to the shared mark stack mode. That is, revoke and process thread-local mark stacks
863 // for the last time before transitioning to the shared mark stack mode, which would process new
864 // refs that may have been concurrently pushed onto the mark stack during the ProcessMarkStack()
865 // call above. At the same time, disable weak ref accesses using a per-thread flag. It's
866 // important to do these together in a single checkpoint so that we can ensure that mutators
867 // won't newly gray objects and push new refs onto the mark stack due to weak ref accesses and
868 // mutators safely transition to the shared mark stack mode (without leaving unprocessed refs on
869 // the thread-local mark stacks), without a race. This is why we use a thread-local weak ref
870 // access flag Thread::tls32_.weak_ref_access_enabled_ instead of the global ones.
871 SwitchToSharedMarkStackMode();
872 CHECK(!self->GetWeakRefAccessEnabled());
873 // Now that weak refs accesses are disabled, once we exhaust the shared mark stack again here
874 // (which may be non-empty if there were refs found on thread-local mark stacks during the above
875 // SwitchToSharedMarkStackMode() call), we won't have new refs to process, that is, mutators
876 // (via read barriers) have no way to produce any more refs to process. Marking converges once
877 // before we process weak refs below.
878 ProcessMarkStack();
879 CheckEmptyMarkStack();
880 // Switch to the GC exclusive mark stack mode so that we can process the mark stack without a
881 // lock from this point on.
882 SwitchToGcExclusiveMarkStackMode();
883 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800884 if (kVerboseMode) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800885 LOG(INFO) << "ProcessReferences";
886 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700887 // Process weak references. This may produce new refs to process and have them processed via
Mathieu Chartier97509952015-07-13 14:35:43 -0700888 // ProcessMarkStack (in the GC exclusive mark stack mode).
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700889 ProcessReferences(self);
890 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800891 if (kVerboseMode) {
892 LOG(INFO) << "SweepSystemWeaks";
893 }
894 SweepSystemWeaks(self);
895 if (kVerboseMode) {
896 LOG(INFO) << "SweepSystemWeaks done";
897 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700898 // Process the mark stack here one last time because the above SweepSystemWeaks() call may have
899 // marked some objects (strings alive) as hash_set::Erase() can call the hash function for
900 // arbitrary elements in the weak intern table in InternTable::Table::SweepWeaks().
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800901 ProcessMarkStack();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700902 CheckEmptyMarkStack();
903 // Re-enable weak ref accesses.
904 ReenableWeakRefAccess(self);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -0700905 // Free data for class loaders that we unloaded.
906 Runtime::Current()->GetClassLinker()->CleanupClassLoaders();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700907 // Marking is done. Disable marking.
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700908 DisableMarking();
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800909 if (kUseBakerReadBarrier) {
910 ProcessFalseGrayStack();
911 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700912 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800913 }
914
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -0700915 if (kIsDebugBuild) {
916 MutexLock mu(self, *Locks::thread_list_lock_);
917 CHECK(weak_ref_access_enabled_);
918 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800919 if (kVerboseMode) {
920 LOG(INFO) << "GC end of MarkingPhase";
921 }
922}
923
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700924void ConcurrentCopying::ReenableWeakRefAccess(Thread* self) {
925 if (kVerboseMode) {
926 LOG(INFO) << "ReenableWeakRefAccess";
927 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700928 // Iterate all threads (don't need to or can't use a checkpoint) and re-enable weak ref access.
929 {
930 MutexLock mu(self, *Locks::thread_list_lock_);
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -0700931 weak_ref_access_enabled_ = true; // This is for new threads.
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700932 std::list<Thread*> thread_list = Runtime::Current()->GetThreadList()->GetList();
933 for (Thread* thread : thread_list) {
934 thread->SetWeakRefAccessEnabled(true);
935 }
936 }
937 // Unblock blocking threads.
938 GetHeap()->GetReferenceProcessor()->BroadcastForSlowPath(self);
939 Runtime::Current()->BroadcastForNewSystemWeaks();
940}
941
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700942class ConcurrentCopying::DisableMarkingCheckpoint : public Closure {
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700943 public:
944 explicit DisableMarkingCheckpoint(ConcurrentCopying* concurrent_copying)
945 : concurrent_copying_(concurrent_copying) {
946 }
947
948 void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
949 // Note: self is not necessarily equal to thread since thread may be suspended.
950 Thread* self = Thread::Current();
951 DCHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
952 << thread->GetState() << " thread " << thread << " self " << self;
953 // Disable the thread-local is_gc_marking flag.
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -0700954 // Note a thread that has just started right before this checkpoint may have already this flag
955 // set to false, which is ok.
Mathieu Chartierfe814e82016-11-09 14:32:49 -0800956 thread->SetIsGcMarkingAndUpdateEntrypoints(false);
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700957 // If thread is a running mutator, then act on behalf of the garbage collector.
958 // See the code in ThreadList::RunCheckpoint.
Mathieu Chartier10d25082015-10-28 18:36:09 -0700959 concurrent_copying_->GetBarrier().Pass(self);
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700960 }
961
962 private:
963 ConcurrentCopying* const concurrent_copying_;
964};
965
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -0700966class ConcurrentCopying::DisableMarkingCallback : public Closure {
967 public:
968 explicit DisableMarkingCallback(ConcurrentCopying* concurrent_copying)
969 : concurrent_copying_(concurrent_copying) {
970 }
971
972 void Run(Thread* self ATTRIBUTE_UNUSED) OVERRIDE REQUIRES(Locks::thread_list_lock_) {
973 // This needs to run under the thread_list_lock_ critical section in ThreadList::RunCheckpoint()
974 // to avoid a race with ThreadList::Register().
975 CHECK(concurrent_copying_->is_marking_);
976 concurrent_copying_->is_marking_ = false;
Mathieu Chartiera9a4f5f2017-05-03 18:19:13 -0700977 if (kUseBakerReadBarrier && kGrayDirtyImmuneObjects) {
978 CHECK(concurrent_copying_->is_using_read_barrier_entrypoints_);
979 concurrent_copying_->is_using_read_barrier_entrypoints_ = false;
980 } else {
981 CHECK(!concurrent_copying_->is_using_read_barrier_entrypoints_);
982 }
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -0700983 }
984
985 private:
986 ConcurrentCopying* const concurrent_copying_;
987};
988
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700989void ConcurrentCopying::IssueDisableMarkingCheckpoint() {
990 Thread* self = Thread::Current();
991 DisableMarkingCheckpoint check_point(this);
992 ThreadList* thread_list = Runtime::Current()->GetThreadList();
993 gc_barrier_->Init(self, 0);
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -0700994 DisableMarkingCallback dmc(this);
995 size_t barrier_count = thread_list->RunCheckpoint(&check_point, &dmc);
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700996 // If there are no threads to wait which implies that all the checkpoint functions are finished,
997 // then no need to release the mutator lock.
998 if (barrier_count == 0) {
999 return;
1000 }
1001 // Release locks then wait for all mutator threads to pass the barrier.
1002 Locks::mutator_lock_->SharedUnlock(self);
1003 {
1004 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
1005 gc_barrier_->Increment(self, barrier_count);
1006 }
1007 Locks::mutator_lock_->SharedLock(self);
1008}
1009
1010void ConcurrentCopying::DisableMarking() {
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001011 // Use a checkpoint to turn off the global is_marking and the thread-local is_gc_marking flags and
1012 // to ensure no threads are still in the middle of a read barrier which may have a from-space ref
1013 // cached in a local variable.
Hiroshi Yamauchi00370822015-08-18 14:47:25 -07001014 IssueDisableMarkingCheckpoint();
1015 if (kUseTableLookupReadBarrier) {
1016 heap_->rb_table_->ClearAll();
1017 DCHECK(heap_->rb_table_->IsAllCleared());
1018 }
1019 is_mark_stack_push_disallowed_.StoreSequentiallyConsistent(1);
1020 mark_stack_mode_.StoreSequentiallyConsistent(kMarkStackModeOff);
1021}
1022
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001023void ConcurrentCopying::PushOntoFalseGrayStack(mirror::Object* ref) {
1024 CHECK(kUseBakerReadBarrier);
1025 DCHECK(ref != nullptr);
1026 MutexLock mu(Thread::Current(), mark_stack_lock_);
1027 false_gray_stack_.push_back(ref);
1028}
1029
1030void ConcurrentCopying::ProcessFalseGrayStack() {
1031 CHECK(kUseBakerReadBarrier);
1032 // Change the objects on the false gray stack from gray to white.
1033 MutexLock mu(Thread::Current(), mark_stack_lock_);
1034 for (mirror::Object* obj : false_gray_stack_) {
1035 DCHECK(IsMarked(obj));
1036 // The object could be white here if a thread got preempted after a success at the
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001037 // AtomicSetReadBarrierState in Mark(), GC started marking through it (but not finished so
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001038 // still gray), and the thread ran to register it onto the false gray stack.
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001039 if (obj->GetReadBarrierState() == ReadBarrier::GrayState()) {
1040 bool success = obj->AtomicSetReadBarrierState(ReadBarrier::GrayState(),
1041 ReadBarrier::WhiteState());
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001042 DCHECK(success);
1043 }
1044 }
1045 false_gray_stack_.clear();
1046}
1047
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001048void ConcurrentCopying::IssueEmptyCheckpoint() {
1049 Thread* self = Thread::Current();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001050 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001051 // Release locks then wait for all mutator threads to pass the barrier.
1052 Locks::mutator_lock_->SharedUnlock(self);
Hiroshi Yamauchia2224042017-02-08 16:35:45 -08001053 thread_list->RunEmptyCheckpoint();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001054 Locks::mutator_lock_->SharedLock(self);
1055}
1056
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -07001057void ConcurrentCopying::ExpandGcMarkStack() {
1058 DCHECK(gc_mark_stack_->IsFull());
1059 const size_t new_size = gc_mark_stack_->Capacity() * 2;
1060 std::vector<StackReference<mirror::Object>> temp(gc_mark_stack_->Begin(),
1061 gc_mark_stack_->End());
1062 gc_mark_stack_->Resize(new_size);
1063 for (auto& ref : temp) {
1064 gc_mark_stack_->PushBack(ref.AsMirrorPtr());
1065 }
1066 DCHECK(!gc_mark_stack_->IsFull());
1067}
1068
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001069void ConcurrentCopying::PushOntoMarkStack(mirror::Object* to_ref) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001070 CHECK_EQ(is_mark_stack_push_disallowed_.LoadRelaxed(), 0)
David Sehr709b0702016-10-13 09:12:37 -07001071 << " " << to_ref << " " << mirror::Object::PrettyTypeOf(to_ref);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001072 Thread* self = Thread::Current(); // TODO: pass self as an argument from call sites?
1073 CHECK(thread_running_gc_ != nullptr);
1074 MarkStackMode mark_stack_mode = mark_stack_mode_.LoadRelaxed();
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001075 if (LIKELY(mark_stack_mode == kMarkStackModeThreadLocal)) {
1076 if (LIKELY(self == thread_running_gc_)) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001077 // If GC-running thread, use the GC mark stack instead of a thread-local mark stack.
1078 CHECK(self->GetThreadLocalMarkStack() == nullptr);
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -07001079 if (UNLIKELY(gc_mark_stack_->IsFull())) {
1080 ExpandGcMarkStack();
1081 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001082 gc_mark_stack_->PushBack(to_ref);
1083 } else {
1084 // Otherwise, use a thread-local mark stack.
1085 accounting::AtomicStack<mirror::Object>* tl_mark_stack = self->GetThreadLocalMarkStack();
1086 if (UNLIKELY(tl_mark_stack == nullptr || tl_mark_stack->IsFull())) {
1087 MutexLock mu(self, mark_stack_lock_);
1088 // Get a new thread local mark stack.
1089 accounting::AtomicStack<mirror::Object>* new_tl_mark_stack;
1090 if (!pooled_mark_stacks_.empty()) {
1091 // Use a pooled mark stack.
1092 new_tl_mark_stack = pooled_mark_stacks_.back();
1093 pooled_mark_stacks_.pop_back();
1094 } else {
1095 // None pooled. Create a new one.
1096 new_tl_mark_stack =
1097 accounting::AtomicStack<mirror::Object>::Create(
1098 "thread local mark stack", 4 * KB, 4 * KB);
1099 }
1100 DCHECK(new_tl_mark_stack != nullptr);
1101 DCHECK(new_tl_mark_stack->IsEmpty());
1102 new_tl_mark_stack->PushBack(to_ref);
1103 self->SetThreadLocalMarkStack(new_tl_mark_stack);
1104 if (tl_mark_stack != nullptr) {
1105 // Store the old full stack into a vector.
1106 revoked_mark_stacks_.push_back(tl_mark_stack);
1107 }
1108 } else {
1109 tl_mark_stack->PushBack(to_ref);
1110 }
1111 }
1112 } else if (mark_stack_mode == kMarkStackModeShared) {
1113 // Access the shared GC mark stack with a lock.
1114 MutexLock mu(self, mark_stack_lock_);
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -07001115 if (UNLIKELY(gc_mark_stack_->IsFull())) {
1116 ExpandGcMarkStack();
1117 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001118 gc_mark_stack_->PushBack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001119 } else {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001120 CHECK_EQ(static_cast<uint32_t>(mark_stack_mode),
Hiroshi Yamauchifa755182015-09-30 20:12:11 -07001121 static_cast<uint32_t>(kMarkStackModeGcExclusive))
1122 << "ref=" << to_ref
1123 << " self->gc_marking=" << self->GetIsGcMarking()
1124 << " cc->is_marking=" << is_marking_;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001125 CHECK(self == thread_running_gc_)
1126 << "Only GC-running thread should access the mark stack "
1127 << "in the GC exclusive mark stack mode";
1128 // Access the GC mark stack without a lock.
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -07001129 if (UNLIKELY(gc_mark_stack_->IsFull())) {
1130 ExpandGcMarkStack();
1131 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001132 gc_mark_stack_->PushBack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001133 }
1134}
1135
1136accounting::ObjectStack* ConcurrentCopying::GetAllocationStack() {
1137 return heap_->allocation_stack_.get();
1138}
1139
1140accounting::ObjectStack* ConcurrentCopying::GetLiveStack() {
1141 return heap_->live_stack_.get();
1142}
1143
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001144// The following visitors are used to verify that there's no references to the from-space left after
1145// marking.
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001146class ConcurrentCopying::VerifyNoFromSpaceRefsVisitor : public SingleRootVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001147 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001148 explicit VerifyNoFromSpaceRefsVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001149 : collector_(collector) {}
1150
Mathieu Chartierbc632f02017-04-20 13:31:39 -07001151 void operator()(mirror::Object* ref,
1152 MemberOffset offset = MemberOffset(0),
1153 mirror::Object* holder = nullptr) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001154 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001155 if (ref == nullptr) {
1156 // OK.
1157 return;
1158 }
Mathieu Chartierbc632f02017-04-20 13:31:39 -07001159 collector_->AssertToSpaceInvariant(holder, offset, ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001160 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001161 CHECK_EQ(ref->GetReadBarrierState(), ReadBarrier::WhiteState())
David Sehr709b0702016-10-13 09:12:37 -07001162 << "Ref " << ref << " " << ref->PrettyTypeOf()
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001163 << " has non-white rb_state ";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001164 }
1165 }
1166
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001167 void VisitRoot(mirror::Object* root, const RootInfo& info ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001168 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001169 DCHECK(root != nullptr);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001170 operator()(root);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001171 }
1172
1173 private:
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001174 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001175};
1176
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001177class ConcurrentCopying::VerifyNoFromSpaceRefsFieldVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001178 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001179 explicit VerifyNoFromSpaceRefsFieldVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001180 : collector_(collector) {}
1181
Mathieu Chartier31e88222016-10-14 18:43:19 -07001182 void operator()(ObjPtr<mirror::Object> obj,
1183 MemberOffset offset,
1184 bool is_static ATTRIBUTE_UNUSED) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001185 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001186 mirror::Object* ref =
1187 obj->GetFieldObject<mirror::Object, kDefaultVerifyFlags, kWithoutReadBarrier>(offset);
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001188 VerifyNoFromSpaceRefsVisitor visitor(collector_);
Mathieu Chartierbc632f02017-04-20 13:31:39 -07001189 visitor(ref, offset, obj.Ptr());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001190 }
Mathieu Chartier31e88222016-10-14 18:43:19 -07001191 void operator()(ObjPtr<mirror::Class> klass,
1192 ObjPtr<mirror::Reference> ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001193 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001194 CHECK(klass->IsTypeOfReferenceClass());
1195 this->operator()(ref, mirror::Reference::ReferentOffset(), false);
1196 }
1197
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001198 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001199 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001200 if (!root->IsNull()) {
1201 VisitRoot(root);
1202 }
1203 }
1204
1205 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001206 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001207 VerifyNoFromSpaceRefsVisitor visitor(collector_);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001208 visitor(root->AsMirrorPtr());
1209 }
1210
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001211 private:
Mathieu Chartier97509952015-07-13 14:35:43 -07001212 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001213};
1214
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001215// Verify there's no from-space references left after the marking phase.
1216void ConcurrentCopying::VerifyNoFromSpaceReferences() {
1217 Thread* self = Thread::Current();
1218 DCHECK(Locks::mutator_lock_->IsExclusiveHeld(self));
Hiroshi Yamauchi00370822015-08-18 14:47:25 -07001219 // Verify all threads have is_gc_marking to be false
1220 {
1221 MutexLock mu(self, *Locks::thread_list_lock_);
1222 std::list<Thread*> thread_list = Runtime::Current()->GetThreadList()->GetList();
1223 for (Thread* thread : thread_list) {
1224 CHECK(!thread->GetIsGcMarking());
1225 }
1226 }
Andreas Gampe0c183382017-07-13 22:26:24 -07001227
1228 auto verify_no_from_space_refs_visitor = [&](mirror::Object* obj)
1229 REQUIRES_SHARED(Locks::mutator_lock_) {
1230 CHECK(obj != nullptr);
1231 space::RegionSpace* region_space = RegionSpace();
1232 CHECK(!region_space->IsInFromSpace(obj)) << "Scanning object " << obj << " in from space";
1233 VerifyNoFromSpaceRefsFieldVisitor visitor(this);
1234 obj->VisitReferences</*kVisitNativeRoots*/true, kDefaultVerifyFlags, kWithoutReadBarrier>(
1235 visitor,
1236 visitor);
1237 if (kUseBakerReadBarrier) {
1238 CHECK_EQ(obj->GetReadBarrierState(), ReadBarrier::WhiteState())
1239 << "obj=" << obj << " non-white rb_state " << obj->GetReadBarrierState();
1240 }
1241 };
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001242 // Roots.
1243 {
1244 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001245 VerifyNoFromSpaceRefsVisitor ref_visitor(this);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001246 Runtime::Current()->VisitRoots(&ref_visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001247 }
1248 // The to-space.
Andreas Gampe0c183382017-07-13 22:26:24 -07001249 region_space_->WalkToSpace(verify_no_from_space_refs_visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001250 // Non-moving spaces.
1251 {
1252 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Andreas Gampe0c183382017-07-13 22:26:24 -07001253 heap_->GetMarkBitmap()->Visit(verify_no_from_space_refs_visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001254 }
1255 // The alloc stack.
1256 {
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001257 VerifyNoFromSpaceRefsVisitor ref_visitor(this);
Mathieu Chartiercb535da2015-01-23 13:50:03 -08001258 for (auto* it = heap_->allocation_stack_->Begin(), *end = heap_->allocation_stack_->End();
1259 it < end; ++it) {
1260 mirror::Object* const obj = it->AsMirrorPtr();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001261 if (obj != nullptr && obj->GetClass() != nullptr) {
1262 // TODO: need to call this only if obj is alive?
1263 ref_visitor(obj);
Andreas Gampe0c183382017-07-13 22:26:24 -07001264 verify_no_from_space_refs_visitor(obj);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001265 }
1266 }
1267 }
1268 // TODO: LOS. But only refs in LOS are classes.
1269}
1270
1271// The following visitors are used to assert the to-space invariant.
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001272class ConcurrentCopying::AssertToSpaceInvariantRefsVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001273 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001274 explicit AssertToSpaceInvariantRefsVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001275 : collector_(collector) {}
1276
1277 void operator()(mirror::Object* ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001278 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001279 if (ref == nullptr) {
1280 // OK.
1281 return;
1282 }
1283 collector_->AssertToSpaceInvariant(nullptr, MemberOffset(0), ref);
1284 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001285
1286 private:
Mathieu Chartier97509952015-07-13 14:35:43 -07001287 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001288};
1289
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001290class ConcurrentCopying::AssertToSpaceInvariantFieldVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001291 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001292 explicit AssertToSpaceInvariantFieldVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001293 : collector_(collector) {}
1294
Mathieu Chartier31e88222016-10-14 18:43:19 -07001295 void operator()(ObjPtr<mirror::Object> obj,
1296 MemberOffset offset,
1297 bool is_static ATTRIBUTE_UNUSED) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001298 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001299 mirror::Object* ref =
1300 obj->GetFieldObject<mirror::Object, kDefaultVerifyFlags, kWithoutReadBarrier>(offset);
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001301 AssertToSpaceInvariantRefsVisitor visitor(collector_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001302 visitor(ref);
1303 }
Mathieu Chartier31e88222016-10-14 18:43:19 -07001304 void operator()(ObjPtr<mirror::Class> klass, ObjPtr<mirror::Reference> ref ATTRIBUTE_UNUSED) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001305 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001306 CHECK(klass->IsTypeOfReferenceClass());
1307 }
1308
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001309 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001310 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001311 if (!root->IsNull()) {
1312 VisitRoot(root);
1313 }
1314 }
1315
1316 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001317 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001318 AssertToSpaceInvariantRefsVisitor visitor(collector_);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001319 visitor(root->AsMirrorPtr());
1320 }
1321
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001322 private:
Mathieu Chartier97509952015-07-13 14:35:43 -07001323 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001324};
1325
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001326class ConcurrentCopying::RevokeThreadLocalMarkStackCheckpoint : public Closure {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001327 public:
Roland Levillain3887c462015-08-12 18:15:42 +01001328 RevokeThreadLocalMarkStackCheckpoint(ConcurrentCopying* concurrent_copying,
1329 bool disable_weak_ref_access)
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001330 : concurrent_copying_(concurrent_copying),
1331 disable_weak_ref_access_(disable_weak_ref_access) {
1332 }
1333
1334 virtual void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
1335 // Note: self is not necessarily equal to thread since thread may be suspended.
1336 Thread* self = Thread::Current();
1337 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
1338 << thread->GetState() << " thread " << thread << " self " << self;
1339 // Revoke thread local mark stacks.
1340 accounting::AtomicStack<mirror::Object>* tl_mark_stack = thread->GetThreadLocalMarkStack();
1341 if (tl_mark_stack != nullptr) {
1342 MutexLock mu(self, concurrent_copying_->mark_stack_lock_);
1343 concurrent_copying_->revoked_mark_stacks_.push_back(tl_mark_stack);
1344 thread->SetThreadLocalMarkStack(nullptr);
1345 }
1346 // Disable weak ref access.
1347 if (disable_weak_ref_access_) {
1348 thread->SetWeakRefAccessEnabled(false);
1349 }
1350 // If thread is a running mutator, then act on behalf of the garbage collector.
1351 // See the code in ThreadList::RunCheckpoint.
Mathieu Chartier10d25082015-10-28 18:36:09 -07001352 concurrent_copying_->GetBarrier().Pass(self);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001353 }
1354
1355 private:
1356 ConcurrentCopying* const concurrent_copying_;
1357 const bool disable_weak_ref_access_;
1358};
1359
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001360void ConcurrentCopying::RevokeThreadLocalMarkStacks(bool disable_weak_ref_access,
1361 Closure* checkpoint_callback) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001362 Thread* self = Thread::Current();
1363 RevokeThreadLocalMarkStackCheckpoint check_point(this, disable_weak_ref_access);
1364 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1365 gc_barrier_->Init(self, 0);
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001366 size_t barrier_count = thread_list->RunCheckpoint(&check_point, checkpoint_callback);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001367 // If there are no threads to wait which implys that all the checkpoint functions are finished,
1368 // then no need to release the mutator lock.
1369 if (barrier_count == 0) {
1370 return;
1371 }
1372 Locks::mutator_lock_->SharedUnlock(self);
1373 {
1374 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
1375 gc_barrier_->Increment(self, barrier_count);
1376 }
1377 Locks::mutator_lock_->SharedLock(self);
1378}
1379
1380void ConcurrentCopying::RevokeThreadLocalMarkStack(Thread* thread) {
1381 Thread* self = Thread::Current();
1382 CHECK_EQ(self, thread);
1383 accounting::AtomicStack<mirror::Object>* tl_mark_stack = thread->GetThreadLocalMarkStack();
1384 if (tl_mark_stack != nullptr) {
1385 CHECK(is_marking_);
1386 MutexLock mu(self, mark_stack_lock_);
1387 revoked_mark_stacks_.push_back(tl_mark_stack);
1388 thread->SetThreadLocalMarkStack(nullptr);
1389 }
1390}
1391
1392void ConcurrentCopying::ProcessMarkStack() {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001393 if (kVerboseMode) {
1394 LOG(INFO) << "ProcessMarkStack. ";
1395 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001396 bool empty_prev = false;
1397 while (true) {
1398 bool empty = ProcessMarkStackOnce();
1399 if (empty_prev && empty) {
1400 // Saw empty mark stack for a second time, done.
1401 break;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001402 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001403 empty_prev = empty;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001404 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001405}
1406
1407bool ConcurrentCopying::ProcessMarkStackOnce() {
1408 Thread* self = Thread::Current();
1409 CHECK(thread_running_gc_ != nullptr);
1410 CHECK(self == thread_running_gc_);
1411 CHECK(self->GetThreadLocalMarkStack() == nullptr);
1412 size_t count = 0;
1413 MarkStackMode mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1414 if (mark_stack_mode == kMarkStackModeThreadLocal) {
1415 // Process the thread-local mark stacks and the GC mark stack.
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001416 count += ProcessThreadLocalMarkStacks(false, nullptr);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001417 while (!gc_mark_stack_->IsEmpty()) {
1418 mirror::Object* to_ref = gc_mark_stack_->PopBack();
1419 ProcessMarkStackRef(to_ref);
1420 ++count;
1421 }
1422 gc_mark_stack_->Reset();
1423 } else if (mark_stack_mode == kMarkStackModeShared) {
Hiroshi Yamauchi30493242016-11-03 13:06:52 -07001424 // Do an empty checkpoint to avoid a race with a mutator preempted in the middle of a read
1425 // barrier but before pushing onto the mark stack. b/32508093. Note the weak ref access is
1426 // disabled at this point.
1427 IssueEmptyCheckpoint();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001428 // Process the shared GC mark stack with a lock.
1429 {
1430 MutexLock mu(self, mark_stack_lock_);
1431 CHECK(revoked_mark_stacks_.empty());
1432 }
1433 while (true) {
1434 std::vector<mirror::Object*> refs;
1435 {
1436 // Copy refs with lock. Note the number of refs should be small.
1437 MutexLock mu(self, mark_stack_lock_);
1438 if (gc_mark_stack_->IsEmpty()) {
1439 break;
1440 }
1441 for (StackReference<mirror::Object>* p = gc_mark_stack_->Begin();
1442 p != gc_mark_stack_->End(); ++p) {
1443 refs.push_back(p->AsMirrorPtr());
1444 }
1445 gc_mark_stack_->Reset();
1446 }
1447 for (mirror::Object* ref : refs) {
1448 ProcessMarkStackRef(ref);
1449 ++count;
1450 }
1451 }
1452 } else {
1453 CHECK_EQ(static_cast<uint32_t>(mark_stack_mode),
1454 static_cast<uint32_t>(kMarkStackModeGcExclusive));
1455 {
1456 MutexLock mu(self, mark_stack_lock_);
1457 CHECK(revoked_mark_stacks_.empty());
1458 }
1459 // Process the GC mark stack in the exclusive mode. No need to take the lock.
1460 while (!gc_mark_stack_->IsEmpty()) {
1461 mirror::Object* to_ref = gc_mark_stack_->PopBack();
1462 ProcessMarkStackRef(to_ref);
1463 ++count;
1464 }
1465 gc_mark_stack_->Reset();
1466 }
1467
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001468 // Return true if the stack was empty.
1469 return count == 0;
1470}
1471
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001472size_t ConcurrentCopying::ProcessThreadLocalMarkStacks(bool disable_weak_ref_access,
1473 Closure* checkpoint_callback) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001474 // Run a checkpoint to collect all thread local mark stacks and iterate over them all.
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001475 RevokeThreadLocalMarkStacks(disable_weak_ref_access, checkpoint_callback);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001476 size_t count = 0;
1477 std::vector<accounting::AtomicStack<mirror::Object>*> mark_stacks;
1478 {
1479 MutexLock mu(Thread::Current(), mark_stack_lock_);
1480 // Make a copy of the mark stack vector.
1481 mark_stacks = revoked_mark_stacks_;
1482 revoked_mark_stacks_.clear();
1483 }
1484 for (accounting::AtomicStack<mirror::Object>* mark_stack : mark_stacks) {
1485 for (StackReference<mirror::Object>* p = mark_stack->Begin(); p != mark_stack->End(); ++p) {
1486 mirror::Object* to_ref = p->AsMirrorPtr();
1487 ProcessMarkStackRef(to_ref);
1488 ++count;
1489 }
1490 {
1491 MutexLock mu(Thread::Current(), mark_stack_lock_);
1492 if (pooled_mark_stacks_.size() >= kMarkStackPoolSize) {
1493 // The pool has enough. Delete it.
1494 delete mark_stack;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001495 } else {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001496 // Otherwise, put it into the pool for later reuse.
1497 mark_stack->Reset();
1498 pooled_mark_stacks_.push_back(mark_stack);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001499 }
1500 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001501 }
1502 return count;
1503}
1504
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001505inline void ConcurrentCopying::ProcessMarkStackRef(mirror::Object* to_ref) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001506 DCHECK(!region_space_->IsInFromSpace(to_ref));
1507 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001508 DCHECK(to_ref->GetReadBarrierState() == ReadBarrier::GrayState())
1509 << " " << to_ref << " " << to_ref->GetReadBarrierState()
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001510 << " is_marked=" << IsMarked(to_ref);
1511 }
Mathieu Chartierc381c362016-08-23 13:27:53 -07001512 bool add_to_live_bytes = false;
1513 if (region_space_->IsInUnevacFromSpace(to_ref)) {
1514 // Mark the bitmap only in the GC thread here so that we don't need a CAS.
1515 if (!kUseBakerReadBarrier || !region_space_bitmap_->Set(to_ref)) {
1516 // It may be already marked if we accidentally pushed the same object twice due to the racy
1517 // bitmap read in MarkUnevacFromSpaceRegion.
1518 Scan(to_ref);
1519 // Only add to the live bytes if the object was not already marked.
1520 add_to_live_bytes = true;
1521 }
1522 } else {
1523 Scan(to_ref);
1524 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001525 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001526 DCHECK(to_ref->GetReadBarrierState() == ReadBarrier::GrayState())
1527 << " " << to_ref << " " << to_ref->GetReadBarrierState()
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001528 << " is_marked=" << IsMarked(to_ref);
1529 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001530#ifdef USE_BAKER_OR_BROOKS_READ_BARRIER
Hiroshi Yamauchi39c12d42016-12-06 16:46:37 -08001531 mirror::Object* referent = nullptr;
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001532 if (UNLIKELY((to_ref->GetClass<kVerifyNone, kWithoutReadBarrier>()->IsTypeOfReferenceClass() &&
Hiroshi Yamauchi39c12d42016-12-06 16:46:37 -08001533 (referent = to_ref->AsReference()->GetReferent<kWithoutReadBarrier>()) != nullptr &&
1534 !IsInToSpace(referent)))) {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001535 // Leave this reference gray in the queue so that GetReferent() will trigger a read barrier. We
1536 // will change it to white later in ReferenceQueue::DequeuePendingReference().
Richard Uhlere3627402016-02-02 13:36:55 -08001537 DCHECK(to_ref->AsReference()->GetPendingNext() != nullptr) << "Left unenqueued ref gray " << to_ref;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001538 } else {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001539 // We may occasionally leave a reference white in the queue if its referent happens to be
1540 // concurrently marked after the Scan() call above has enqueued the Reference, in which case the
1541 // above IsInToSpace() evaluates to true and we change the color from gray to white here in this
1542 // else block.
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001543 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001544 bool success = to_ref->AtomicSetReadBarrierState</*kCasRelease*/true>(
1545 ReadBarrier::GrayState(),
1546 ReadBarrier::WhiteState());
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001547 DCHECK(success) << "Must succeed as we won the race.";
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001548 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001549 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001550#else
1551 DCHECK(!kUseBakerReadBarrier);
1552#endif
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001553
Mathieu Chartierc381c362016-08-23 13:27:53 -07001554 if (add_to_live_bytes) {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001555 // Add to the live bytes per unevacuated from space. Note this code is always run by the
1556 // GC-running thread (no synchronization required).
1557 DCHECK(region_space_bitmap_->Test(to_ref));
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07001558 size_t obj_size = to_ref->SizeOf<kDefaultVerifyFlags>();
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001559 size_t alloc_size = RoundUp(obj_size, space::RegionSpace::kAlignment);
1560 region_space_->AddLiveBytes(to_ref, alloc_size);
1561 }
Andreas Gampee3ce7872017-02-22 13:36:21 -08001562 if (ReadBarrier::kEnableToSpaceInvariantChecks) {
Andreas Gampe0c183382017-07-13 22:26:24 -07001563 CHECK(to_ref != nullptr);
1564 space::RegionSpace* region_space = RegionSpace();
1565 CHECK(!region_space->IsInFromSpace(to_ref)) << "Scanning object " << to_ref << " in from space";
1566 AssertToSpaceInvariant(nullptr, MemberOffset(0), to_ref);
1567 AssertToSpaceInvariantFieldVisitor visitor(this);
1568 to_ref->VisitReferences</*kVisitNativeRoots*/true, kDefaultVerifyFlags, kWithoutReadBarrier>(
1569 visitor,
1570 visitor);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001571 }
1572}
1573
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001574class ConcurrentCopying::DisableWeakRefAccessCallback : public Closure {
1575 public:
1576 explicit DisableWeakRefAccessCallback(ConcurrentCopying* concurrent_copying)
1577 : concurrent_copying_(concurrent_copying) {
1578 }
1579
1580 void Run(Thread* self ATTRIBUTE_UNUSED) OVERRIDE REQUIRES(Locks::thread_list_lock_) {
1581 // This needs to run under the thread_list_lock_ critical section in ThreadList::RunCheckpoint()
1582 // to avoid a deadlock b/31500969.
1583 CHECK(concurrent_copying_->weak_ref_access_enabled_);
1584 concurrent_copying_->weak_ref_access_enabled_ = false;
1585 }
1586
1587 private:
1588 ConcurrentCopying* const concurrent_copying_;
1589};
1590
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001591void ConcurrentCopying::SwitchToSharedMarkStackMode() {
1592 Thread* self = Thread::Current();
1593 CHECK(thread_running_gc_ != nullptr);
1594 CHECK_EQ(self, thread_running_gc_);
1595 CHECK(self->GetThreadLocalMarkStack() == nullptr);
1596 MarkStackMode before_mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1597 CHECK_EQ(static_cast<uint32_t>(before_mark_stack_mode),
1598 static_cast<uint32_t>(kMarkStackModeThreadLocal));
1599 mark_stack_mode_.StoreRelaxed(kMarkStackModeShared);
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001600 DisableWeakRefAccessCallback dwrac(this);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001601 // Process the thread local mark stacks one last time after switching to the shared mark stack
1602 // mode and disable weak ref accesses.
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001603 ProcessThreadLocalMarkStacks(true, &dwrac);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001604 if (kVerboseMode) {
1605 LOG(INFO) << "Switched to shared mark stack mode and disabled weak ref access";
1606 }
1607}
1608
1609void ConcurrentCopying::SwitchToGcExclusiveMarkStackMode() {
1610 Thread* self = Thread::Current();
1611 CHECK(thread_running_gc_ != nullptr);
1612 CHECK_EQ(self, thread_running_gc_);
1613 CHECK(self->GetThreadLocalMarkStack() == nullptr);
1614 MarkStackMode before_mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1615 CHECK_EQ(static_cast<uint32_t>(before_mark_stack_mode),
1616 static_cast<uint32_t>(kMarkStackModeShared));
1617 mark_stack_mode_.StoreRelaxed(kMarkStackModeGcExclusive);
1618 QuasiAtomic::ThreadFenceForConstructor();
1619 if (kVerboseMode) {
1620 LOG(INFO) << "Switched to GC exclusive mark stack mode";
1621 }
1622}
1623
1624void ConcurrentCopying::CheckEmptyMarkStack() {
1625 Thread* self = Thread::Current();
1626 CHECK(thread_running_gc_ != nullptr);
1627 CHECK_EQ(self, thread_running_gc_);
1628 CHECK(self->GetThreadLocalMarkStack() == nullptr);
1629 MarkStackMode mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1630 if (mark_stack_mode == kMarkStackModeThreadLocal) {
1631 // Thread-local mark stack mode.
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001632 RevokeThreadLocalMarkStacks(false, nullptr);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001633 MutexLock mu(Thread::Current(), mark_stack_lock_);
1634 if (!revoked_mark_stacks_.empty()) {
1635 for (accounting::AtomicStack<mirror::Object>* mark_stack : revoked_mark_stacks_) {
1636 while (!mark_stack->IsEmpty()) {
1637 mirror::Object* obj = mark_stack->PopBack();
1638 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001639 uint32_t rb_state = obj->GetReadBarrierState();
1640 LOG(INFO) << "On mark queue : " << obj << " " << obj->PrettyTypeOf() << " rb_state="
1641 << rb_state << " is_marked=" << IsMarked(obj);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001642 } else {
David Sehr709b0702016-10-13 09:12:37 -07001643 LOG(INFO) << "On mark queue : " << obj << " " << obj->PrettyTypeOf()
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001644 << " is_marked=" << IsMarked(obj);
1645 }
1646 }
1647 }
1648 LOG(FATAL) << "mark stack is not empty";
1649 }
1650 } else {
1651 // Shared, GC-exclusive, or off.
1652 MutexLock mu(Thread::Current(), mark_stack_lock_);
1653 CHECK(gc_mark_stack_->IsEmpty());
1654 CHECK(revoked_mark_stacks_.empty());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001655 }
1656}
1657
1658void ConcurrentCopying::SweepSystemWeaks(Thread* self) {
1659 TimingLogger::ScopedTiming split("SweepSystemWeaks", GetTimings());
1660 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier97509952015-07-13 14:35:43 -07001661 Runtime::Current()->SweepSystemWeaks(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001662}
1663
1664void ConcurrentCopying::Sweep(bool swap_bitmaps) {
1665 {
1666 TimingLogger::ScopedTiming t("MarkStackAsLive", GetTimings());
1667 accounting::ObjectStack* live_stack = heap_->GetLiveStack();
1668 if (kEnableFromSpaceAccountingCheck) {
1669 CHECK_GE(live_stack_freeze_size_, live_stack->Size());
1670 }
1671 heap_->MarkAllocStackAsLive(live_stack);
1672 live_stack->Reset();
1673 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001674 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001675 TimingLogger::ScopedTiming split("Sweep", GetTimings());
1676 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
1677 if (space->IsContinuousMemMapAllocSpace()) {
1678 space::ContinuousMemMapAllocSpace* alloc_space = space->AsContinuousMemMapAllocSpace();
Mathieu Chartier763a31e2015-11-16 16:05:55 -08001679 if (space == region_space_ || immune_spaces_.ContainsSpace(space)) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001680 continue;
1681 }
1682 TimingLogger::ScopedTiming split2(
1683 alloc_space->IsZygoteSpace() ? "SweepZygoteSpace" : "SweepAllocSpace", GetTimings());
1684 RecordFree(alloc_space->Sweep(swap_bitmaps));
1685 }
1686 }
1687 SweepLargeObjects(swap_bitmaps);
1688}
1689
Mathieu Chartier962cd7a2016-08-16 12:15:59 -07001690void ConcurrentCopying::MarkZygoteLargeObjects() {
1691 TimingLogger::ScopedTiming split(__FUNCTION__, GetTimings());
1692 Thread* const self = Thread::Current();
1693 WriterMutexLock rmu(self, *Locks::heap_bitmap_lock_);
1694 space::LargeObjectSpace* const los = heap_->GetLargeObjectsSpace();
Nicolas Geoffray7acddd82017-05-03 15:04:55 +01001695 if (los != nullptr) {
1696 // Pick the current live bitmap (mark bitmap if swapped).
1697 accounting::LargeObjectBitmap* const live_bitmap = los->GetLiveBitmap();
1698 accounting::LargeObjectBitmap* const mark_bitmap = los->GetMarkBitmap();
1699 // Walk through all of the objects and explicitly mark the zygote ones so they don't get swept.
1700 std::pair<uint8_t*, uint8_t*> range = los->GetBeginEndAtomic();
1701 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(range.first),
1702 reinterpret_cast<uintptr_t>(range.second),
1703 [mark_bitmap, los, self](mirror::Object* obj)
1704 REQUIRES(Locks::heap_bitmap_lock_)
1705 REQUIRES_SHARED(Locks::mutator_lock_) {
1706 if (los->IsZygoteLargeObject(self, obj)) {
1707 mark_bitmap->Set(obj);
1708 }
1709 });
1710 }
Mathieu Chartier962cd7a2016-08-16 12:15:59 -07001711}
1712
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001713void ConcurrentCopying::SweepLargeObjects(bool swap_bitmaps) {
1714 TimingLogger::ScopedTiming split("SweepLargeObjects", GetTimings());
Nicolas Geoffray7acddd82017-05-03 15:04:55 +01001715 if (heap_->GetLargeObjectsSpace() != nullptr) {
1716 RecordFreeLOS(heap_->GetLargeObjectsSpace()->Sweep(swap_bitmaps));
1717 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001718}
1719
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001720void ConcurrentCopying::ReclaimPhase() {
1721 TimingLogger::ScopedTiming split("ReclaimPhase", GetTimings());
1722 if (kVerboseMode) {
1723 LOG(INFO) << "GC ReclaimPhase";
1724 }
1725 Thread* self = Thread::Current();
1726
1727 {
1728 // Double-check that the mark stack is empty.
1729 // Note: need to set this after VerifyNoFromSpaceRef().
1730 is_asserting_to_space_invariant_ = false;
1731 QuasiAtomic::ThreadFenceForConstructor();
1732 if (kVerboseMode) {
1733 LOG(INFO) << "Issue an empty check point. ";
1734 }
1735 IssueEmptyCheckpoint();
1736 // Disable the check.
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001737 is_mark_stack_push_disallowed_.StoreSequentiallyConsistent(0);
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001738 if (kUseBakerReadBarrier) {
1739 updated_all_immune_objects_.StoreSequentiallyConsistent(false);
1740 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001741 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001742 }
1743
1744 {
1745 // Record freed objects.
1746 TimingLogger::ScopedTiming split2("RecordFree", GetTimings());
1747 // Don't include thread-locals that are in the to-space.
Mathieu Chartier371b0472017-02-27 16:37:21 -08001748 const uint64_t from_bytes = region_space_->GetBytesAllocatedInFromSpace();
1749 const uint64_t from_objects = region_space_->GetObjectsAllocatedInFromSpace();
1750 const uint64_t unevac_from_bytes = region_space_->GetBytesAllocatedInUnevacFromSpace();
1751 const uint64_t unevac_from_objects = region_space_->GetObjectsAllocatedInUnevacFromSpace();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001752 uint64_t to_bytes = bytes_moved_.LoadSequentiallyConsistent();
Mathieu Chartiercca44a02016-08-17 10:07:29 -07001753 cumulative_bytes_moved_.FetchAndAddRelaxed(to_bytes);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001754 uint64_t to_objects = objects_moved_.LoadSequentiallyConsistent();
Mathieu Chartiercca44a02016-08-17 10:07:29 -07001755 cumulative_objects_moved_.FetchAndAddRelaxed(to_objects);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001756 if (kEnableFromSpaceAccountingCheck) {
1757 CHECK_EQ(from_space_num_objects_at_first_pause_, from_objects + unevac_from_objects);
1758 CHECK_EQ(from_space_num_bytes_at_first_pause_, from_bytes + unevac_from_bytes);
1759 }
1760 CHECK_LE(to_objects, from_objects);
1761 CHECK_LE(to_bytes, from_bytes);
Mathieu Chartier371b0472017-02-27 16:37:21 -08001762 // cleared_bytes and cleared_objects may be greater than the from space equivalents since
1763 // ClearFromSpace may clear empty unevac regions.
1764 uint64_t cleared_bytes;
1765 uint64_t cleared_objects;
1766 {
1767 TimingLogger::ScopedTiming split4("ClearFromSpace", GetTimings());
1768 region_space_->ClearFromSpace(&cleared_bytes, &cleared_objects);
1769 CHECK_GE(cleared_bytes, from_bytes);
1770 CHECK_GE(cleared_objects, from_objects);
1771 }
1772 int64_t freed_bytes = cleared_bytes - to_bytes;
1773 int64_t freed_objects = cleared_objects - to_objects;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001774 if (kVerboseMode) {
1775 LOG(INFO) << "RecordFree:"
1776 << " from_bytes=" << from_bytes << " from_objects=" << from_objects
1777 << " unevac_from_bytes=" << unevac_from_bytes << " unevac_from_objects=" << unevac_from_objects
1778 << " to_bytes=" << to_bytes << " to_objects=" << to_objects
1779 << " freed_bytes=" << freed_bytes << " freed_objects=" << freed_objects
1780 << " from_space size=" << region_space_->FromSpaceSize()
1781 << " unevac_from_space size=" << region_space_->UnevacFromSpaceSize()
1782 << " to_space size=" << region_space_->ToSpaceSize();
1783 LOG(INFO) << "(before) num_bytes_allocated=" << heap_->num_bytes_allocated_.LoadSequentiallyConsistent();
1784 }
1785 RecordFree(ObjectBytePair(freed_objects, freed_bytes));
1786 if (kVerboseMode) {
1787 LOG(INFO) << "(after) num_bytes_allocated=" << heap_->num_bytes_allocated_.LoadSequentiallyConsistent();
1788 }
1789 }
1790
1791 {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001792 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001793 Sweep(false);
1794 SwapBitmaps();
1795 heap_->UnBindBitmaps();
1796
Mathieu Chartier7ec38dc2016-10-07 15:24:46 -07001797 // The bitmap was cleared at the start of the GC, there is nothing we need to do here.
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001798 DCHECK(region_space_bitmap_ != nullptr);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001799 region_space_bitmap_ = nullptr;
1800 }
1801
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001802 CheckEmptyMarkStack();
1803
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001804 if (kVerboseMode) {
1805 LOG(INFO) << "GC end of ReclaimPhase";
1806 }
1807}
1808
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001809// Assert the to-space invariant.
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07001810void ConcurrentCopying::AssertToSpaceInvariant(mirror::Object* obj,
1811 MemberOffset offset,
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001812 mirror::Object* ref) {
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07001813 CHECK_EQ(heap_->collector_type_, kCollectorTypeCC);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001814 if (is_asserting_to_space_invariant_) {
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07001815 using RegionType = space::RegionSpace::RegionType;
1816 space::RegionSpace::RegionType type = region_space_->GetRegionType(ref);
1817 if (type == RegionType::kRegionTypeToSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001818 // OK.
1819 return;
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07001820 } else if (type == RegionType::kRegionTypeUnevacFromSpace) {
Mathieu Chartierc381c362016-08-23 13:27:53 -07001821 CHECK(IsMarkedInUnevacFromSpace(ref)) << ref;
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07001822 } else if (UNLIKELY(type == RegionType::kRegionTypeFromSpace)) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001823 // Not OK. Do extra logging.
1824 if (obj != nullptr) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001825 LogFromSpaceRefHolder(obj, offset);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001826 }
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07001827 ref->GetLockWord(false).Dump(LOG_STREAM(FATAL_WITHOUT_ABORT));
David Sehr709b0702016-10-13 09:12:37 -07001828 CHECK(false) << "Found from-space ref " << ref << " " << ref->PrettyTypeOf();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001829 } else {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001830 AssertToSpaceInvariantInNonMovingSpace(obj, ref);
1831 }
1832 }
1833}
1834
1835class RootPrinter {
1836 public:
1837 RootPrinter() { }
1838
1839 template <class MirrorType>
1840 ALWAYS_INLINE void VisitRootIfNonNull(mirror::CompressedReference<MirrorType>* root)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001841 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001842 if (!root->IsNull()) {
1843 VisitRoot(root);
1844 }
1845 }
1846
1847 template <class MirrorType>
1848 void VisitRoot(mirror::Object** root)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001849 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07001850 LOG(FATAL_WITHOUT_ABORT) << "root=" << root << " ref=" << *root;
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001851 }
1852
1853 template <class MirrorType>
1854 void VisitRoot(mirror::CompressedReference<MirrorType>* root)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001855 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07001856 LOG(FATAL_WITHOUT_ABORT) << "root=" << root << " ref=" << root->AsMirrorPtr();
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001857 }
1858};
1859
1860void ConcurrentCopying::AssertToSpaceInvariant(GcRootSource* gc_root_source,
1861 mirror::Object* ref) {
1862 CHECK(heap_->collector_type_ == kCollectorTypeCC) << static_cast<size_t>(heap_->collector_type_);
1863 if (is_asserting_to_space_invariant_) {
1864 if (region_space_->IsInToSpace(ref)) {
1865 // OK.
1866 return;
1867 } else if (region_space_->IsInUnevacFromSpace(ref)) {
Mathieu Chartierc381c362016-08-23 13:27:53 -07001868 CHECK(IsMarkedInUnevacFromSpace(ref)) << ref;
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001869 } else if (region_space_->IsInFromSpace(ref)) {
1870 // Not OK. Do extra logging.
1871 if (gc_root_source == nullptr) {
1872 // No info.
1873 } else if (gc_root_source->HasArtField()) {
1874 ArtField* field = gc_root_source->GetArtField();
David Sehr709b0702016-10-13 09:12:37 -07001875 LOG(FATAL_WITHOUT_ABORT) << "gc root in field " << field << " "
1876 << ArtField::PrettyField(field);
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001877 RootPrinter root_printer;
1878 field->VisitRoots(root_printer);
1879 } else if (gc_root_source->HasArtMethod()) {
1880 ArtMethod* method = gc_root_source->GetArtMethod();
David Sehr709b0702016-10-13 09:12:37 -07001881 LOG(FATAL_WITHOUT_ABORT) << "gc root in method " << method << " "
1882 << ArtMethod::PrettyMethod(method);
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001883 RootPrinter root_printer;
Andreas Gampe542451c2016-07-26 09:02:02 -07001884 method->VisitRoots(root_printer, kRuntimePointerSize);
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001885 }
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07001886 ref->GetLockWord(false).Dump(LOG_STREAM(FATAL_WITHOUT_ABORT));
1887 region_space_->DumpNonFreeRegions(LOG_STREAM(FATAL_WITHOUT_ABORT));
1888 PrintFileToLog("/proc/self/maps", LogSeverity::FATAL_WITHOUT_ABORT);
1889 MemMap::DumpMaps(LOG_STREAM(FATAL_WITHOUT_ABORT), true);
David Sehr709b0702016-10-13 09:12:37 -07001890 CHECK(false) << "Found from-space ref " << ref << " " << ref->PrettyTypeOf();
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001891 } else {
1892 AssertToSpaceInvariantInNonMovingSpace(nullptr, ref);
1893 }
1894 }
1895}
1896
1897void ConcurrentCopying::LogFromSpaceRefHolder(mirror::Object* obj, MemberOffset offset) {
1898 if (kUseBakerReadBarrier) {
David Sehr709b0702016-10-13 09:12:37 -07001899 LOG(INFO) << "holder=" << obj << " " << obj->PrettyTypeOf()
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001900 << " holder rb_state=" << obj->GetReadBarrierState();
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001901 } else {
David Sehr709b0702016-10-13 09:12:37 -07001902 LOG(INFO) << "holder=" << obj << " " << obj->PrettyTypeOf();
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001903 }
1904 if (region_space_->IsInFromSpace(obj)) {
1905 LOG(INFO) << "holder is in the from-space.";
1906 } else if (region_space_->IsInToSpace(obj)) {
1907 LOG(INFO) << "holder is in the to-space.";
1908 } else if (region_space_->IsInUnevacFromSpace(obj)) {
1909 LOG(INFO) << "holder is in the unevac from-space.";
Mathieu Chartierc381c362016-08-23 13:27:53 -07001910 if (IsMarkedInUnevacFromSpace(obj)) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001911 LOG(INFO) << "holder is marked in the region space bitmap.";
1912 } else {
1913 LOG(INFO) << "holder is not marked in the region space bitmap.";
1914 }
1915 } else {
1916 // In a non-moving space.
Mathieu Chartier763a31e2015-11-16 16:05:55 -08001917 if (immune_spaces_.ContainsObject(obj)) {
1918 LOG(INFO) << "holder is in an immune image or the zygote space.";
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001919 } else {
Mathieu Chartier763a31e2015-11-16 16:05:55 -08001920 LOG(INFO) << "holder is in a non-immune, non-moving (or main) space.";
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001921 accounting::ContinuousSpaceBitmap* mark_bitmap =
1922 heap_mark_bitmap_->GetContinuousSpaceBitmap(obj);
1923 accounting::LargeObjectBitmap* los_bitmap =
1924 heap_mark_bitmap_->GetLargeObjectBitmap(obj);
1925 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
1926 bool is_los = mark_bitmap == nullptr;
1927 if (!is_los && mark_bitmap->Test(obj)) {
1928 LOG(INFO) << "holder is marked in the mark bit map.";
1929 } else if (is_los && los_bitmap->Test(obj)) {
1930 LOG(INFO) << "holder is marked in the los bit map.";
1931 } else {
1932 // If ref is on the allocation stack, then it is considered
1933 // mark/alive (but not necessarily on the live stack.)
1934 if (IsOnAllocStack(obj)) {
1935 LOG(INFO) << "holder is on the alloc stack.";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001936 } else {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001937 LOG(INFO) << "holder is not marked or on the alloc stack.";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001938 }
1939 }
1940 }
1941 }
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001942 LOG(INFO) << "offset=" << offset.SizeValue();
1943}
1944
1945void ConcurrentCopying::AssertToSpaceInvariantInNonMovingSpace(mirror::Object* obj,
1946 mirror::Object* ref) {
1947 // In a non-moving spaces. Check that the ref is marked.
Mathieu Chartier763a31e2015-11-16 16:05:55 -08001948 if (immune_spaces_.ContainsObject(ref)) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001949 if (kUseBakerReadBarrier) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001950 // Immune object may not be gray if called from the GC.
1951 if (Thread::Current() == thread_running_gc_ && !gc_grays_immune_objects_) {
1952 return;
1953 }
1954 bool updated_all_immune_objects = updated_all_immune_objects_.LoadSequentiallyConsistent();
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001955 CHECK(updated_all_immune_objects || ref->GetReadBarrierState() == ReadBarrier::GrayState())
1956 << "Unmarked immune space ref. obj=" << obj << " rb_state="
1957 << (obj != nullptr ? obj->GetReadBarrierState() : 0U)
1958 << " ref=" << ref << " ref rb_state=" << ref->GetReadBarrierState()
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001959 << " updated_all_immune_objects=" << updated_all_immune_objects;
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001960 }
1961 } else {
1962 accounting::ContinuousSpaceBitmap* mark_bitmap =
1963 heap_mark_bitmap_->GetContinuousSpaceBitmap(ref);
1964 accounting::LargeObjectBitmap* los_bitmap =
1965 heap_mark_bitmap_->GetLargeObjectBitmap(ref);
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001966 bool is_los = mark_bitmap == nullptr;
1967 if ((!is_los && mark_bitmap->Test(ref)) ||
1968 (is_los && los_bitmap->Test(ref))) {
1969 // OK.
1970 } else {
1971 // If ref is on the allocation stack, then it may not be
1972 // marked live, but considered marked/alive (but not
1973 // necessarily on the live stack).
1974 CHECK(IsOnAllocStack(ref)) << "Unmarked ref that's not on the allocation stack. "
1975 << "obj=" << obj << " ref=" << ref;
1976 }
1977 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001978}
1979
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001980// Used to scan ref fields of an object.
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001981class ConcurrentCopying::RefFieldsVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001982 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001983 explicit RefFieldsVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001984 : collector_(collector) {}
1985
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07001986 void operator()(mirror::Object* obj, MemberOffset offset, bool /* is_static */)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001987 const ALWAYS_INLINE REQUIRES_SHARED(Locks::mutator_lock_)
1988 REQUIRES_SHARED(Locks::heap_bitmap_lock_) {
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07001989 collector_->Process(obj, offset);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001990 }
1991
Mathieu Chartier31e88222016-10-14 18:43:19 -07001992 void operator()(ObjPtr<mirror::Class> klass, ObjPtr<mirror::Reference> ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001993 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001994 CHECK(klass->IsTypeOfReferenceClass());
1995 collector_->DelayReferenceReferent(klass, ref);
1996 }
1997
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001998 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001999 ALWAYS_INLINE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002000 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002001 if (!root->IsNull()) {
2002 VisitRoot(root);
2003 }
2004 }
2005
2006 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002007 ALWAYS_INLINE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002008 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002009 collector_->MarkRoot</*kGrayImmuneObject*/false>(root);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002010 }
2011
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002012 private:
2013 ConcurrentCopying* const collector_;
2014};
2015
2016// Scan ref fields of an object.
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002017inline void ConcurrentCopying::Scan(mirror::Object* to_ref) {
Hiroshi Yamauchi9b60d502017-02-03 15:09:26 -08002018 if (kDisallowReadBarrierDuringScan && !Runtime::Current()->IsActiveTransaction()) {
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07002019 // Avoid all read barriers during visit references to help performance.
Hiroshi Yamauchi9b60d502017-02-03 15:09:26 -08002020 // Don't do this in transaction mode because we may read the old value of an field which may
2021 // trigger read barriers.
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07002022 Thread::Current()->ModifyDebugDisallowReadBarrier(1);
2023 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002024 DCHECK(!region_space_->IsInFromSpace(to_ref));
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002025 DCHECK_EQ(Thread::Current(), thread_running_gc_);
Mathieu Chartiera07f5592016-06-16 11:44:28 -07002026 RefFieldsVisitor visitor(this);
Hiroshi Yamauchi5496f692016-02-17 13:29:59 -08002027 // Disable the read barrier for a performance reason.
2028 to_ref->VisitReferences</*kVisitNativeRoots*/true, kDefaultVerifyFlags, kWithoutReadBarrier>(
2029 visitor, visitor);
Hiroshi Yamauchi9b60d502017-02-03 15:09:26 -08002030 if (kDisallowReadBarrierDuringScan && !Runtime::Current()->IsActiveTransaction()) {
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07002031 Thread::Current()->ModifyDebugDisallowReadBarrier(-1);
2032 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002033}
2034
2035// Process a field.
2036inline void ConcurrentCopying::Process(mirror::Object* obj, MemberOffset offset) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002037 DCHECK_EQ(Thread::Current(), thread_running_gc_);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002038 mirror::Object* ref = obj->GetFieldObject<
2039 mirror::Object, kVerifyNone, kWithoutReadBarrier, false>(offset);
Mathieu Chartier4ce0c762017-05-18 10:01:07 -07002040 mirror::Object* to_ref = Mark</*kGrayImmuneObject*/false, /*kFromGCThread*/true>(
2041 ref,
2042 /*holder*/ obj,
2043 offset);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002044 if (to_ref == ref) {
2045 return;
2046 }
2047 // This may fail if the mutator writes to the field at the same time. But it's ok.
2048 mirror::Object* expected_ref = ref;
2049 mirror::Object* new_ref = to_ref;
2050 do {
2051 if (expected_ref !=
2052 obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier, false>(offset)) {
2053 // It was updated by the mutator.
2054 break;
2055 }
Mathieu Chartierfdd513d2017-06-01 11:26:50 -07002056 // Use release cas to make sure threads reading the reference see contents of copied objects.
2057 } while (!obj->CasFieldWeakReleaseObjectWithoutWriteBarrier<false, false, kVerifyNone>(
2058 offset,
2059 expected_ref,
2060 new_ref));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002061}
2062
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002063// Process some roots.
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002064inline void ConcurrentCopying::VisitRoots(
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002065 mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED) {
2066 for (size_t i = 0; i < count; ++i) {
2067 mirror::Object** root = roots[i];
2068 mirror::Object* ref = *root;
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002069 mirror::Object* to_ref = Mark(ref);
2070 if (to_ref == ref) {
Mathieu Chartier4809d0a2015-04-07 10:39:04 -07002071 continue;
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002072 }
2073 Atomic<mirror::Object*>* addr = reinterpret_cast<Atomic<mirror::Object*>*>(root);
2074 mirror::Object* expected_ref = ref;
2075 mirror::Object* new_ref = to_ref;
2076 do {
2077 if (expected_ref != addr->LoadRelaxed()) {
2078 // It was updated by the mutator.
2079 break;
2080 }
Hiroshi Yamauchifed3e2f2015-10-20 11:11:56 -07002081 } while (!addr->CompareExchangeWeakRelaxed(expected_ref, new_ref));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002082 }
2083}
2084
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002085template<bool kGrayImmuneObject>
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002086inline void ConcurrentCopying::MarkRoot(mirror::CompressedReference<mirror::Object>* root) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002087 DCHECK(!root->IsNull());
2088 mirror::Object* const ref = root->AsMirrorPtr();
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002089 mirror::Object* to_ref = Mark<kGrayImmuneObject>(ref);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002090 if (to_ref != ref) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002091 auto* addr = reinterpret_cast<Atomic<mirror::CompressedReference<mirror::Object>>*>(root);
2092 auto expected_ref = mirror::CompressedReference<mirror::Object>::FromMirrorPtr(ref);
2093 auto new_ref = mirror::CompressedReference<mirror::Object>::FromMirrorPtr(to_ref);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002094 // If the cas fails, then it was updated by the mutator.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002095 do {
2096 if (ref != addr->LoadRelaxed().AsMirrorPtr()) {
2097 // It was updated by the mutator.
2098 break;
2099 }
Hiroshi Yamauchifed3e2f2015-10-20 11:11:56 -07002100 } while (!addr->CompareExchangeWeakRelaxed(expected_ref, new_ref));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002101 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002102}
2103
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002104inline void ConcurrentCopying::VisitRoots(
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002105 mirror::CompressedReference<mirror::Object>** roots, size_t count,
2106 const RootInfo& info ATTRIBUTE_UNUSED) {
2107 for (size_t i = 0; i < count; ++i) {
2108 mirror::CompressedReference<mirror::Object>* const root = roots[i];
2109 if (!root->IsNull()) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002110 // kGrayImmuneObject is true because this is used for the thread flip.
2111 MarkRoot</*kGrayImmuneObject*/true>(root);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002112 }
2113 }
2114}
2115
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002116// Temporary set gc_grays_immune_objects_ to true in a scope if the current thread is GC.
2117class ConcurrentCopying::ScopedGcGraysImmuneObjects {
2118 public:
2119 explicit ScopedGcGraysImmuneObjects(ConcurrentCopying* collector)
2120 : collector_(collector), enabled_(false) {
2121 if (kUseBakerReadBarrier &&
2122 collector_->thread_running_gc_ == Thread::Current() &&
2123 !collector_->gc_grays_immune_objects_) {
2124 collector_->gc_grays_immune_objects_ = true;
2125 enabled_ = true;
2126 }
2127 }
2128
2129 ~ScopedGcGraysImmuneObjects() {
2130 if (kUseBakerReadBarrier &&
2131 collector_->thread_running_gc_ == Thread::Current() &&
2132 enabled_) {
2133 DCHECK(collector_->gc_grays_immune_objects_);
2134 collector_->gc_grays_immune_objects_ = false;
2135 }
2136 }
2137
2138 private:
2139 ConcurrentCopying* const collector_;
2140 bool enabled_;
2141};
2142
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002143// Fill the given memory block with a dummy object. Used to fill in a
2144// copy of objects that was lost in race.
2145void ConcurrentCopying::FillWithDummyObject(mirror::Object* dummy_obj, size_t byte_size) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002146 // GC doesn't gray immune objects while scanning immune objects. But we need to trigger the read
2147 // barriers here because we need the updated reference to the int array class, etc. Temporary set
2148 // gc_grays_immune_objects_ to true so that we won't cause a DCHECK failure in MarkImmuneSpace().
2149 ScopedGcGraysImmuneObjects scoped_gc_gray_immune_objects(this);
Roland Levillain14d90572015-07-16 10:52:26 +01002150 CHECK_ALIGNED(byte_size, kObjectAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002151 memset(dummy_obj, 0, byte_size);
Mathieu Chartierd6636d32016-07-28 11:02:38 -07002152 // Avoid going through read barrier for since kDisallowReadBarrierDuringScan may be enabled.
2153 // Explicitly mark to make sure to get an object in the to-space.
2154 mirror::Class* int_array_class = down_cast<mirror::Class*>(
2155 Mark(mirror::IntArray::GetArrayClass<kWithoutReadBarrier>()));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002156 CHECK(int_array_class != nullptr);
Andreas Gampe6c578712017-10-19 13:00:34 -07002157 if (ReadBarrier::kEnableToSpaceInvariantChecks) {
2158 AssertToSpaceInvariant(nullptr, MemberOffset(0), int_array_class);
2159 }
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07002160 size_t component_size = int_array_class->GetComponentSize<kWithoutReadBarrier>();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002161 CHECK_EQ(component_size, sizeof(int32_t));
2162 size_t data_offset = mirror::Array::DataOffset(component_size).SizeValue();
2163 if (data_offset > byte_size) {
2164 // An int array is too big. Use java.lang.Object.
Mathieu Chartier9aef9922017-04-23 13:53:50 -07002165 CHECK(java_lang_Object_ != nullptr);
Andreas Gampe6c578712017-10-19 13:00:34 -07002166 if (ReadBarrier::kEnableToSpaceInvariantChecks) {
2167 AssertToSpaceInvariant(nullptr, MemberOffset(0), java_lang_Object_);
2168 }
Mathieu Chartier3ed8ec12017-04-20 19:28:54 -07002169 CHECK_EQ(byte_size, (java_lang_Object_->GetObjectSize<kVerifyNone, kWithoutReadBarrier>()));
2170 dummy_obj->SetClass(java_lang_Object_);
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07002171 CHECK_EQ(byte_size, (dummy_obj->SizeOf<kVerifyNone>()));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002172 } else {
2173 // Use an int array.
2174 dummy_obj->SetClass(int_array_class);
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07002175 CHECK((dummy_obj->IsArrayInstance<kVerifyNone, kWithoutReadBarrier>()));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002176 int32_t length = (byte_size - data_offset) / component_size;
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07002177 mirror::Array* dummy_arr = dummy_obj->AsArray<kVerifyNone, kWithoutReadBarrier>();
2178 dummy_arr->SetLength(length);
2179 CHECK_EQ(dummy_arr->GetLength(), length)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002180 << "byte_size=" << byte_size << " length=" << length
2181 << " component_size=" << component_size << " data_offset=" << data_offset;
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07002182 CHECK_EQ(byte_size, (dummy_obj->SizeOf<kVerifyNone>()))
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002183 << "byte_size=" << byte_size << " length=" << length
2184 << " component_size=" << component_size << " data_offset=" << data_offset;
2185 }
2186}
2187
2188// Reuse the memory blocks that were copy of objects that were lost in race.
2189mirror::Object* ConcurrentCopying::AllocateInSkippedBlock(size_t alloc_size) {
2190 // Try to reuse the blocks that were unused due to CAS failures.
Roland Levillain14d90572015-07-16 10:52:26 +01002191 CHECK_ALIGNED(alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002192 Thread* self = Thread::Current();
2193 size_t min_object_size = RoundUp(sizeof(mirror::Object), space::RegionSpace::kAlignment);
Mathieu Chartierd6636d32016-07-28 11:02:38 -07002194 size_t byte_size;
2195 uint8_t* addr;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002196 {
Mathieu Chartierd6636d32016-07-28 11:02:38 -07002197 MutexLock mu(self, skipped_blocks_lock_);
2198 auto it = skipped_blocks_map_.lower_bound(alloc_size);
2199 if (it == skipped_blocks_map_.end()) {
2200 // Not found.
2201 return nullptr;
2202 }
2203 byte_size = it->first;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002204 CHECK_GE(byte_size, alloc_size);
2205 if (byte_size > alloc_size && byte_size - alloc_size < min_object_size) {
2206 // If remainder would be too small for a dummy object, retry with a larger request size.
2207 it = skipped_blocks_map_.lower_bound(alloc_size + min_object_size);
2208 if (it == skipped_blocks_map_.end()) {
2209 // Not found.
2210 return nullptr;
2211 }
Roland Levillain14d90572015-07-16 10:52:26 +01002212 CHECK_ALIGNED(it->first - alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002213 CHECK_GE(it->first - alloc_size, min_object_size)
2214 << "byte_size=" << byte_size << " it->first=" << it->first << " alloc_size=" << alloc_size;
2215 }
Mathieu Chartierd6636d32016-07-28 11:02:38 -07002216 // Found a block.
2217 CHECK(it != skipped_blocks_map_.end());
2218 byte_size = it->first;
2219 addr = it->second;
2220 CHECK_GE(byte_size, alloc_size);
2221 CHECK(region_space_->IsInToSpace(reinterpret_cast<mirror::Object*>(addr)));
2222 CHECK_ALIGNED(byte_size, space::RegionSpace::kAlignment);
2223 if (kVerboseMode) {
2224 LOG(INFO) << "Reusing skipped bytes : " << reinterpret_cast<void*>(addr) << ", " << byte_size;
2225 }
2226 skipped_blocks_map_.erase(it);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002227 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002228 memset(addr, 0, byte_size);
2229 if (byte_size > alloc_size) {
2230 // Return the remainder to the map.
Roland Levillain14d90572015-07-16 10:52:26 +01002231 CHECK_ALIGNED(byte_size - alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002232 CHECK_GE(byte_size - alloc_size, min_object_size);
Mathieu Chartierd6636d32016-07-28 11:02:38 -07002233 // FillWithDummyObject may mark an object, avoid holding skipped_blocks_lock_ to prevent lock
2234 // violation and possible deadlock. The deadlock case is a recursive case:
2235 // FillWithDummyObject -> IntArray::GetArrayClass -> Mark -> Copy -> AllocateInSkippedBlock.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002236 FillWithDummyObject(reinterpret_cast<mirror::Object*>(addr + alloc_size),
2237 byte_size - alloc_size);
2238 CHECK(region_space_->IsInToSpace(reinterpret_cast<mirror::Object*>(addr + alloc_size)));
Mathieu Chartierd6636d32016-07-28 11:02:38 -07002239 {
2240 MutexLock mu(self, skipped_blocks_lock_);
2241 skipped_blocks_map_.insert(std::make_pair(byte_size - alloc_size, addr + alloc_size));
2242 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002243 }
2244 return reinterpret_cast<mirror::Object*>(addr);
2245}
2246
Mathieu Chartieref496d92017-04-28 18:58:59 -07002247mirror::Object* ConcurrentCopying::Copy(mirror::Object* from_ref,
2248 mirror::Object* holder,
2249 MemberOffset offset) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002250 DCHECK(region_space_->IsInFromSpace(from_ref));
Mathieu Chartieref496d92017-04-28 18:58:59 -07002251 // If the class pointer is null, the object is invalid. This could occur for a dangling pointer
2252 // from a previous GC that is either inside or outside the allocated region.
2253 mirror::Class* klass = from_ref->GetClass<kVerifyNone, kWithoutReadBarrier>();
2254 if (UNLIKELY(klass == nullptr)) {
2255 heap_->GetVerification()->LogHeapCorruption(holder, offset, from_ref, /* fatal */ true);
2256 }
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07002257 // There must not be a read barrier to avoid nested RB that might violate the to-space invariant.
2258 // Note that from_ref is a from space ref so the SizeOf() call will access the from-space meta
2259 // objects, but it's ok and necessary.
2260 size_t obj_size = from_ref->SizeOf<kDefaultVerifyFlags>();
Nicolas Geoffray4b361a82017-07-06 15:30:10 +01002261 size_t region_space_alloc_size = (obj_size <= space::RegionSpace::kRegionSize)
2262 ? RoundUp(obj_size, space::RegionSpace::kAlignment)
2263 : RoundUp(obj_size, space::RegionSpace::kRegionSize);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002264 size_t region_space_bytes_allocated = 0U;
2265 size_t non_moving_space_bytes_allocated = 0U;
2266 size_t bytes_allocated = 0U;
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07002267 size_t dummy;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002268 mirror::Object* to_ref = region_space_->AllocNonvirtual<true>(
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07002269 region_space_alloc_size, &region_space_bytes_allocated, nullptr, &dummy);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002270 bytes_allocated = region_space_bytes_allocated;
2271 if (to_ref != nullptr) {
2272 DCHECK_EQ(region_space_alloc_size, region_space_bytes_allocated);
2273 }
2274 bool fall_back_to_non_moving = false;
2275 if (UNLIKELY(to_ref == nullptr)) {
2276 // Failed to allocate in the region space. Try the skipped blocks.
2277 to_ref = AllocateInSkippedBlock(region_space_alloc_size);
2278 if (to_ref != nullptr) {
2279 // Succeeded to allocate in a skipped block.
2280 if (heap_->use_tlab_) {
2281 // This is necessary for the tlab case as it's not accounted in the space.
2282 region_space_->RecordAlloc(to_ref);
2283 }
2284 bytes_allocated = region_space_alloc_size;
2285 } else {
2286 // Fall back to the non-moving space.
2287 fall_back_to_non_moving = true;
2288 if (kVerboseMode) {
2289 LOG(INFO) << "Out of memory in the to-space. Fall back to non-moving. skipped_bytes="
2290 << to_space_bytes_skipped_.LoadSequentiallyConsistent()
2291 << " skipped_objects=" << to_space_objects_skipped_.LoadSequentiallyConsistent();
2292 }
2293 fall_back_to_non_moving = true;
2294 to_ref = heap_->non_moving_space_->Alloc(Thread::Current(), obj_size,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07002295 &non_moving_space_bytes_allocated, nullptr, &dummy);
Mathieu Chartierb01335c2017-03-22 13:15:01 -07002296 if (UNLIKELY(to_ref == nullptr)) {
2297 LOG(FATAL_WITHOUT_ABORT) << "Fall-back non-moving space allocation failed for a "
2298 << obj_size << " byte object in region type "
2299 << region_space_->GetRegionType(from_ref);
2300 LOG(FATAL) << "Object address=" << from_ref << " type=" << from_ref->PrettyTypeOf();
2301 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002302 bytes_allocated = non_moving_space_bytes_allocated;
2303 // Mark it in the mark bitmap.
2304 accounting::ContinuousSpaceBitmap* mark_bitmap =
2305 heap_mark_bitmap_->GetContinuousSpaceBitmap(to_ref);
2306 CHECK(mark_bitmap != nullptr);
2307 CHECK(!mark_bitmap->AtomicTestAndSet(to_ref));
2308 }
2309 }
2310 DCHECK(to_ref != nullptr);
2311
Mathieu Chartierd818adb2016-09-15 13:12:47 -07002312 // Copy the object excluding the lock word since that is handled in the loop.
Mathieu Chartieref496d92017-04-28 18:58:59 -07002313 to_ref->SetClass(klass);
Mathieu Chartierd818adb2016-09-15 13:12:47 -07002314 const size_t kObjectHeaderSize = sizeof(mirror::Object);
2315 DCHECK_GE(obj_size, kObjectHeaderSize);
2316 static_assert(kObjectHeaderSize == sizeof(mirror::HeapReference<mirror::Class>) +
2317 sizeof(LockWord),
2318 "Object header size does not match");
2319 // Memcpy can tear for words since it may do byte copy. It is only safe to do this since the
2320 // object in the from space is immutable other than the lock word. b/31423258
2321 memcpy(reinterpret_cast<uint8_t*>(to_ref) + kObjectHeaderSize,
2322 reinterpret_cast<const uint8_t*>(from_ref) + kObjectHeaderSize,
2323 obj_size - kObjectHeaderSize);
2324
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002325 // Attempt to install the forward pointer. This is in a loop as the
2326 // lock word atomic write can fail.
2327 while (true) {
Mathieu Chartierd818adb2016-09-15 13:12:47 -07002328 LockWord old_lock_word = from_ref->GetLockWord(false);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002329
2330 if (old_lock_word.GetState() == LockWord::kForwardingAddress) {
2331 // Lost the race. Another thread (either GC or mutator) stored
2332 // the forwarding pointer first. Make the lost copy (to_ref)
2333 // look like a valid but dead (dummy) object and keep it for
2334 // future reuse.
2335 FillWithDummyObject(to_ref, bytes_allocated);
2336 if (!fall_back_to_non_moving) {
2337 DCHECK(region_space_->IsInToSpace(to_ref));
2338 if (bytes_allocated > space::RegionSpace::kRegionSize) {
2339 // Free the large alloc.
2340 region_space_->FreeLarge(to_ref, bytes_allocated);
2341 } else {
2342 // Record the lost copy for later reuse.
2343 heap_->num_bytes_allocated_.FetchAndAddSequentiallyConsistent(bytes_allocated);
2344 to_space_bytes_skipped_.FetchAndAddSequentiallyConsistent(bytes_allocated);
2345 to_space_objects_skipped_.FetchAndAddSequentiallyConsistent(1);
2346 MutexLock mu(Thread::Current(), skipped_blocks_lock_);
2347 skipped_blocks_map_.insert(std::make_pair(bytes_allocated,
2348 reinterpret_cast<uint8_t*>(to_ref)));
2349 }
2350 } else {
2351 DCHECK(heap_->non_moving_space_->HasAddress(to_ref));
2352 DCHECK_EQ(bytes_allocated, non_moving_space_bytes_allocated);
2353 // Free the non-moving-space chunk.
2354 accounting::ContinuousSpaceBitmap* mark_bitmap =
2355 heap_mark_bitmap_->GetContinuousSpaceBitmap(to_ref);
2356 CHECK(mark_bitmap != nullptr);
2357 CHECK(mark_bitmap->Clear(to_ref));
2358 heap_->non_moving_space_->Free(Thread::Current(), to_ref);
2359 }
2360
2361 // Get the winner's forward ptr.
2362 mirror::Object* lost_fwd_ptr = to_ref;
2363 to_ref = reinterpret_cast<mirror::Object*>(old_lock_word.ForwardingAddress());
2364 CHECK(to_ref != nullptr);
2365 CHECK_NE(to_ref, lost_fwd_ptr);
Mathieu Chartierdfcd6f42016-09-13 10:02:48 -07002366 CHECK(region_space_->IsInToSpace(to_ref) || heap_->non_moving_space_->HasAddress(to_ref))
2367 << "to_ref=" << to_ref << " " << heap_->DumpSpaces();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002368 CHECK_NE(to_ref->GetLockWord(false).GetState(), LockWord::kForwardingAddress);
2369 return to_ref;
2370 }
2371
Mathieu Chartierd818adb2016-09-15 13:12:47 -07002372 // Copy the old lock word over since we did not copy it yet.
2373 to_ref->SetLockWord(old_lock_word, false);
Hiroshi Yamauchi60f63f52015-04-23 16:12:40 -07002374 // Set the gray ptr.
2375 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002376 to_ref->SetReadBarrierState(ReadBarrier::GrayState());
Hiroshi Yamauchi60f63f52015-04-23 16:12:40 -07002377 }
2378
Mathieu Chartiera8131262016-11-29 17:55:19 -08002379 // Do a fence to prevent the field CAS in ConcurrentCopying::Process from possibly reordering
2380 // before the object copy.
2381 QuasiAtomic::ThreadFenceRelease();
2382
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002383 LockWord new_lock_word = LockWord::FromForwardingAddress(reinterpret_cast<size_t>(to_ref));
2384
2385 // Try to atomically write the fwd ptr.
Mathieu Chartiera8131262016-11-29 17:55:19 -08002386 bool success = from_ref->CasLockWordWeakRelaxed(old_lock_word, new_lock_word);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002387 if (LIKELY(success)) {
2388 // The CAS succeeded.
Mathieu Chartiera8131262016-11-29 17:55:19 -08002389 objects_moved_.FetchAndAddRelaxed(1);
2390 bytes_moved_.FetchAndAddRelaxed(region_space_alloc_size);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002391 if (LIKELY(!fall_back_to_non_moving)) {
2392 DCHECK(region_space_->IsInToSpace(to_ref));
2393 } else {
2394 DCHECK(heap_->non_moving_space_->HasAddress(to_ref));
2395 DCHECK_EQ(bytes_allocated, non_moving_space_bytes_allocated);
2396 }
2397 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002398 DCHECK(to_ref->GetReadBarrierState() == ReadBarrier::GrayState());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002399 }
2400 DCHECK(GetFwdPtr(from_ref) == to_ref);
2401 CHECK_NE(to_ref->GetLockWord(false).GetState(), LockWord::kForwardingAddress);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002402 PushOntoMarkStack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002403 return to_ref;
2404 } else {
2405 // The CAS failed. It may have lost the race or may have failed
2406 // due to monitor/hashcode ops. Either way, retry.
2407 }
2408 }
2409}
2410
2411mirror::Object* ConcurrentCopying::IsMarked(mirror::Object* from_ref) {
2412 DCHECK(from_ref != nullptr);
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08002413 space::RegionSpace::RegionType rtype = region_space_->GetRegionType(from_ref);
2414 if (rtype == space::RegionSpace::RegionType::kRegionTypeToSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002415 // It's already marked.
2416 return from_ref;
2417 }
2418 mirror::Object* to_ref;
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08002419 if (rtype == space::RegionSpace::RegionType::kRegionTypeFromSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002420 to_ref = GetFwdPtr(from_ref);
2421 DCHECK(to_ref == nullptr || region_space_->IsInToSpace(to_ref) ||
2422 heap_->non_moving_space_->HasAddress(to_ref))
2423 << "from_ref=" << from_ref << " to_ref=" << to_ref;
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08002424 } else if (rtype == space::RegionSpace::RegionType::kRegionTypeUnevacFromSpace) {
Mathieu Chartierc381c362016-08-23 13:27:53 -07002425 if (IsMarkedInUnevacFromSpace(from_ref)) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002426 to_ref = from_ref;
2427 } else {
2428 to_ref = nullptr;
2429 }
2430 } else {
2431 // from_ref is in a non-moving space.
Mathieu Chartier763a31e2015-11-16 16:05:55 -08002432 if (immune_spaces_.ContainsObject(from_ref)) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002433 // An immune object is alive.
2434 to_ref = from_ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002435 } else {
2436 // Non-immune non-moving space. Use the mark bitmap.
2437 accounting::ContinuousSpaceBitmap* mark_bitmap =
2438 heap_mark_bitmap_->GetContinuousSpaceBitmap(from_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002439 bool is_los = mark_bitmap == nullptr;
2440 if (!is_los && mark_bitmap->Test(from_ref)) {
2441 // Already marked.
2442 to_ref = from_ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002443 } else {
Mathieu Chartier47863bb2017-08-04 11:30:27 -07002444 accounting::LargeObjectBitmap* los_bitmap =
2445 heap_mark_bitmap_->GetLargeObjectBitmap(from_ref);
2446 // We may not have a large object space for dex2oat, don't assume it exists.
2447 if (los_bitmap == nullptr) {
2448 CHECK(heap_->GetLargeObjectsSpace() == nullptr)
2449 << "LOS bitmap covers the entire address range " << from_ref
2450 << " " << heap_->DumpSpaces();
2451 }
2452 if (los_bitmap != nullptr && is_los && los_bitmap->Test(from_ref)) {
2453 // Already marked in LOS.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002454 to_ref = from_ref;
2455 } else {
2456 // Not marked.
Mathieu Chartier47863bb2017-08-04 11:30:27 -07002457 if (IsOnAllocStack(from_ref)) {
2458 // If on the allocation stack, it's considered marked.
2459 to_ref = from_ref;
2460 } else {
2461 // Not marked.
2462 to_ref = nullptr;
2463 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002464 }
2465 }
2466 }
2467 }
2468 return to_ref;
2469}
2470
2471bool ConcurrentCopying::IsOnAllocStack(mirror::Object* ref) {
Hans Boehmcc55e1d2017-07-27 15:28:07 -07002472 // TODO: Explain why this is here. What release operation does it pair with?
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002473 QuasiAtomic::ThreadFenceAcquire();
2474 accounting::ObjectStack* alloc_stack = GetAllocationStack();
Mathieu Chartiercb535da2015-01-23 13:50:03 -08002475 return alloc_stack->Contains(ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002476}
2477
Mathieu Chartier1ca68902017-04-18 11:26:22 -07002478mirror::Object* ConcurrentCopying::MarkNonMoving(mirror::Object* ref,
2479 mirror::Object* holder,
2480 MemberOffset offset) {
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002481 // ref is in a non-moving space (from_ref == to_ref).
2482 DCHECK(!region_space_->HasAddress(ref)) << ref;
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002483 DCHECK(!immune_spaces_.ContainsObject(ref));
2484 // Use the mark bitmap.
2485 accounting::ContinuousSpaceBitmap* mark_bitmap =
2486 heap_mark_bitmap_->GetContinuousSpaceBitmap(ref);
2487 accounting::LargeObjectBitmap* los_bitmap =
2488 heap_mark_bitmap_->GetLargeObjectBitmap(ref);
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002489 bool is_los = mark_bitmap == nullptr;
2490 if (!is_los && mark_bitmap->Test(ref)) {
2491 // Already marked.
2492 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002493 DCHECK(ref->GetReadBarrierState() == ReadBarrier::GrayState() ||
2494 ref->GetReadBarrierState() == ReadBarrier::WhiteState());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002495 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002496 } else if (is_los && los_bitmap->Test(ref)) {
2497 // Already marked in LOS.
2498 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002499 DCHECK(ref->GetReadBarrierState() == ReadBarrier::GrayState() ||
2500 ref->GetReadBarrierState() == ReadBarrier::WhiteState());
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002501 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002502 } else {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002503 // Not marked.
2504 if (IsOnAllocStack(ref)) {
2505 // If it's on the allocation stack, it's considered marked. Keep it white.
2506 // Objects on the allocation stack need not be marked.
2507 if (!is_los) {
2508 DCHECK(!mark_bitmap->Test(ref));
2509 } else {
2510 DCHECK(!los_bitmap->Test(ref));
Nicolas Geoffrayddeb1722016-06-28 08:25:59 +00002511 }
Nicolas Geoffrayddeb1722016-06-28 08:25:59 +00002512 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002513 DCHECK_EQ(ref->GetReadBarrierState(), ReadBarrier::WhiteState());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002514 }
2515 } else {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002516 // For the baker-style RB, we need to handle 'false-gray' cases. See the
2517 // kRegionTypeUnevacFromSpace-case comment in Mark().
2518 if (kUseBakerReadBarrier) {
2519 // Test the bitmap first to reduce the chance of false gray cases.
2520 if ((!is_los && mark_bitmap->Test(ref)) ||
2521 (is_los && los_bitmap->Test(ref))) {
2522 return ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002523 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002524 }
Mathieu Chartier1ca68902017-04-18 11:26:22 -07002525 if (is_los && !IsAligned<kPageSize>(ref)) {
2526 // Ref is a large object that is not aligned, it must be heap corruption. Dump data before
2527 // AtomicSetReadBarrierState since it will fault if the address is not valid.
Mathieu Chartieref496d92017-04-28 18:58:59 -07002528 heap_->GetVerification()->LogHeapCorruption(holder, offset, ref, /* fatal */ true);
Mathieu Chartier1ca68902017-04-18 11:26:22 -07002529 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002530 // Not marked or on the allocation stack. Try to mark it.
2531 // This may or may not succeed, which is ok.
2532 bool cas_success = false;
2533 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002534 cas_success = ref->AtomicSetReadBarrierState(ReadBarrier::WhiteState(),
2535 ReadBarrier::GrayState());
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002536 }
2537 if (!is_los && mark_bitmap->AtomicTestAndSet(ref)) {
2538 // Already marked.
2539 if (kUseBakerReadBarrier && cas_success &&
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002540 ref->GetReadBarrierState() == ReadBarrier::GrayState()) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002541 PushOntoFalseGrayStack(ref);
2542 }
2543 } else if (is_los && los_bitmap->AtomicTestAndSet(ref)) {
2544 // Already marked in LOS.
2545 if (kUseBakerReadBarrier && cas_success &&
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002546 ref->GetReadBarrierState() == ReadBarrier::GrayState()) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002547 PushOntoFalseGrayStack(ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002548 }
2549 } else {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002550 // Newly marked.
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08002551 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002552 DCHECK_EQ(ref->GetReadBarrierState(), ReadBarrier::GrayState());
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08002553 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002554 PushOntoMarkStack(ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002555 }
2556 }
2557 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002558 return ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002559}
2560
2561void ConcurrentCopying::FinishPhase() {
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -08002562 Thread* const self = Thread::Current();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002563 {
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -08002564 MutexLock mu(self, mark_stack_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002565 CHECK_EQ(pooled_mark_stacks_.size(), kMarkStackPoolSize);
2566 }
Mathieu Chartiera1467d02017-02-22 09:22:50 -08002567 // kVerifyNoMissingCardMarks relies on the region space cards not being cleared to avoid false
2568 // positives.
2569 if (!kVerifyNoMissingCardMarks) {
Mathieu Chartier6e6078a2016-10-24 15:45:41 -07002570 TimingLogger::ScopedTiming split("ClearRegionSpaceCards", GetTimings());
2571 // We do not currently use the region space cards at all, madvise them away to save ram.
2572 heap_->GetCardTable()->ClearCardRange(region_space_->Begin(), region_space_->Limit());
Mathieu Chartier6e6078a2016-10-24 15:45:41 -07002573 }
2574 {
2575 MutexLock mu(self, skipped_blocks_lock_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002576 skipped_blocks_map_.clear();
2577 }
Mathieu Chartier56fe2582016-07-14 13:30:03 -07002578 {
2579 ReaderMutexLock mu(self, *Locks::mutator_lock_);
Mathieu Chartier21328a12016-07-22 10:47:45 -07002580 {
2581 WriterMutexLock mu2(self, *Locks::heap_bitmap_lock_);
2582 heap_->ClearMarkedObjects();
2583 }
2584 if (kUseBakerReadBarrier && kFilterModUnionCards) {
2585 TimingLogger::ScopedTiming split("FilterModUnionCards", GetTimings());
2586 ReaderMutexLock mu2(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier21328a12016-07-22 10:47:45 -07002587 for (space::ContinuousSpace* space : immune_spaces_.GetSpaces()) {
2588 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
Mathieu Chartier6e6078a2016-10-24 15:45:41 -07002589 accounting::ModUnionTable* table = heap_->FindModUnionTableFromSpace(space);
Mathieu Chartier21328a12016-07-22 10:47:45 -07002590 // Filter out cards that don't need to be set.
2591 if (table != nullptr) {
2592 table->FilterCards();
2593 }
2594 }
2595 }
Mathieu Chartier36a270a2016-07-28 18:08:51 -07002596 if (kUseBakerReadBarrier) {
2597 TimingLogger::ScopedTiming split("EmptyRBMarkBitStack", GetTimings());
Mathieu Chartier6e6078a2016-10-24 15:45:41 -07002598 DCHECK(rb_mark_bit_stack_ != nullptr);
Mathieu Chartier36a270a2016-07-28 18:08:51 -07002599 const auto* limit = rb_mark_bit_stack_->End();
2600 for (StackReference<mirror::Object>* it = rb_mark_bit_stack_->Begin(); it != limit; ++it) {
2601 CHECK(it->AsMirrorPtr()->AtomicSetMarkBit(1, 0));
2602 }
2603 rb_mark_bit_stack_->Reset();
2604 }
Mathieu Chartier56fe2582016-07-14 13:30:03 -07002605 }
2606 if (measure_read_barrier_slow_path_) {
2607 MutexLock mu(self, rb_slow_path_histogram_lock_);
2608 rb_slow_path_time_histogram_.AdjustAndAddValue(rb_slow_path_ns_.LoadRelaxed());
2609 rb_slow_path_count_total_ += rb_slow_path_count_.LoadRelaxed();
2610 rb_slow_path_count_gc_total_ += rb_slow_path_count_gc_.LoadRelaxed();
2611 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002612}
2613
Hiroshi Yamauchi65f5f242016-12-19 11:44:47 -08002614bool ConcurrentCopying::IsNullOrMarkedHeapReference(mirror::HeapReference<mirror::Object>* field,
2615 bool do_atomic_update) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002616 mirror::Object* from_ref = field->AsMirrorPtr();
Hiroshi Yamauchi65f5f242016-12-19 11:44:47 -08002617 if (from_ref == nullptr) {
2618 return true;
2619 }
Mathieu Chartier97509952015-07-13 14:35:43 -07002620 mirror::Object* to_ref = IsMarked(from_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002621 if (to_ref == nullptr) {
2622 return false;
2623 }
2624 if (from_ref != to_ref) {
Hiroshi Yamauchi65f5f242016-12-19 11:44:47 -08002625 if (do_atomic_update) {
2626 do {
2627 if (field->AsMirrorPtr() != from_ref) {
2628 // Concurrently overwritten by a mutator.
2629 break;
2630 }
2631 } while (!field->CasWeakRelaxed(from_ref, to_ref));
2632 } else {
Hans Boehmcc55e1d2017-07-27 15:28:07 -07002633 // TODO: Why is this seq_cst when the above is relaxed? Document memory ordering.
2634 field->Assign</* kIsVolatile */ true>(to_ref);
Hiroshi Yamauchi65f5f242016-12-19 11:44:47 -08002635 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002636 }
2637 return true;
2638}
2639
Mathieu Chartier97509952015-07-13 14:35:43 -07002640mirror::Object* ConcurrentCopying::MarkObject(mirror::Object* from_ref) {
2641 return Mark(from_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002642}
2643
Mathieu Chartier31e88222016-10-14 18:43:19 -07002644void ConcurrentCopying::DelayReferenceReferent(ObjPtr<mirror::Class> klass,
2645 ObjPtr<mirror::Reference> reference) {
Mathieu Chartier97509952015-07-13 14:35:43 -07002646 heap_->GetReferenceProcessor()->DelayReferenceReferent(klass, reference, this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002647}
2648
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002649void ConcurrentCopying::ProcessReferences(Thread* self) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002650 TimingLogger::ScopedTiming split("ProcessReferences", GetTimings());
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002651 // 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 -08002652 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
2653 GetHeap()->GetReferenceProcessor()->ProcessReferences(
Mathieu Chartier97509952015-07-13 14:35:43 -07002654 true /*concurrent*/, GetTimings(), GetCurrentIteration()->GetClearSoftReferences(), this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002655}
2656
2657void ConcurrentCopying::RevokeAllThreadLocalBuffers() {
2658 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
2659 region_space_->RevokeAllThreadLocalBuffers();
2660}
2661
Mathieu Chartier56fe2582016-07-14 13:30:03 -07002662mirror::Object* ConcurrentCopying::MarkFromReadBarrierWithMeasurements(mirror::Object* from_ref) {
2663 if (Thread::Current() != thread_running_gc_) {
2664 rb_slow_path_count_.FetchAndAddRelaxed(1u);
2665 } else {
2666 rb_slow_path_count_gc_.FetchAndAddRelaxed(1u);
2667 }
2668 ScopedTrace tr(__FUNCTION__);
2669 const uint64_t start_time = measure_read_barrier_slow_path_ ? NanoTime() : 0u;
2670 mirror::Object* ret = Mark(from_ref);
2671 if (measure_read_barrier_slow_path_) {
2672 rb_slow_path_ns_.FetchAndAddRelaxed(NanoTime() - start_time);
2673 }
2674 return ret;
2675}
2676
2677void ConcurrentCopying::DumpPerformanceInfo(std::ostream& os) {
2678 GarbageCollector::DumpPerformanceInfo(os);
2679 MutexLock mu(Thread::Current(), rb_slow_path_histogram_lock_);
2680 if (rb_slow_path_time_histogram_.SampleSize() > 0) {
2681 Histogram<uint64_t>::CumulativeData cumulative_data;
2682 rb_slow_path_time_histogram_.CreateHistogram(&cumulative_data);
2683 rb_slow_path_time_histogram_.PrintConfidenceIntervals(os, 0.99, cumulative_data);
2684 }
2685 if (rb_slow_path_count_total_ > 0) {
2686 os << "Slow path count " << rb_slow_path_count_total_ << "\n";
2687 }
2688 if (rb_slow_path_count_gc_total_ > 0) {
2689 os << "GC slow path count " << rb_slow_path_count_gc_total_ << "\n";
2690 }
Mathieu Chartiercca44a02016-08-17 10:07:29 -07002691 os << "Cumulative bytes moved " << cumulative_bytes_moved_.LoadRelaxed() << "\n";
2692 os << "Cumulative objects moved " << cumulative_objects_moved_.LoadRelaxed() << "\n";
Mathieu Chartier56fe2582016-07-14 13:30:03 -07002693}
2694
Hiroshi Yamauchid5307ec2014-03-27 21:07:51 -07002695} // namespace collector
2696} // namespace gc
2697} // namespace art