blob: 54882874c6e3540649958fc90ff263c8ecc1621f [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"
Mathieu Chartier56fe2582016-07-14 13:30:03 -070021#include "base/histogram-inl.h"
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070022#include "base/stl_util.h"
Mathieu Chartier56fe2582016-07-14 13:30:03 -070023#include "base/systrace.h"
Mathieu Chartiera6b1ead2015-10-06 10:32:38 -070024#include "debugger.h"
Andreas Gampe291ce172017-04-24 13:22:18 -070025#include "gc/accounting/atomic_stack.h"
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080026#include "gc/accounting/heap_bitmap-inl.h"
Mathieu Chartier21328a12016-07-22 10:47:45 -070027#include "gc/accounting/mod_union_table-inl.h"
Andreas Gampe291ce172017-04-24 13:22:18 -070028#include "gc/accounting/read_barrier_table.h"
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080029#include "gc/accounting/space_bitmap-inl.h"
Andreas Gampe4934eb12017-01-30 13:15:26 -080030#include "gc/gc_pause_listener.h"
Mathieu Chartier3cf22532015-07-09 15:15:09 -070031#include "gc/reference_processor.h"
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080032#include "gc/space/image_space.h"
Mathieu Chartier073b16c2015-11-10 14:13:23 -080033#include "gc/space/space-inl.h"
Mathieu Chartier1ca68902017-04-18 11:26:22 -070034#include "gc/verification.h"
Mathieu Chartier4a26f172016-01-26 14:26:18 -080035#include "image-inl.h"
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080036#include "intern_table.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070037#include "mirror/class-inl.h"
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080038#include "mirror/object-inl.h"
Andreas Gampec6ea7d02017-02-01 16:46:28 -080039#include "mirror/object-refvisitor-inl.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070040#include "scoped_thread_state_change-inl.h"
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080041#include "thread-inl.h"
42#include "thread_list.h"
43#include "well_known_classes.h"
44
Hiroshi Yamauchid5307ec2014-03-27 21:07:51 -070045namespace art {
46namespace gc {
47namespace collector {
48
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -070049static constexpr size_t kDefaultGcMarkStackSize = 2 * MB;
Mathieu Chartier21328a12016-07-22 10:47:45 -070050// If kFilterModUnionCards then we attempt to filter cards that don't need to be dirty in the mod
51// union table. Disabled since it does not seem to help the pause much.
52static constexpr bool kFilterModUnionCards = kIsDebugBuild;
Mathieu Chartierd6636d32016-07-28 11:02:38 -070053// If kDisallowReadBarrierDuringScan is true then the GC aborts if there are any that occur during
54// ConcurrentCopying::Scan. May be used to diagnose possibly unnecessary read barriers.
55// Only enabled for kIsDebugBuild to avoid performance hit.
56static constexpr bool kDisallowReadBarrierDuringScan = kIsDebugBuild;
Mathieu Chartier36a270a2016-07-28 18:08:51 -070057// Slow path mark stack size, increase this if the stack is getting full and it is causing
58// performance problems.
59static constexpr size_t kReadBarrierMarkStackSize = 512 * KB;
Mathieu Chartiera1467d02017-02-22 09:22:50 -080060// Verify that there are no missing card marks.
61static constexpr bool kVerifyNoMissingCardMarks = kIsDebugBuild;
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -070062
Mathieu Chartier56fe2582016-07-14 13:30:03 -070063ConcurrentCopying::ConcurrentCopying(Heap* heap,
64 const std::string& name_prefix,
65 bool measure_read_barrier_slow_path)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080066 : GarbageCollector(heap,
67 name_prefix + (name_prefix.empty() ? "" : " ") +
Hiroshi Yamauchi88e08162017-01-06 15:03:26 -080068 "concurrent copying"),
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070069 region_space_(nullptr), gc_barrier_(new Barrier(0)),
70 gc_mark_stack_(accounting::ObjectStack::Create("concurrent copying gc mark stack",
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -070071 kDefaultGcMarkStackSize,
72 kDefaultGcMarkStackSize)),
Mathieu Chartier36a270a2016-07-28 18:08:51 -070073 rb_mark_bit_stack_(accounting::ObjectStack::Create("rb copying gc mark stack",
74 kReadBarrierMarkStackSize,
75 kReadBarrierMarkStackSize)),
76 rb_mark_bit_stack_full_(false),
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070077 mark_stack_lock_("concurrent copying mark stack lock", kMarkSweepMarkStackLock),
78 thread_running_gc_(nullptr),
Andreas Gamped9911ee2017-03-27 13:27:24 -070079 is_marking_(false),
Mathieu Chartier3768ade2017-05-02 14:04:39 -070080 is_using_read_barrier_entrypoints_(false),
Andreas Gamped9911ee2017-03-27 13:27:24 -070081 is_active_(false),
82 is_asserting_to_space_invariant_(false),
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -070083 region_space_bitmap_(nullptr),
Andreas Gamped9911ee2017-03-27 13:27:24 -070084 heap_mark_bitmap_(nullptr),
85 live_stack_freeze_size_(0),
86 from_space_num_objects_at_first_pause_(0),
87 from_space_num_bytes_at_first_pause_(0),
88 mark_stack_mode_(kMarkStackModeOff),
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070089 weak_ref_access_enabled_(true),
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080090 skipped_blocks_lock_("concurrent copying bytes blocks lock", kMarkSweepMarkStackLock),
Mathieu Chartier56fe2582016-07-14 13:30:03 -070091 measure_read_barrier_slow_path_(measure_read_barrier_slow_path),
Andreas Gamped9911ee2017-03-27 13:27:24 -070092 mark_from_read_barrier_measurements_(false),
Mathieu Chartier56fe2582016-07-14 13:30:03 -070093 rb_slow_path_ns_(0),
94 rb_slow_path_count_(0),
95 rb_slow_path_count_gc_(0),
96 rb_slow_path_histogram_lock_("Read barrier histogram lock"),
97 rb_slow_path_time_histogram_("Mutator time in read barrier slow path", 500, 32),
98 rb_slow_path_count_total_(0),
99 rb_slow_path_count_gc_total_(0),
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800100 rb_table_(heap_->GetReadBarrierTable()),
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700101 force_evacuate_all_(false),
Andreas Gamped9911ee2017-03-27 13:27:24 -0700102 gc_grays_immune_objects_(false),
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700103 immune_gray_stack_lock_("concurrent copying immune gray stack lock",
104 kMarkSweepMarkStackLock) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800105 static_assert(space::RegionSpace::kRegionSize == accounting::ReadBarrierTable::kRegionSize,
106 "The region space size and the read barrier table region size must match");
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700107 Thread* self = Thread::Current();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800108 {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800109 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
110 // Cache this so that we won't have to lock heap_bitmap_lock_ in
111 // Mark() which could cause a nested lock on heap_bitmap_lock_
112 // when GC causes a RB while doing GC or a lock order violation
113 // (class_linker_lock_ and heap_bitmap_lock_).
114 heap_mark_bitmap_ = heap->GetMarkBitmap();
115 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700116 {
117 MutexLock mu(self, mark_stack_lock_);
118 for (size_t i = 0; i < kMarkStackPoolSize; ++i) {
119 accounting::AtomicStack<mirror::Object>* mark_stack =
120 accounting::AtomicStack<mirror::Object>::Create(
121 "thread local mark stack", kMarkStackSize, kMarkStackSize);
122 pooled_mark_stacks_.push_back(mark_stack);
123 }
124 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800125}
126
Hiroshi Yamauchi057d9772017-02-17 15:33:23 -0800127void ConcurrentCopying::MarkHeapReference(mirror::HeapReference<mirror::Object>* field,
128 bool do_atomic_update) {
129 if (UNLIKELY(do_atomic_update)) {
130 // Used to mark the referent in DelayReferenceReferent in transaction mode.
131 mirror::Object* from_ref = field->AsMirrorPtr();
132 if (from_ref == nullptr) {
133 return;
134 }
135 mirror::Object* to_ref = Mark(from_ref);
136 if (from_ref != to_ref) {
137 do {
138 if (field->AsMirrorPtr() != from_ref) {
139 // Concurrently overwritten by a mutator.
140 break;
141 }
142 } while (!field->CasWeakRelaxed(from_ref, to_ref));
143 }
144 } else {
145 // Used for preserving soft references, should be OK to not have a CAS here since there should be
146 // no other threads which can trigger read barriers on the same referent during reference
147 // processing.
148 field->Assign(Mark(field->AsMirrorPtr()));
149 }
Mathieu Chartier97509952015-07-13 14:35:43 -0700150}
151
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800152ConcurrentCopying::~ConcurrentCopying() {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700153 STLDeleteElements(&pooled_mark_stacks_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800154}
155
156void ConcurrentCopying::RunPhases() {
157 CHECK(kUseBakerReadBarrier || kUseTableLookupReadBarrier);
158 CHECK(!is_active_);
159 is_active_ = true;
160 Thread* self = Thread::Current();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700161 thread_running_gc_ = self;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800162 Locks::mutator_lock_->AssertNotHeld(self);
163 {
164 ReaderMutexLock mu(self, *Locks::mutator_lock_);
165 InitializePhase();
166 }
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700167 if (kUseBakerReadBarrier && kGrayDirtyImmuneObjects) {
168 // Switch to read barrier mark entrypoints before we gray the objects. This is required in case
169 // a mutator sees a gray bit and dispatches on the entrpoint. (b/37876887).
170 ActivateReadBarrierEntrypoints();
171 // Gray dirty immune objects concurrently to reduce GC pause times. We re-process gray cards in
172 // the pause.
173 ReaderMutexLock mu(self, *Locks::mutator_lock_);
174 GrayAllDirtyImmuneObjects();
175 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800176 FlipThreadRoots();
177 {
178 ReaderMutexLock mu(self, *Locks::mutator_lock_);
179 MarkingPhase();
180 }
181 // Verify no from space refs. This causes a pause.
Andreas Gampee3ce7872017-02-22 13:36:21 -0800182 if (kEnableNoFromSpaceRefsVerification) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800183 TimingLogger::ScopedTiming split("(Paused)VerifyNoFromSpaceReferences", GetTimings());
Andreas Gampe4934eb12017-01-30 13:15:26 -0800184 ScopedPause pause(this, false);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700185 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800186 if (kVerboseMode) {
187 LOG(INFO) << "Verifying no from-space refs";
188 }
189 VerifyNoFromSpaceReferences();
Mathieu Chartier720e71a2015-04-06 17:10:58 -0700190 if (kVerboseMode) {
191 LOG(INFO) << "Done verifying no from-space refs";
192 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700193 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800194 }
195 {
196 ReaderMutexLock mu(self, *Locks::mutator_lock_);
197 ReclaimPhase();
198 }
199 FinishPhase();
200 CHECK(is_active_);
201 is_active_ = false;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700202 thread_running_gc_ = nullptr;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800203}
204
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700205class ConcurrentCopying::ActivateReadBarrierEntrypointsCheckpoint : public Closure {
206 public:
207 explicit ActivateReadBarrierEntrypointsCheckpoint(ConcurrentCopying* concurrent_copying)
208 : concurrent_copying_(concurrent_copying) {}
209
210 void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
211 // Note: self is not necessarily equal to thread since thread may be suspended.
212 Thread* self = Thread::Current();
213 DCHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
214 << thread->GetState() << " thread " << thread << " self " << self;
215 // Switch to the read barrier entrypoints.
216 thread->SetReadBarrierEntrypoints();
217 // If thread is a running mutator, then act on behalf of the garbage collector.
218 // See the code in ThreadList::RunCheckpoint.
219 concurrent_copying_->GetBarrier().Pass(self);
220 }
221
222 private:
223 ConcurrentCopying* const concurrent_copying_;
224};
225
226class ConcurrentCopying::ActivateReadBarrierEntrypointsCallback : public Closure {
227 public:
228 explicit ActivateReadBarrierEntrypointsCallback(ConcurrentCopying* concurrent_copying)
229 : concurrent_copying_(concurrent_copying) {}
230
231 void Run(Thread* self ATTRIBUTE_UNUSED) OVERRIDE REQUIRES(Locks::thread_list_lock_) {
232 // This needs to run under the thread_list_lock_ critical section in ThreadList::RunCheckpoint()
233 // to avoid a race with ThreadList::Register().
234 CHECK(!concurrent_copying_->is_using_read_barrier_entrypoints_);
235 concurrent_copying_->is_using_read_barrier_entrypoints_ = true;
236 }
237
238 private:
239 ConcurrentCopying* const concurrent_copying_;
240};
241
242void ConcurrentCopying::ActivateReadBarrierEntrypoints() {
243 Thread* const self = Thread::Current();
244 ActivateReadBarrierEntrypointsCheckpoint checkpoint(this);
245 ThreadList* thread_list = Runtime::Current()->GetThreadList();
246 gc_barrier_->Init(self, 0);
247 ActivateReadBarrierEntrypointsCallback callback(this);
248 const size_t barrier_count = thread_list->RunCheckpoint(&checkpoint, &callback);
249 // If there are no threads to wait which implies that all the checkpoint functions are finished,
250 // then no need to release the mutator lock.
251 if (barrier_count == 0) {
252 return;
253 }
254 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
255 gc_barrier_->Increment(self, barrier_count);
256}
257
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800258void ConcurrentCopying::BindBitmaps() {
259 Thread* self = Thread::Current();
260 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
261 // Mark all of the spaces we never collect as immune.
262 for (const auto& space : heap_->GetContinuousSpaces()) {
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800263 if (space->GetGcRetentionPolicy() == space::kGcRetentionPolicyNeverCollect ||
264 space->GetGcRetentionPolicy() == space::kGcRetentionPolicyFullCollect) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800265 CHECK(space->IsZygoteSpace() || space->IsImageSpace());
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800266 immune_spaces_.AddSpace(space);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800267 } else if (space == region_space_) {
Mathieu Chartier7ec38dc2016-10-07 15:24:46 -0700268 // It is OK to clear the bitmap with mutators running since the only place it is read is
269 // VisitObjects which has exclusion with CC.
270 region_space_bitmap_ = region_space_->GetMarkBitmap();
271 region_space_bitmap_->Clear();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800272 }
273 }
274}
275
276void ConcurrentCopying::InitializePhase() {
277 TimingLogger::ScopedTiming split("InitializePhase", GetTimings());
278 if (kVerboseMode) {
279 LOG(INFO) << "GC InitializePhase";
280 LOG(INFO) << "Region-space : " << reinterpret_cast<void*>(region_space_->Begin()) << "-"
281 << reinterpret_cast<void*>(region_space_->Limit());
282 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700283 CheckEmptyMarkStack();
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800284 if (kIsDebugBuild) {
285 MutexLock mu(Thread::Current(), mark_stack_lock_);
286 CHECK(false_gray_stack_.empty());
287 }
Mathieu Chartier56fe2582016-07-14 13:30:03 -0700288
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700289 rb_mark_bit_stack_full_ = false;
Mathieu Chartier56fe2582016-07-14 13:30:03 -0700290 mark_from_read_barrier_measurements_ = measure_read_barrier_slow_path_;
291 if (measure_read_barrier_slow_path_) {
292 rb_slow_path_ns_.StoreRelaxed(0);
293 rb_slow_path_count_.StoreRelaxed(0);
294 rb_slow_path_count_gc_.StoreRelaxed(0);
295 }
296
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800297 immune_spaces_.Reset();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800298 bytes_moved_.StoreRelaxed(0);
299 objects_moved_.StoreRelaxed(0);
Hiroshi Yamauchi60985b72016-08-24 13:53:12 -0700300 GcCause gc_cause = GetCurrentIteration()->GetGcCause();
301 if (gc_cause == kGcCauseExplicit ||
Richard Uhlerda1da8a2017-05-16 13:37:32 +0000302 gc_cause == kGcCauseForNativeAllocBlocking ||
Hiroshi Yamauchi60985b72016-08-24 13:53:12 -0700303 gc_cause == kGcCauseCollectorTransition ||
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800304 GetCurrentIteration()->GetClearSoftReferences()) {
305 force_evacuate_all_ = true;
306 } else {
307 force_evacuate_all_ = false;
308 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700309 if (kUseBakerReadBarrier) {
310 updated_all_immune_objects_.StoreRelaxed(false);
311 // GC may gray immune objects in the thread flip.
312 gc_grays_immune_objects_ = true;
313 if (kIsDebugBuild) {
314 MutexLock mu(Thread::Current(), immune_gray_stack_lock_);
315 DCHECK(immune_gray_stack_.empty());
316 }
317 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800318 BindBitmaps();
319 if (kVerboseMode) {
320 LOG(INFO) << "force_evacuate_all=" << force_evacuate_all_;
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800321 LOG(INFO) << "Largest immune region: " << immune_spaces_.GetLargestImmuneRegion().Begin()
322 << "-" << immune_spaces_.GetLargestImmuneRegion().End();
323 for (space::ContinuousSpace* space : immune_spaces_.GetSpaces()) {
324 LOG(INFO) << "Immune space: " << *space;
325 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800326 LOG(INFO) << "GC end of InitializePhase";
327 }
Mathieu Chartier962cd7a2016-08-16 12:15:59 -0700328 // Mark all of the zygote large objects without graying them.
329 MarkZygoteLargeObjects();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800330}
331
332// Used to switch the thread roots of a thread from from-space refs to to-space refs.
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700333class ConcurrentCopying::ThreadFlipVisitor : public Closure, public RootVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800334 public:
Roland Levillain3887c462015-08-12 18:15:42 +0100335 ThreadFlipVisitor(ConcurrentCopying* concurrent_copying, bool use_tlab)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800336 : concurrent_copying_(concurrent_copying), use_tlab_(use_tlab) {
337 }
338
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700339 virtual void Run(Thread* thread) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800340 // Note: self is not necessarily equal to thread since thread may be suspended.
341 Thread* self = Thread::Current();
342 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
343 << thread->GetState() << " thread " << thread << " self " << self;
Mathieu Chartierfe814e82016-11-09 14:32:49 -0800344 thread->SetIsGcMarkingAndUpdateEntrypoints(true);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800345 if (use_tlab_ && thread->HasTlab()) {
346 if (ConcurrentCopying::kEnableFromSpaceAccountingCheck) {
347 // This must come before the revoke.
348 size_t thread_local_objects = thread->GetThreadLocalObjectsAllocated();
349 concurrent_copying_->region_space_->RevokeThreadLocalBuffers(thread);
350 reinterpret_cast<Atomic<size_t>*>(&concurrent_copying_->from_space_num_objects_at_first_pause_)->
351 FetchAndAddSequentiallyConsistent(thread_local_objects);
352 } else {
353 concurrent_copying_->region_space_->RevokeThreadLocalBuffers(thread);
354 }
355 }
356 if (kUseThreadLocalAllocationStack) {
357 thread->RevokeThreadLocalAllocationStack();
358 }
359 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700360 // We can use the non-CAS VisitRoots functions below because we update thread-local GC roots
361 // only.
Andreas Gampe513061a2017-06-01 09:17:34 -0700362 thread->VisitRoots(this, kVisitRootFlagAllRoots);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800363 concurrent_copying_->GetBarrier().Pass(self);
364 }
365
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700366 void VisitRoots(mirror::Object*** roots,
367 size_t count,
368 const RootInfo& info ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700369 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700370 for (size_t i = 0; i < count; ++i) {
371 mirror::Object** root = roots[i];
372 mirror::Object* ref = *root;
373 if (ref != nullptr) {
374 mirror::Object* to_ref = concurrent_copying_->Mark(ref);
375 if (to_ref != ref) {
376 *root = to_ref;
377 }
378 }
379 }
380 }
381
382 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots,
383 size_t count,
384 const RootInfo& info ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700385 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700386 for (size_t i = 0; i < count; ++i) {
387 mirror::CompressedReference<mirror::Object>* const root = roots[i];
388 if (!root->IsNull()) {
389 mirror::Object* ref = root->AsMirrorPtr();
390 mirror::Object* to_ref = concurrent_copying_->Mark(ref);
391 if (to_ref != ref) {
392 root->Assign(to_ref);
393 }
394 }
395 }
396 }
397
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800398 private:
399 ConcurrentCopying* const concurrent_copying_;
400 const bool use_tlab_;
401};
402
403// Called back from Runtime::FlipThreadRoots() during a pause.
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700404class ConcurrentCopying::FlipCallback : public Closure {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800405 public:
406 explicit FlipCallback(ConcurrentCopying* concurrent_copying)
407 : concurrent_copying_(concurrent_copying) {
408 }
409
Mathieu Chartier90443472015-07-16 20:32:27 -0700410 virtual void Run(Thread* thread) OVERRIDE REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800411 ConcurrentCopying* cc = concurrent_copying_;
412 TimingLogger::ScopedTiming split("(Paused)FlipCallback", cc->GetTimings());
413 // Note: self is not necessarily equal to thread since thread may be suspended.
414 Thread* self = Thread::Current();
Mathieu Chartiera1467d02017-02-22 09:22:50 -0800415 if (kVerifyNoMissingCardMarks) {
416 cc->VerifyNoMissingCardMarks();
417 }
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700418 CHECK_EQ(thread, self);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800419 Locks::mutator_lock_->AssertExclusiveHeld(self);
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700420 {
421 TimingLogger::ScopedTiming split2("(Paused)SetFromSpace", cc->GetTimings());
422 cc->region_space_->SetFromSpace(cc->rb_table_, cc->force_evacuate_all_);
423 }
Mathieu Chartiera4f6af92015-08-11 17:35:25 -0700424 cc->SwapStacks();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800425 if (ConcurrentCopying::kEnableFromSpaceAccountingCheck) {
426 cc->RecordLiveStackFreezeSize(self);
427 cc->from_space_num_objects_at_first_pause_ = cc->region_space_->GetObjectsAllocated();
428 cc->from_space_num_bytes_at_first_pause_ = cc->region_space_->GetBytesAllocated();
429 }
430 cc->is_marking_ = true;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700431 cc->mark_stack_mode_.StoreRelaxed(ConcurrentCopying::kMarkStackModeThreadLocal);
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800432 if (kIsDebugBuild) {
433 cc->region_space_->AssertAllRegionLiveBytesZeroOrCleared();
434 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800435 if (UNLIKELY(Runtime::Current()->IsActiveTransaction())) {
Mathieu Chartier184c9dc2015-03-05 13:20:54 -0800436 CHECK(Runtime::Current()->IsAotCompiler());
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700437 TimingLogger::ScopedTiming split3("(Paused)VisitTransactionRoots", cc->GetTimings());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700438 Runtime::Current()->VisitTransactionRoots(cc);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800439 }
Mathieu Chartier21328a12016-07-22 10:47:45 -0700440 if (kUseBakerReadBarrier && kGrayDirtyImmuneObjects) {
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700441 cc->GrayAllNewlyDirtyImmuneObjects();
Mathieu Chartier21328a12016-07-22 10:47:45 -0700442 if (kIsDebugBuild) {
443 // Check that all non-gray immune objects only refernce immune objects.
444 cc->VerifyGrayImmuneObjects();
445 }
446 }
Mathieu Chartier9aef9922017-04-23 13:53:50 -0700447 // May be null during runtime creation, in this case leave java_lang_Object null.
448 // This is safe since single threaded behavior should mean FillDummyObject does not
449 // happen when java_lang_Object_ is null.
450 if (WellKnownClasses::java_lang_Object != nullptr) {
451 cc->java_lang_Object_ = down_cast<mirror::Class*>(cc->Mark(
452 WellKnownClasses::ToClass(WellKnownClasses::java_lang_Object).Ptr()));
453 } else {
454 cc->java_lang_Object_ = nullptr;
455 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800456 }
457
458 private:
459 ConcurrentCopying* const concurrent_copying_;
460};
461
Mathieu Chartier21328a12016-07-22 10:47:45 -0700462class ConcurrentCopying::VerifyGrayImmuneObjectsVisitor {
463 public:
464 explicit VerifyGrayImmuneObjectsVisitor(ConcurrentCopying* collector)
465 : collector_(collector) {}
466
Mathieu Chartier31e88222016-10-14 18:43:19 -0700467 void operator()(ObjPtr<mirror::Object> obj, MemberOffset offset, bool /* is_static */)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700468 const ALWAYS_INLINE REQUIRES_SHARED(Locks::mutator_lock_)
469 REQUIRES_SHARED(Locks::heap_bitmap_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700470 CheckReference(obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(offset),
471 obj, offset);
472 }
473
Mathieu Chartier31e88222016-10-14 18:43:19 -0700474 void operator()(ObjPtr<mirror::Class> klass, ObjPtr<mirror::Reference> ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700475 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700476 CHECK(klass->IsTypeOfReferenceClass());
477 CheckReference(ref->GetReferent<kWithoutReadBarrier>(),
478 ref,
479 mirror::Reference::ReferentOffset());
480 }
481
482 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
483 ALWAYS_INLINE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700484 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700485 if (!root->IsNull()) {
486 VisitRoot(root);
487 }
488 }
489
490 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
491 ALWAYS_INLINE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700492 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700493 CheckReference(root->AsMirrorPtr(), nullptr, MemberOffset(0));
494 }
495
496 private:
497 ConcurrentCopying* const collector_;
498
Mathieu Chartier31e88222016-10-14 18:43:19 -0700499 void CheckReference(ObjPtr<mirror::Object> ref,
500 ObjPtr<mirror::Object> holder,
501 MemberOffset offset) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700502 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700503 if (ref != nullptr) {
Mathieu Chartier31e88222016-10-14 18:43:19 -0700504 if (!collector_->immune_spaces_.ContainsObject(ref.Ptr())) {
Mathieu Chartier962cd7a2016-08-16 12:15:59 -0700505 // Not immune, must be a zygote large object.
506 CHECK(Runtime::Current()->GetHeap()->GetLargeObjectsSpace()->IsZygoteLargeObject(
Mathieu Chartier31e88222016-10-14 18:43:19 -0700507 Thread::Current(), ref.Ptr()))
Mathieu Chartier962cd7a2016-08-16 12:15:59 -0700508 << "Non gray object references non immune, non zygote large object "<< ref << " "
David Sehr709b0702016-10-13 09:12:37 -0700509 << mirror::Object::PrettyTypeOf(ref) << " in holder " << holder << " "
510 << mirror::Object::PrettyTypeOf(holder) << " offset=" << offset.Uint32Value();
Mathieu Chartier962cd7a2016-08-16 12:15:59 -0700511 } else {
512 // Make sure the large object class is immune since we will never scan the large object.
513 CHECK(collector_->immune_spaces_.ContainsObject(
514 ref->GetClass<kVerifyNone, kWithoutReadBarrier>()));
515 }
Mathieu Chartier21328a12016-07-22 10:47:45 -0700516 }
517 }
518};
519
520void ConcurrentCopying::VerifyGrayImmuneObjects() {
521 TimingLogger::ScopedTiming split(__FUNCTION__, GetTimings());
522 for (auto& space : immune_spaces_.GetSpaces()) {
523 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
524 accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
525 VerifyGrayImmuneObjectsVisitor visitor(this);
526 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()),
527 reinterpret_cast<uintptr_t>(space->Limit()),
528 [&visitor](mirror::Object* obj)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700529 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700530 // If an object is not gray, it should only have references to things in the immune spaces.
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700531 if (obj->GetReadBarrierState() != ReadBarrier::GrayState()) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700532 obj->VisitReferences</*kVisitNativeRoots*/true,
533 kDefaultVerifyFlags,
534 kWithoutReadBarrier>(visitor, visitor);
535 }
536 });
537 }
538}
539
Mathieu Chartiera1467d02017-02-22 09:22:50 -0800540class ConcurrentCopying::VerifyNoMissingCardMarkVisitor {
541 public:
542 VerifyNoMissingCardMarkVisitor(ConcurrentCopying* cc, ObjPtr<mirror::Object> holder)
543 : cc_(cc),
544 holder_(holder) {}
545
546 void operator()(ObjPtr<mirror::Object> obj,
547 MemberOffset offset,
548 bool is_static ATTRIBUTE_UNUSED) const
549 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
550 if (offset.Uint32Value() != mirror::Object::ClassOffset().Uint32Value()) {
551 CheckReference(obj->GetFieldObject<mirror::Object, kDefaultVerifyFlags, kWithoutReadBarrier>(
552 offset), offset.Uint32Value());
553 }
554 }
555 void operator()(ObjPtr<mirror::Class> klass,
556 ObjPtr<mirror::Reference> ref) const
557 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
558 CHECK(klass->IsTypeOfReferenceClass());
559 this->operator()(ref, mirror::Reference::ReferentOffset(), false);
560 }
561
562 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
563 REQUIRES_SHARED(Locks::mutator_lock_) {
564 if (!root->IsNull()) {
565 VisitRoot(root);
566 }
567 }
568
569 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
570 REQUIRES_SHARED(Locks::mutator_lock_) {
571 CheckReference(root->AsMirrorPtr());
572 }
573
574 void CheckReference(mirror::Object* ref, int32_t offset = -1) const
575 REQUIRES_SHARED(Locks::mutator_lock_) {
576 CHECK(ref == nullptr || !cc_->region_space_->IsInNewlyAllocatedRegion(ref))
577 << holder_->PrettyTypeOf() << "(" << holder_.Ptr() << ") references object "
578 << ref->PrettyTypeOf() << "(" << ref << ") in newly allocated region at offset=" << offset;
579 }
580
581 private:
582 ConcurrentCopying* const cc_;
583 ObjPtr<mirror::Object> const holder_;
584};
585
586void ConcurrentCopying::VerifyNoMissingCardMarkCallback(mirror::Object* obj, void* arg) {
587 auto* collector = reinterpret_cast<ConcurrentCopying*>(arg);
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700588 // Objects not on dirty or aged cards should never have references to newly allocated regions.
589 if (collector->heap_->GetCardTable()->GetCard(obj) == gc::accounting::CardTable::kCardClean) {
Mathieu Chartiera1467d02017-02-22 09:22:50 -0800590 VerifyNoMissingCardMarkVisitor visitor(collector, /*holder*/ obj);
591 obj->VisitReferences</*kVisitNativeRoots*/true, kVerifyNone, kWithoutReadBarrier>(
592 visitor,
593 visitor);
594 }
595}
596
597void ConcurrentCopying::VerifyNoMissingCardMarks() {
598 TimingLogger::ScopedTiming split(__FUNCTION__, GetTimings());
599 region_space_->Walk(&VerifyNoMissingCardMarkCallback, this);
600 {
601 ReaderMutexLock rmu(Thread::Current(), *Locks::heap_bitmap_lock_);
602 heap_->GetLiveBitmap()->Walk(&VerifyNoMissingCardMarkCallback, this);
603 }
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
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001215class ConcurrentCopying::VerifyNoFromSpaceRefsObjectVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001216 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001217 explicit VerifyNoFromSpaceRefsObjectVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001218 : collector_(collector) {}
1219 void operator()(mirror::Object* obj) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001220 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001221 ObjectCallback(obj, collector_);
1222 }
1223 static void ObjectCallback(mirror::Object* obj, void *arg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001224 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001225 CHECK(obj != nullptr);
1226 ConcurrentCopying* collector = reinterpret_cast<ConcurrentCopying*>(arg);
1227 space::RegionSpace* region_space = collector->RegionSpace();
1228 CHECK(!region_space->IsInFromSpace(obj)) << "Scanning object " << obj << " in from space";
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001229 VerifyNoFromSpaceRefsFieldVisitor visitor(collector);
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07001230 obj->VisitReferences</*kVisitNativeRoots*/true, kDefaultVerifyFlags, kWithoutReadBarrier>(
1231 visitor,
1232 visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001233 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001234 CHECK_EQ(obj->GetReadBarrierState(), ReadBarrier::WhiteState())
1235 << "obj=" << obj << " non-white rb_state " << obj->GetReadBarrierState();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001236 }
1237 }
1238
1239 private:
1240 ConcurrentCopying* const collector_;
1241};
1242
1243// Verify there's no from-space references left after the marking phase.
1244void ConcurrentCopying::VerifyNoFromSpaceReferences() {
1245 Thread* self = Thread::Current();
1246 DCHECK(Locks::mutator_lock_->IsExclusiveHeld(self));
Hiroshi Yamauchi00370822015-08-18 14:47:25 -07001247 // Verify all threads have is_gc_marking to be false
1248 {
1249 MutexLock mu(self, *Locks::thread_list_lock_);
1250 std::list<Thread*> thread_list = Runtime::Current()->GetThreadList()->GetList();
1251 for (Thread* thread : thread_list) {
1252 CHECK(!thread->GetIsGcMarking());
1253 }
1254 }
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001255 VerifyNoFromSpaceRefsObjectVisitor visitor(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001256 // Roots.
1257 {
1258 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001259 VerifyNoFromSpaceRefsVisitor ref_visitor(this);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001260 Runtime::Current()->VisitRoots(&ref_visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001261 }
1262 // The to-space.
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001263 region_space_->WalkToSpace(VerifyNoFromSpaceRefsObjectVisitor::ObjectCallback, this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001264 // Non-moving spaces.
1265 {
1266 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1267 heap_->GetMarkBitmap()->Visit(visitor);
1268 }
1269 // The alloc stack.
1270 {
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001271 VerifyNoFromSpaceRefsVisitor ref_visitor(this);
Mathieu Chartiercb535da2015-01-23 13:50:03 -08001272 for (auto* it = heap_->allocation_stack_->Begin(), *end = heap_->allocation_stack_->End();
1273 it < end; ++it) {
1274 mirror::Object* const obj = it->AsMirrorPtr();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001275 if (obj != nullptr && obj->GetClass() != nullptr) {
1276 // TODO: need to call this only if obj is alive?
1277 ref_visitor(obj);
1278 visitor(obj);
1279 }
1280 }
1281 }
1282 // TODO: LOS. But only refs in LOS are classes.
1283}
1284
1285// The following visitors are used to assert the to-space invariant.
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001286class ConcurrentCopying::AssertToSpaceInvariantRefsVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001287 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001288 explicit AssertToSpaceInvariantRefsVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001289 : collector_(collector) {}
1290
1291 void operator()(mirror::Object* ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001292 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001293 if (ref == nullptr) {
1294 // OK.
1295 return;
1296 }
1297 collector_->AssertToSpaceInvariant(nullptr, MemberOffset(0), ref);
1298 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001299
1300 private:
Mathieu Chartier97509952015-07-13 14:35:43 -07001301 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001302};
1303
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001304class ConcurrentCopying::AssertToSpaceInvariantFieldVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001305 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001306 explicit AssertToSpaceInvariantFieldVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001307 : collector_(collector) {}
1308
Mathieu Chartier31e88222016-10-14 18:43:19 -07001309 void operator()(ObjPtr<mirror::Object> obj,
1310 MemberOffset offset,
1311 bool is_static ATTRIBUTE_UNUSED) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001312 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001313 mirror::Object* ref =
1314 obj->GetFieldObject<mirror::Object, kDefaultVerifyFlags, kWithoutReadBarrier>(offset);
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001315 AssertToSpaceInvariantRefsVisitor visitor(collector_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001316 visitor(ref);
1317 }
Mathieu Chartier31e88222016-10-14 18:43:19 -07001318 void operator()(ObjPtr<mirror::Class> klass, ObjPtr<mirror::Reference> ref ATTRIBUTE_UNUSED) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001319 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001320 CHECK(klass->IsTypeOfReferenceClass());
1321 }
1322
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001323 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001324 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001325 if (!root->IsNull()) {
1326 VisitRoot(root);
1327 }
1328 }
1329
1330 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001331 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001332 AssertToSpaceInvariantRefsVisitor visitor(collector_);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001333 visitor(root->AsMirrorPtr());
1334 }
1335
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001336 private:
Mathieu Chartier97509952015-07-13 14:35:43 -07001337 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001338};
1339
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001340class ConcurrentCopying::AssertToSpaceInvariantObjectVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001341 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001342 explicit AssertToSpaceInvariantObjectVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001343 : collector_(collector) {}
1344 void operator()(mirror::Object* obj) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001345 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001346 ObjectCallback(obj, collector_);
1347 }
1348 static void ObjectCallback(mirror::Object* obj, void *arg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001349 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001350 CHECK(obj != nullptr);
1351 ConcurrentCopying* collector = reinterpret_cast<ConcurrentCopying*>(arg);
1352 space::RegionSpace* region_space = collector->RegionSpace();
1353 CHECK(!region_space->IsInFromSpace(obj)) << "Scanning object " << obj << " in from space";
1354 collector->AssertToSpaceInvariant(nullptr, MemberOffset(0), obj);
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001355 AssertToSpaceInvariantFieldVisitor visitor(collector);
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07001356 obj->VisitReferences</*kVisitNativeRoots*/true, kDefaultVerifyFlags, kWithoutReadBarrier>(
1357 visitor,
1358 visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001359 }
1360
1361 private:
Mathieu Chartier97509952015-07-13 14:35:43 -07001362 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001363};
1364
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001365class ConcurrentCopying::RevokeThreadLocalMarkStackCheckpoint : public Closure {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001366 public:
Roland Levillain3887c462015-08-12 18:15:42 +01001367 RevokeThreadLocalMarkStackCheckpoint(ConcurrentCopying* concurrent_copying,
1368 bool disable_weak_ref_access)
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001369 : concurrent_copying_(concurrent_copying),
1370 disable_weak_ref_access_(disable_weak_ref_access) {
1371 }
1372
1373 virtual void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
1374 // Note: self is not necessarily equal to thread since thread may be suspended.
1375 Thread* self = Thread::Current();
1376 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
1377 << thread->GetState() << " thread " << thread << " self " << self;
1378 // Revoke thread local mark stacks.
1379 accounting::AtomicStack<mirror::Object>* tl_mark_stack = thread->GetThreadLocalMarkStack();
1380 if (tl_mark_stack != nullptr) {
1381 MutexLock mu(self, concurrent_copying_->mark_stack_lock_);
1382 concurrent_copying_->revoked_mark_stacks_.push_back(tl_mark_stack);
1383 thread->SetThreadLocalMarkStack(nullptr);
1384 }
1385 // Disable weak ref access.
1386 if (disable_weak_ref_access_) {
1387 thread->SetWeakRefAccessEnabled(false);
1388 }
1389 // If thread is a running mutator, then act on behalf of the garbage collector.
1390 // See the code in ThreadList::RunCheckpoint.
Mathieu Chartier10d25082015-10-28 18:36:09 -07001391 concurrent_copying_->GetBarrier().Pass(self);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001392 }
1393
1394 private:
1395 ConcurrentCopying* const concurrent_copying_;
1396 const bool disable_weak_ref_access_;
1397};
1398
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001399void ConcurrentCopying::RevokeThreadLocalMarkStacks(bool disable_weak_ref_access,
1400 Closure* checkpoint_callback) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001401 Thread* self = Thread::Current();
1402 RevokeThreadLocalMarkStackCheckpoint check_point(this, disable_weak_ref_access);
1403 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1404 gc_barrier_->Init(self, 0);
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001405 size_t barrier_count = thread_list->RunCheckpoint(&check_point, checkpoint_callback);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001406 // If there are no threads to wait which implys that all the checkpoint functions are finished,
1407 // then no need to release the mutator lock.
1408 if (barrier_count == 0) {
1409 return;
1410 }
1411 Locks::mutator_lock_->SharedUnlock(self);
1412 {
1413 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
1414 gc_barrier_->Increment(self, barrier_count);
1415 }
1416 Locks::mutator_lock_->SharedLock(self);
1417}
1418
1419void ConcurrentCopying::RevokeThreadLocalMarkStack(Thread* thread) {
1420 Thread* self = Thread::Current();
1421 CHECK_EQ(self, thread);
1422 accounting::AtomicStack<mirror::Object>* tl_mark_stack = thread->GetThreadLocalMarkStack();
1423 if (tl_mark_stack != nullptr) {
1424 CHECK(is_marking_);
1425 MutexLock mu(self, mark_stack_lock_);
1426 revoked_mark_stacks_.push_back(tl_mark_stack);
1427 thread->SetThreadLocalMarkStack(nullptr);
1428 }
1429}
1430
1431void ConcurrentCopying::ProcessMarkStack() {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001432 if (kVerboseMode) {
1433 LOG(INFO) << "ProcessMarkStack. ";
1434 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001435 bool empty_prev = false;
1436 while (true) {
1437 bool empty = ProcessMarkStackOnce();
1438 if (empty_prev && empty) {
1439 // Saw empty mark stack for a second time, done.
1440 break;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001441 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001442 empty_prev = empty;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001443 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001444}
1445
1446bool ConcurrentCopying::ProcessMarkStackOnce() {
1447 Thread* self = Thread::Current();
1448 CHECK(thread_running_gc_ != nullptr);
1449 CHECK(self == thread_running_gc_);
1450 CHECK(self->GetThreadLocalMarkStack() == nullptr);
1451 size_t count = 0;
1452 MarkStackMode mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1453 if (mark_stack_mode == kMarkStackModeThreadLocal) {
1454 // Process the thread-local mark stacks and the GC mark stack.
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001455 count += ProcessThreadLocalMarkStacks(false, nullptr);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001456 while (!gc_mark_stack_->IsEmpty()) {
1457 mirror::Object* to_ref = gc_mark_stack_->PopBack();
1458 ProcessMarkStackRef(to_ref);
1459 ++count;
1460 }
1461 gc_mark_stack_->Reset();
1462 } else if (mark_stack_mode == kMarkStackModeShared) {
Hiroshi Yamauchi30493242016-11-03 13:06:52 -07001463 // Do an empty checkpoint to avoid a race with a mutator preempted in the middle of a read
1464 // barrier but before pushing onto the mark stack. b/32508093. Note the weak ref access is
1465 // disabled at this point.
1466 IssueEmptyCheckpoint();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001467 // Process the shared GC mark stack with a lock.
1468 {
1469 MutexLock mu(self, mark_stack_lock_);
1470 CHECK(revoked_mark_stacks_.empty());
1471 }
1472 while (true) {
1473 std::vector<mirror::Object*> refs;
1474 {
1475 // Copy refs with lock. Note the number of refs should be small.
1476 MutexLock mu(self, mark_stack_lock_);
1477 if (gc_mark_stack_->IsEmpty()) {
1478 break;
1479 }
1480 for (StackReference<mirror::Object>* p = gc_mark_stack_->Begin();
1481 p != gc_mark_stack_->End(); ++p) {
1482 refs.push_back(p->AsMirrorPtr());
1483 }
1484 gc_mark_stack_->Reset();
1485 }
1486 for (mirror::Object* ref : refs) {
1487 ProcessMarkStackRef(ref);
1488 ++count;
1489 }
1490 }
1491 } else {
1492 CHECK_EQ(static_cast<uint32_t>(mark_stack_mode),
1493 static_cast<uint32_t>(kMarkStackModeGcExclusive));
1494 {
1495 MutexLock mu(self, mark_stack_lock_);
1496 CHECK(revoked_mark_stacks_.empty());
1497 }
1498 // Process the GC mark stack in the exclusive mode. No need to take the lock.
1499 while (!gc_mark_stack_->IsEmpty()) {
1500 mirror::Object* to_ref = gc_mark_stack_->PopBack();
1501 ProcessMarkStackRef(to_ref);
1502 ++count;
1503 }
1504 gc_mark_stack_->Reset();
1505 }
1506
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001507 // Return true if the stack was empty.
1508 return count == 0;
1509}
1510
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001511size_t ConcurrentCopying::ProcessThreadLocalMarkStacks(bool disable_weak_ref_access,
1512 Closure* checkpoint_callback) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001513 // Run a checkpoint to collect all thread local mark stacks and iterate over them all.
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001514 RevokeThreadLocalMarkStacks(disable_weak_ref_access, checkpoint_callback);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001515 size_t count = 0;
1516 std::vector<accounting::AtomicStack<mirror::Object>*> mark_stacks;
1517 {
1518 MutexLock mu(Thread::Current(), mark_stack_lock_);
1519 // Make a copy of the mark stack vector.
1520 mark_stacks = revoked_mark_stacks_;
1521 revoked_mark_stacks_.clear();
1522 }
1523 for (accounting::AtomicStack<mirror::Object>* mark_stack : mark_stacks) {
1524 for (StackReference<mirror::Object>* p = mark_stack->Begin(); p != mark_stack->End(); ++p) {
1525 mirror::Object* to_ref = p->AsMirrorPtr();
1526 ProcessMarkStackRef(to_ref);
1527 ++count;
1528 }
1529 {
1530 MutexLock mu(Thread::Current(), mark_stack_lock_);
1531 if (pooled_mark_stacks_.size() >= kMarkStackPoolSize) {
1532 // The pool has enough. Delete it.
1533 delete mark_stack;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001534 } else {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001535 // Otherwise, put it into the pool for later reuse.
1536 mark_stack->Reset();
1537 pooled_mark_stacks_.push_back(mark_stack);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001538 }
1539 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001540 }
1541 return count;
1542}
1543
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001544inline void ConcurrentCopying::ProcessMarkStackRef(mirror::Object* to_ref) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001545 DCHECK(!region_space_->IsInFromSpace(to_ref));
1546 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001547 DCHECK(to_ref->GetReadBarrierState() == ReadBarrier::GrayState())
1548 << " " << to_ref << " " << to_ref->GetReadBarrierState()
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001549 << " is_marked=" << IsMarked(to_ref);
1550 }
Mathieu Chartierc381c362016-08-23 13:27:53 -07001551 bool add_to_live_bytes = false;
1552 if (region_space_->IsInUnevacFromSpace(to_ref)) {
1553 // Mark the bitmap only in the GC thread here so that we don't need a CAS.
1554 if (!kUseBakerReadBarrier || !region_space_bitmap_->Set(to_ref)) {
1555 // It may be already marked if we accidentally pushed the same object twice due to the racy
1556 // bitmap read in MarkUnevacFromSpaceRegion.
1557 Scan(to_ref);
1558 // Only add to the live bytes if the object was not already marked.
1559 add_to_live_bytes = true;
1560 }
1561 } else {
1562 Scan(to_ref);
1563 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001564 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001565 DCHECK(to_ref->GetReadBarrierState() == ReadBarrier::GrayState())
1566 << " " << to_ref << " " << to_ref->GetReadBarrierState()
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001567 << " is_marked=" << IsMarked(to_ref);
1568 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001569#ifdef USE_BAKER_OR_BROOKS_READ_BARRIER
Hiroshi Yamauchi39c12d42016-12-06 16:46:37 -08001570 mirror::Object* referent = nullptr;
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001571 if (UNLIKELY((to_ref->GetClass<kVerifyNone, kWithoutReadBarrier>()->IsTypeOfReferenceClass() &&
Hiroshi Yamauchi39c12d42016-12-06 16:46:37 -08001572 (referent = to_ref->AsReference()->GetReferent<kWithoutReadBarrier>()) != nullptr &&
1573 !IsInToSpace(referent)))) {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001574 // Leave this reference gray in the queue so that GetReferent() will trigger a read barrier. We
1575 // will change it to white later in ReferenceQueue::DequeuePendingReference().
Richard Uhlere3627402016-02-02 13:36:55 -08001576 DCHECK(to_ref->AsReference()->GetPendingNext() != nullptr) << "Left unenqueued ref gray " << to_ref;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001577 } else {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001578 // We may occasionally leave a reference white in the queue if its referent happens to be
1579 // concurrently marked after the Scan() call above has enqueued the Reference, in which case the
1580 // above IsInToSpace() evaluates to true and we change the color from gray to white here in this
1581 // else block.
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001582 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001583 bool success = to_ref->AtomicSetReadBarrierState</*kCasRelease*/true>(
1584 ReadBarrier::GrayState(),
1585 ReadBarrier::WhiteState());
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001586 DCHECK(success) << "Must succeed as we won the race.";
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001587 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001588 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001589#else
1590 DCHECK(!kUseBakerReadBarrier);
1591#endif
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001592
Mathieu Chartierc381c362016-08-23 13:27:53 -07001593 if (add_to_live_bytes) {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001594 // Add to the live bytes per unevacuated from space. Note this code is always run by the
1595 // GC-running thread (no synchronization required).
1596 DCHECK(region_space_bitmap_->Test(to_ref));
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07001597 size_t obj_size = to_ref->SizeOf<kDefaultVerifyFlags>();
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001598 size_t alloc_size = RoundUp(obj_size, space::RegionSpace::kAlignment);
1599 region_space_->AddLiveBytes(to_ref, alloc_size);
1600 }
Andreas Gampee3ce7872017-02-22 13:36:21 -08001601 if (ReadBarrier::kEnableToSpaceInvariantChecks) {
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001602 AssertToSpaceInvariantObjectVisitor visitor(this);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001603 visitor(to_ref);
1604 }
1605}
1606
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001607class ConcurrentCopying::DisableWeakRefAccessCallback : public Closure {
1608 public:
1609 explicit DisableWeakRefAccessCallback(ConcurrentCopying* concurrent_copying)
1610 : concurrent_copying_(concurrent_copying) {
1611 }
1612
1613 void Run(Thread* self ATTRIBUTE_UNUSED) OVERRIDE REQUIRES(Locks::thread_list_lock_) {
1614 // This needs to run under the thread_list_lock_ critical section in ThreadList::RunCheckpoint()
1615 // to avoid a deadlock b/31500969.
1616 CHECK(concurrent_copying_->weak_ref_access_enabled_);
1617 concurrent_copying_->weak_ref_access_enabled_ = false;
1618 }
1619
1620 private:
1621 ConcurrentCopying* const concurrent_copying_;
1622};
1623
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001624void ConcurrentCopying::SwitchToSharedMarkStackMode() {
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 before_mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1630 CHECK_EQ(static_cast<uint32_t>(before_mark_stack_mode),
1631 static_cast<uint32_t>(kMarkStackModeThreadLocal));
1632 mark_stack_mode_.StoreRelaxed(kMarkStackModeShared);
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001633 DisableWeakRefAccessCallback dwrac(this);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001634 // Process the thread local mark stacks one last time after switching to the shared mark stack
1635 // mode and disable weak ref accesses.
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001636 ProcessThreadLocalMarkStacks(true, &dwrac);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001637 if (kVerboseMode) {
1638 LOG(INFO) << "Switched to shared mark stack mode and disabled weak ref access";
1639 }
1640}
1641
1642void ConcurrentCopying::SwitchToGcExclusiveMarkStackMode() {
1643 Thread* self = Thread::Current();
1644 CHECK(thread_running_gc_ != nullptr);
1645 CHECK_EQ(self, thread_running_gc_);
1646 CHECK(self->GetThreadLocalMarkStack() == nullptr);
1647 MarkStackMode before_mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1648 CHECK_EQ(static_cast<uint32_t>(before_mark_stack_mode),
1649 static_cast<uint32_t>(kMarkStackModeShared));
1650 mark_stack_mode_.StoreRelaxed(kMarkStackModeGcExclusive);
1651 QuasiAtomic::ThreadFenceForConstructor();
1652 if (kVerboseMode) {
1653 LOG(INFO) << "Switched to GC exclusive mark stack mode";
1654 }
1655}
1656
1657void ConcurrentCopying::CheckEmptyMarkStack() {
1658 Thread* self = Thread::Current();
1659 CHECK(thread_running_gc_ != nullptr);
1660 CHECK_EQ(self, thread_running_gc_);
1661 CHECK(self->GetThreadLocalMarkStack() == nullptr);
1662 MarkStackMode mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1663 if (mark_stack_mode == kMarkStackModeThreadLocal) {
1664 // Thread-local mark stack mode.
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001665 RevokeThreadLocalMarkStacks(false, nullptr);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001666 MutexLock mu(Thread::Current(), mark_stack_lock_);
1667 if (!revoked_mark_stacks_.empty()) {
1668 for (accounting::AtomicStack<mirror::Object>* mark_stack : revoked_mark_stacks_) {
1669 while (!mark_stack->IsEmpty()) {
1670 mirror::Object* obj = mark_stack->PopBack();
1671 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001672 uint32_t rb_state = obj->GetReadBarrierState();
1673 LOG(INFO) << "On mark queue : " << obj << " " << obj->PrettyTypeOf() << " rb_state="
1674 << rb_state << " is_marked=" << IsMarked(obj);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001675 } else {
David Sehr709b0702016-10-13 09:12:37 -07001676 LOG(INFO) << "On mark queue : " << obj << " " << obj->PrettyTypeOf()
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001677 << " is_marked=" << IsMarked(obj);
1678 }
1679 }
1680 }
1681 LOG(FATAL) << "mark stack is not empty";
1682 }
1683 } else {
1684 // Shared, GC-exclusive, or off.
1685 MutexLock mu(Thread::Current(), mark_stack_lock_);
1686 CHECK(gc_mark_stack_->IsEmpty());
1687 CHECK(revoked_mark_stacks_.empty());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001688 }
1689}
1690
1691void ConcurrentCopying::SweepSystemWeaks(Thread* self) {
1692 TimingLogger::ScopedTiming split("SweepSystemWeaks", GetTimings());
1693 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier97509952015-07-13 14:35:43 -07001694 Runtime::Current()->SweepSystemWeaks(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001695}
1696
1697void ConcurrentCopying::Sweep(bool swap_bitmaps) {
1698 {
1699 TimingLogger::ScopedTiming t("MarkStackAsLive", GetTimings());
1700 accounting::ObjectStack* live_stack = heap_->GetLiveStack();
1701 if (kEnableFromSpaceAccountingCheck) {
1702 CHECK_GE(live_stack_freeze_size_, live_stack->Size());
1703 }
1704 heap_->MarkAllocStackAsLive(live_stack);
1705 live_stack->Reset();
1706 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001707 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001708 TimingLogger::ScopedTiming split("Sweep", GetTimings());
1709 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
1710 if (space->IsContinuousMemMapAllocSpace()) {
1711 space::ContinuousMemMapAllocSpace* alloc_space = space->AsContinuousMemMapAllocSpace();
Mathieu Chartier763a31e2015-11-16 16:05:55 -08001712 if (space == region_space_ || immune_spaces_.ContainsSpace(space)) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001713 continue;
1714 }
1715 TimingLogger::ScopedTiming split2(
1716 alloc_space->IsZygoteSpace() ? "SweepZygoteSpace" : "SweepAllocSpace", GetTimings());
1717 RecordFree(alloc_space->Sweep(swap_bitmaps));
1718 }
1719 }
1720 SweepLargeObjects(swap_bitmaps);
1721}
1722
Mathieu Chartier962cd7a2016-08-16 12:15:59 -07001723void ConcurrentCopying::MarkZygoteLargeObjects() {
1724 TimingLogger::ScopedTiming split(__FUNCTION__, GetTimings());
1725 Thread* const self = Thread::Current();
1726 WriterMutexLock rmu(self, *Locks::heap_bitmap_lock_);
1727 space::LargeObjectSpace* const los = heap_->GetLargeObjectsSpace();
Nicolas Geoffray7acddd82017-05-03 15:04:55 +01001728 if (los != nullptr) {
1729 // Pick the current live bitmap (mark bitmap if swapped).
1730 accounting::LargeObjectBitmap* const live_bitmap = los->GetLiveBitmap();
1731 accounting::LargeObjectBitmap* const mark_bitmap = los->GetMarkBitmap();
1732 // Walk through all of the objects and explicitly mark the zygote ones so they don't get swept.
1733 std::pair<uint8_t*, uint8_t*> range = los->GetBeginEndAtomic();
1734 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(range.first),
1735 reinterpret_cast<uintptr_t>(range.second),
1736 [mark_bitmap, los, self](mirror::Object* obj)
1737 REQUIRES(Locks::heap_bitmap_lock_)
1738 REQUIRES_SHARED(Locks::mutator_lock_) {
1739 if (los->IsZygoteLargeObject(self, obj)) {
1740 mark_bitmap->Set(obj);
1741 }
1742 });
1743 }
Mathieu Chartier962cd7a2016-08-16 12:15:59 -07001744}
1745
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001746void ConcurrentCopying::SweepLargeObjects(bool swap_bitmaps) {
1747 TimingLogger::ScopedTiming split("SweepLargeObjects", GetTimings());
Nicolas Geoffray7acddd82017-05-03 15:04:55 +01001748 if (heap_->GetLargeObjectsSpace() != nullptr) {
1749 RecordFreeLOS(heap_->GetLargeObjectsSpace()->Sweep(swap_bitmaps));
1750 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001751}
1752
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001753void ConcurrentCopying::ReclaimPhase() {
1754 TimingLogger::ScopedTiming split("ReclaimPhase", GetTimings());
1755 if (kVerboseMode) {
1756 LOG(INFO) << "GC ReclaimPhase";
1757 }
1758 Thread* self = Thread::Current();
1759
1760 {
1761 // Double-check that the mark stack is empty.
1762 // Note: need to set this after VerifyNoFromSpaceRef().
1763 is_asserting_to_space_invariant_ = false;
1764 QuasiAtomic::ThreadFenceForConstructor();
1765 if (kVerboseMode) {
1766 LOG(INFO) << "Issue an empty check point. ";
1767 }
1768 IssueEmptyCheckpoint();
1769 // Disable the check.
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001770 is_mark_stack_push_disallowed_.StoreSequentiallyConsistent(0);
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001771 if (kUseBakerReadBarrier) {
1772 updated_all_immune_objects_.StoreSequentiallyConsistent(false);
1773 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001774 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001775 }
1776
1777 {
1778 // Record freed objects.
1779 TimingLogger::ScopedTiming split2("RecordFree", GetTimings());
1780 // Don't include thread-locals that are in the to-space.
Mathieu Chartier371b0472017-02-27 16:37:21 -08001781 const uint64_t from_bytes = region_space_->GetBytesAllocatedInFromSpace();
1782 const uint64_t from_objects = region_space_->GetObjectsAllocatedInFromSpace();
1783 const uint64_t unevac_from_bytes = region_space_->GetBytesAllocatedInUnevacFromSpace();
1784 const uint64_t unevac_from_objects = region_space_->GetObjectsAllocatedInUnevacFromSpace();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001785 uint64_t to_bytes = bytes_moved_.LoadSequentiallyConsistent();
Mathieu Chartiercca44a02016-08-17 10:07:29 -07001786 cumulative_bytes_moved_.FetchAndAddRelaxed(to_bytes);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001787 uint64_t to_objects = objects_moved_.LoadSequentiallyConsistent();
Mathieu Chartiercca44a02016-08-17 10:07:29 -07001788 cumulative_objects_moved_.FetchAndAddRelaxed(to_objects);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001789 if (kEnableFromSpaceAccountingCheck) {
1790 CHECK_EQ(from_space_num_objects_at_first_pause_, from_objects + unevac_from_objects);
1791 CHECK_EQ(from_space_num_bytes_at_first_pause_, from_bytes + unevac_from_bytes);
1792 }
1793 CHECK_LE(to_objects, from_objects);
1794 CHECK_LE(to_bytes, from_bytes);
Mathieu Chartier371b0472017-02-27 16:37:21 -08001795 // cleared_bytes and cleared_objects may be greater than the from space equivalents since
1796 // ClearFromSpace may clear empty unevac regions.
1797 uint64_t cleared_bytes;
1798 uint64_t cleared_objects;
1799 {
1800 TimingLogger::ScopedTiming split4("ClearFromSpace", GetTimings());
1801 region_space_->ClearFromSpace(&cleared_bytes, &cleared_objects);
1802 CHECK_GE(cleared_bytes, from_bytes);
1803 CHECK_GE(cleared_objects, from_objects);
1804 }
1805 int64_t freed_bytes = cleared_bytes - to_bytes;
1806 int64_t freed_objects = cleared_objects - to_objects;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001807 if (kVerboseMode) {
1808 LOG(INFO) << "RecordFree:"
1809 << " from_bytes=" << from_bytes << " from_objects=" << from_objects
1810 << " unevac_from_bytes=" << unevac_from_bytes << " unevac_from_objects=" << unevac_from_objects
1811 << " to_bytes=" << to_bytes << " to_objects=" << to_objects
1812 << " freed_bytes=" << freed_bytes << " freed_objects=" << freed_objects
1813 << " from_space size=" << region_space_->FromSpaceSize()
1814 << " unevac_from_space size=" << region_space_->UnevacFromSpaceSize()
1815 << " to_space size=" << region_space_->ToSpaceSize();
1816 LOG(INFO) << "(before) num_bytes_allocated=" << heap_->num_bytes_allocated_.LoadSequentiallyConsistent();
1817 }
1818 RecordFree(ObjectBytePair(freed_objects, freed_bytes));
1819 if (kVerboseMode) {
1820 LOG(INFO) << "(after) num_bytes_allocated=" << heap_->num_bytes_allocated_.LoadSequentiallyConsistent();
1821 }
1822 }
1823
1824 {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001825 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001826 Sweep(false);
1827 SwapBitmaps();
1828 heap_->UnBindBitmaps();
1829
Mathieu Chartier7ec38dc2016-10-07 15:24:46 -07001830 // 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 -07001831 DCHECK(region_space_bitmap_ != nullptr);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001832 region_space_bitmap_ = nullptr;
1833 }
1834
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001835 CheckEmptyMarkStack();
1836
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001837 if (kVerboseMode) {
1838 LOG(INFO) << "GC end of ReclaimPhase";
1839 }
1840}
1841
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001842// Assert the to-space invariant.
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07001843void ConcurrentCopying::AssertToSpaceInvariant(mirror::Object* obj,
1844 MemberOffset offset,
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001845 mirror::Object* ref) {
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07001846 CHECK_EQ(heap_->collector_type_, kCollectorTypeCC);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001847 if (is_asserting_to_space_invariant_) {
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07001848 using RegionType = space::RegionSpace::RegionType;
1849 space::RegionSpace::RegionType type = region_space_->GetRegionType(ref);
1850 if (type == RegionType::kRegionTypeToSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001851 // OK.
1852 return;
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07001853 } else if (type == RegionType::kRegionTypeUnevacFromSpace) {
Mathieu Chartierc381c362016-08-23 13:27:53 -07001854 CHECK(IsMarkedInUnevacFromSpace(ref)) << ref;
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07001855 } else if (UNLIKELY(type == RegionType::kRegionTypeFromSpace)) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001856 // Not OK. Do extra logging.
1857 if (obj != nullptr) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001858 LogFromSpaceRefHolder(obj, offset);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001859 }
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07001860 ref->GetLockWord(false).Dump(LOG_STREAM(FATAL_WITHOUT_ABORT));
David Sehr709b0702016-10-13 09:12:37 -07001861 CHECK(false) << "Found from-space ref " << ref << " " << ref->PrettyTypeOf();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001862 } else {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001863 AssertToSpaceInvariantInNonMovingSpace(obj, ref);
1864 }
1865 }
1866}
1867
1868class RootPrinter {
1869 public:
1870 RootPrinter() { }
1871
1872 template <class MirrorType>
1873 ALWAYS_INLINE void VisitRootIfNonNull(mirror::CompressedReference<MirrorType>* root)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001874 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001875 if (!root->IsNull()) {
1876 VisitRoot(root);
1877 }
1878 }
1879
1880 template <class MirrorType>
1881 void VisitRoot(mirror::Object** root)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001882 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07001883 LOG(FATAL_WITHOUT_ABORT) << "root=" << root << " ref=" << *root;
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001884 }
1885
1886 template <class MirrorType>
1887 void VisitRoot(mirror::CompressedReference<MirrorType>* root)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001888 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07001889 LOG(FATAL_WITHOUT_ABORT) << "root=" << root << " ref=" << root->AsMirrorPtr();
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001890 }
1891};
1892
1893void ConcurrentCopying::AssertToSpaceInvariant(GcRootSource* gc_root_source,
1894 mirror::Object* ref) {
1895 CHECK(heap_->collector_type_ == kCollectorTypeCC) << static_cast<size_t>(heap_->collector_type_);
1896 if (is_asserting_to_space_invariant_) {
1897 if (region_space_->IsInToSpace(ref)) {
1898 // OK.
1899 return;
1900 } else if (region_space_->IsInUnevacFromSpace(ref)) {
Mathieu Chartierc381c362016-08-23 13:27:53 -07001901 CHECK(IsMarkedInUnevacFromSpace(ref)) << ref;
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001902 } else if (region_space_->IsInFromSpace(ref)) {
1903 // Not OK. Do extra logging.
1904 if (gc_root_source == nullptr) {
1905 // No info.
1906 } else if (gc_root_source->HasArtField()) {
1907 ArtField* field = gc_root_source->GetArtField();
David Sehr709b0702016-10-13 09:12:37 -07001908 LOG(FATAL_WITHOUT_ABORT) << "gc root in field " << field << " "
1909 << ArtField::PrettyField(field);
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001910 RootPrinter root_printer;
1911 field->VisitRoots(root_printer);
1912 } else if (gc_root_source->HasArtMethod()) {
1913 ArtMethod* method = gc_root_source->GetArtMethod();
David Sehr709b0702016-10-13 09:12:37 -07001914 LOG(FATAL_WITHOUT_ABORT) << "gc root in method " << method << " "
1915 << ArtMethod::PrettyMethod(method);
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001916 RootPrinter root_printer;
Andreas Gampe542451c2016-07-26 09:02:02 -07001917 method->VisitRoots(root_printer, kRuntimePointerSize);
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001918 }
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07001919 ref->GetLockWord(false).Dump(LOG_STREAM(FATAL_WITHOUT_ABORT));
1920 region_space_->DumpNonFreeRegions(LOG_STREAM(FATAL_WITHOUT_ABORT));
1921 PrintFileToLog("/proc/self/maps", LogSeverity::FATAL_WITHOUT_ABORT);
1922 MemMap::DumpMaps(LOG_STREAM(FATAL_WITHOUT_ABORT), true);
David Sehr709b0702016-10-13 09:12:37 -07001923 CHECK(false) << "Found from-space ref " << ref << " " << ref->PrettyTypeOf();
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001924 } else {
1925 AssertToSpaceInvariantInNonMovingSpace(nullptr, ref);
1926 }
1927 }
1928}
1929
1930void ConcurrentCopying::LogFromSpaceRefHolder(mirror::Object* obj, MemberOffset offset) {
1931 if (kUseBakerReadBarrier) {
David Sehr709b0702016-10-13 09:12:37 -07001932 LOG(INFO) << "holder=" << obj << " " << obj->PrettyTypeOf()
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001933 << " holder rb_state=" << obj->GetReadBarrierState();
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001934 } else {
David Sehr709b0702016-10-13 09:12:37 -07001935 LOG(INFO) << "holder=" << obj << " " << obj->PrettyTypeOf();
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001936 }
1937 if (region_space_->IsInFromSpace(obj)) {
1938 LOG(INFO) << "holder is in the from-space.";
1939 } else if (region_space_->IsInToSpace(obj)) {
1940 LOG(INFO) << "holder is in the to-space.";
1941 } else if (region_space_->IsInUnevacFromSpace(obj)) {
1942 LOG(INFO) << "holder is in the unevac from-space.";
Mathieu Chartierc381c362016-08-23 13:27:53 -07001943 if (IsMarkedInUnevacFromSpace(obj)) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001944 LOG(INFO) << "holder is marked in the region space bitmap.";
1945 } else {
1946 LOG(INFO) << "holder is not marked in the region space bitmap.";
1947 }
1948 } else {
1949 // In a non-moving space.
Mathieu Chartier763a31e2015-11-16 16:05:55 -08001950 if (immune_spaces_.ContainsObject(obj)) {
1951 LOG(INFO) << "holder is in an immune image or the zygote space.";
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001952 } else {
Mathieu Chartier763a31e2015-11-16 16:05:55 -08001953 LOG(INFO) << "holder is in a non-immune, non-moving (or main) space.";
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001954 accounting::ContinuousSpaceBitmap* mark_bitmap =
1955 heap_mark_bitmap_->GetContinuousSpaceBitmap(obj);
1956 accounting::LargeObjectBitmap* los_bitmap =
1957 heap_mark_bitmap_->GetLargeObjectBitmap(obj);
1958 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
1959 bool is_los = mark_bitmap == nullptr;
1960 if (!is_los && mark_bitmap->Test(obj)) {
1961 LOG(INFO) << "holder is marked in the mark bit map.";
1962 } else if (is_los && los_bitmap->Test(obj)) {
1963 LOG(INFO) << "holder is marked in the los bit map.";
1964 } else {
1965 // If ref is on the allocation stack, then it is considered
1966 // mark/alive (but not necessarily on the live stack.)
1967 if (IsOnAllocStack(obj)) {
1968 LOG(INFO) << "holder is on the alloc stack.";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001969 } else {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001970 LOG(INFO) << "holder is not marked or on the alloc stack.";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001971 }
1972 }
1973 }
1974 }
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001975 LOG(INFO) << "offset=" << offset.SizeValue();
1976}
1977
1978void ConcurrentCopying::AssertToSpaceInvariantInNonMovingSpace(mirror::Object* obj,
1979 mirror::Object* ref) {
1980 // In a non-moving spaces. Check that the ref is marked.
Mathieu Chartier763a31e2015-11-16 16:05:55 -08001981 if (immune_spaces_.ContainsObject(ref)) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001982 if (kUseBakerReadBarrier) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001983 // Immune object may not be gray if called from the GC.
1984 if (Thread::Current() == thread_running_gc_ && !gc_grays_immune_objects_) {
1985 return;
1986 }
1987 bool updated_all_immune_objects = updated_all_immune_objects_.LoadSequentiallyConsistent();
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001988 CHECK(updated_all_immune_objects || ref->GetReadBarrierState() == ReadBarrier::GrayState())
1989 << "Unmarked immune space ref. obj=" << obj << " rb_state="
1990 << (obj != nullptr ? obj->GetReadBarrierState() : 0U)
1991 << " ref=" << ref << " ref rb_state=" << ref->GetReadBarrierState()
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001992 << " updated_all_immune_objects=" << updated_all_immune_objects;
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001993 }
1994 } else {
1995 accounting::ContinuousSpaceBitmap* mark_bitmap =
1996 heap_mark_bitmap_->GetContinuousSpaceBitmap(ref);
1997 accounting::LargeObjectBitmap* los_bitmap =
1998 heap_mark_bitmap_->GetLargeObjectBitmap(ref);
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001999 bool is_los = mark_bitmap == nullptr;
2000 if ((!is_los && mark_bitmap->Test(ref)) ||
2001 (is_los && los_bitmap->Test(ref))) {
2002 // OK.
2003 } else {
2004 // If ref is on the allocation stack, then it may not be
2005 // marked live, but considered marked/alive (but not
2006 // necessarily on the live stack).
2007 CHECK(IsOnAllocStack(ref)) << "Unmarked ref that's not on the allocation stack. "
2008 << "obj=" << obj << " ref=" << ref;
2009 }
2010 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002011}
2012
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002013// Used to scan ref fields of an object.
Mathieu Chartiera07f5592016-06-16 11:44:28 -07002014class ConcurrentCopying::RefFieldsVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002015 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07002016 explicit RefFieldsVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002017 : collector_(collector) {}
2018
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07002019 void operator()(mirror::Object* obj, MemberOffset offset, bool /* is_static */)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002020 const ALWAYS_INLINE REQUIRES_SHARED(Locks::mutator_lock_)
2021 REQUIRES_SHARED(Locks::heap_bitmap_lock_) {
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07002022 collector_->Process(obj, offset);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002023 }
2024
Mathieu Chartier31e88222016-10-14 18:43:19 -07002025 void operator()(ObjPtr<mirror::Class> klass, ObjPtr<mirror::Reference> ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002026 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002027 CHECK(klass->IsTypeOfReferenceClass());
2028 collector_->DelayReferenceReferent(klass, ref);
2029 }
2030
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002031 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002032 ALWAYS_INLINE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002033 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002034 if (!root->IsNull()) {
2035 VisitRoot(root);
2036 }
2037 }
2038
2039 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002040 ALWAYS_INLINE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002041 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002042 collector_->MarkRoot</*kGrayImmuneObject*/false>(root);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002043 }
2044
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002045 private:
2046 ConcurrentCopying* const collector_;
2047};
2048
2049// Scan ref fields of an object.
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002050inline void ConcurrentCopying::Scan(mirror::Object* to_ref) {
Hiroshi Yamauchi9b60d502017-02-03 15:09:26 -08002051 if (kDisallowReadBarrierDuringScan && !Runtime::Current()->IsActiveTransaction()) {
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07002052 // Avoid all read barriers during visit references to help performance.
Hiroshi Yamauchi9b60d502017-02-03 15:09:26 -08002053 // Don't do this in transaction mode because we may read the old value of an field which may
2054 // trigger read barriers.
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07002055 Thread::Current()->ModifyDebugDisallowReadBarrier(1);
2056 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002057 DCHECK(!region_space_->IsInFromSpace(to_ref));
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002058 DCHECK_EQ(Thread::Current(), thread_running_gc_);
Mathieu Chartiera07f5592016-06-16 11:44:28 -07002059 RefFieldsVisitor visitor(this);
Hiroshi Yamauchi5496f692016-02-17 13:29:59 -08002060 // Disable the read barrier for a performance reason.
2061 to_ref->VisitReferences</*kVisitNativeRoots*/true, kDefaultVerifyFlags, kWithoutReadBarrier>(
2062 visitor, visitor);
Hiroshi Yamauchi9b60d502017-02-03 15:09:26 -08002063 if (kDisallowReadBarrierDuringScan && !Runtime::Current()->IsActiveTransaction()) {
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07002064 Thread::Current()->ModifyDebugDisallowReadBarrier(-1);
2065 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002066}
2067
2068// Process a field.
2069inline void ConcurrentCopying::Process(mirror::Object* obj, MemberOffset offset) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002070 DCHECK_EQ(Thread::Current(), thread_running_gc_);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002071 mirror::Object* ref = obj->GetFieldObject<
2072 mirror::Object, kVerifyNone, kWithoutReadBarrier, false>(offset);
Mathieu Chartier4ce0c762017-05-18 10:01:07 -07002073 mirror::Object* to_ref = Mark</*kGrayImmuneObject*/false, /*kFromGCThread*/true>(
2074 ref,
2075 /*holder*/ obj,
2076 offset);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002077 if (to_ref == ref) {
2078 return;
2079 }
2080 // This may fail if the mutator writes to the field at the same time. But it's ok.
2081 mirror::Object* expected_ref = ref;
2082 mirror::Object* new_ref = to_ref;
2083 do {
2084 if (expected_ref !=
2085 obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier, false>(offset)) {
2086 // It was updated by the mutator.
2087 break;
2088 }
Hiroshi Yamauchifed3e2f2015-10-20 11:11:56 -07002089 } while (!obj->CasFieldWeakRelaxedObjectWithoutWriteBarrier<
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002090 false, false, kVerifyNone>(offset, expected_ref, new_ref));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002091}
2092
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002093// Process some roots.
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002094inline void ConcurrentCopying::VisitRoots(
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002095 mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED) {
2096 for (size_t i = 0; i < count; ++i) {
2097 mirror::Object** root = roots[i];
2098 mirror::Object* ref = *root;
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002099 mirror::Object* to_ref = Mark(ref);
2100 if (to_ref == ref) {
Mathieu Chartier4809d0a2015-04-07 10:39:04 -07002101 continue;
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002102 }
2103 Atomic<mirror::Object*>* addr = reinterpret_cast<Atomic<mirror::Object*>*>(root);
2104 mirror::Object* expected_ref = ref;
2105 mirror::Object* new_ref = to_ref;
2106 do {
2107 if (expected_ref != addr->LoadRelaxed()) {
2108 // It was updated by the mutator.
2109 break;
2110 }
Hiroshi Yamauchifed3e2f2015-10-20 11:11:56 -07002111 } while (!addr->CompareExchangeWeakRelaxed(expected_ref, new_ref));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002112 }
2113}
2114
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002115template<bool kGrayImmuneObject>
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002116inline void ConcurrentCopying::MarkRoot(mirror::CompressedReference<mirror::Object>* root) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002117 DCHECK(!root->IsNull());
2118 mirror::Object* const ref = root->AsMirrorPtr();
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002119 mirror::Object* to_ref = Mark<kGrayImmuneObject>(ref);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002120 if (to_ref != ref) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002121 auto* addr = reinterpret_cast<Atomic<mirror::CompressedReference<mirror::Object>>*>(root);
2122 auto expected_ref = mirror::CompressedReference<mirror::Object>::FromMirrorPtr(ref);
2123 auto new_ref = mirror::CompressedReference<mirror::Object>::FromMirrorPtr(to_ref);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002124 // If the cas fails, then it was updated by the mutator.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002125 do {
2126 if (ref != addr->LoadRelaxed().AsMirrorPtr()) {
2127 // It was updated by the mutator.
2128 break;
2129 }
Hiroshi Yamauchifed3e2f2015-10-20 11:11:56 -07002130 } while (!addr->CompareExchangeWeakRelaxed(expected_ref, new_ref));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002131 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002132}
2133
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002134inline void ConcurrentCopying::VisitRoots(
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002135 mirror::CompressedReference<mirror::Object>** roots, size_t count,
2136 const RootInfo& info ATTRIBUTE_UNUSED) {
2137 for (size_t i = 0; i < count; ++i) {
2138 mirror::CompressedReference<mirror::Object>* const root = roots[i];
2139 if (!root->IsNull()) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002140 // kGrayImmuneObject is true because this is used for the thread flip.
2141 MarkRoot</*kGrayImmuneObject*/true>(root);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002142 }
2143 }
2144}
2145
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002146// Temporary set gc_grays_immune_objects_ to true in a scope if the current thread is GC.
2147class ConcurrentCopying::ScopedGcGraysImmuneObjects {
2148 public:
2149 explicit ScopedGcGraysImmuneObjects(ConcurrentCopying* collector)
2150 : collector_(collector), enabled_(false) {
2151 if (kUseBakerReadBarrier &&
2152 collector_->thread_running_gc_ == Thread::Current() &&
2153 !collector_->gc_grays_immune_objects_) {
2154 collector_->gc_grays_immune_objects_ = true;
2155 enabled_ = true;
2156 }
2157 }
2158
2159 ~ScopedGcGraysImmuneObjects() {
2160 if (kUseBakerReadBarrier &&
2161 collector_->thread_running_gc_ == Thread::Current() &&
2162 enabled_) {
2163 DCHECK(collector_->gc_grays_immune_objects_);
2164 collector_->gc_grays_immune_objects_ = false;
2165 }
2166 }
2167
2168 private:
2169 ConcurrentCopying* const collector_;
2170 bool enabled_;
2171};
2172
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002173// Fill the given memory block with a dummy object. Used to fill in a
2174// copy of objects that was lost in race.
2175void ConcurrentCopying::FillWithDummyObject(mirror::Object* dummy_obj, size_t byte_size) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002176 // GC doesn't gray immune objects while scanning immune objects. But we need to trigger the read
2177 // barriers here because we need the updated reference to the int array class, etc. Temporary set
2178 // gc_grays_immune_objects_ to true so that we won't cause a DCHECK failure in MarkImmuneSpace().
2179 ScopedGcGraysImmuneObjects scoped_gc_gray_immune_objects(this);
Roland Levillain14d90572015-07-16 10:52:26 +01002180 CHECK_ALIGNED(byte_size, kObjectAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002181 memset(dummy_obj, 0, byte_size);
Mathieu Chartierd6636d32016-07-28 11:02:38 -07002182 // Avoid going through read barrier for since kDisallowReadBarrierDuringScan may be enabled.
2183 // Explicitly mark to make sure to get an object in the to-space.
2184 mirror::Class* int_array_class = down_cast<mirror::Class*>(
2185 Mark(mirror::IntArray::GetArrayClass<kWithoutReadBarrier>()));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002186 CHECK(int_array_class != nullptr);
2187 AssertToSpaceInvariant(nullptr, MemberOffset(0), int_array_class);
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07002188 size_t component_size = int_array_class->GetComponentSize<kWithoutReadBarrier>();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002189 CHECK_EQ(component_size, sizeof(int32_t));
2190 size_t data_offset = mirror::Array::DataOffset(component_size).SizeValue();
2191 if (data_offset > byte_size) {
2192 // An int array is too big. Use java.lang.Object.
Mathieu Chartier9aef9922017-04-23 13:53:50 -07002193 CHECK(java_lang_Object_ != nullptr);
Mathieu Chartier3ed8ec12017-04-20 19:28:54 -07002194 AssertToSpaceInvariant(nullptr, MemberOffset(0), java_lang_Object_);
2195 CHECK_EQ(byte_size, (java_lang_Object_->GetObjectSize<kVerifyNone, kWithoutReadBarrier>()));
2196 dummy_obj->SetClass(java_lang_Object_);
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07002197 CHECK_EQ(byte_size, (dummy_obj->SizeOf<kVerifyNone>()));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002198 } else {
2199 // Use an int array.
2200 dummy_obj->SetClass(int_array_class);
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07002201 CHECK((dummy_obj->IsArrayInstance<kVerifyNone, kWithoutReadBarrier>()));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002202 int32_t length = (byte_size - data_offset) / component_size;
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07002203 mirror::Array* dummy_arr = dummy_obj->AsArray<kVerifyNone, kWithoutReadBarrier>();
2204 dummy_arr->SetLength(length);
2205 CHECK_EQ(dummy_arr->GetLength(), length)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002206 << "byte_size=" << byte_size << " length=" << length
2207 << " component_size=" << component_size << " data_offset=" << data_offset;
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07002208 CHECK_EQ(byte_size, (dummy_obj->SizeOf<kVerifyNone>()))
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002209 << "byte_size=" << byte_size << " length=" << length
2210 << " component_size=" << component_size << " data_offset=" << data_offset;
2211 }
2212}
2213
2214// Reuse the memory blocks that were copy of objects that were lost in race.
2215mirror::Object* ConcurrentCopying::AllocateInSkippedBlock(size_t alloc_size) {
2216 // Try to reuse the blocks that were unused due to CAS failures.
Roland Levillain14d90572015-07-16 10:52:26 +01002217 CHECK_ALIGNED(alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002218 Thread* self = Thread::Current();
2219 size_t min_object_size = RoundUp(sizeof(mirror::Object), space::RegionSpace::kAlignment);
Mathieu Chartierd6636d32016-07-28 11:02:38 -07002220 size_t byte_size;
2221 uint8_t* addr;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002222 {
Mathieu Chartierd6636d32016-07-28 11:02:38 -07002223 MutexLock mu(self, skipped_blocks_lock_);
2224 auto it = skipped_blocks_map_.lower_bound(alloc_size);
2225 if (it == skipped_blocks_map_.end()) {
2226 // Not found.
2227 return nullptr;
2228 }
2229 byte_size = it->first;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002230 CHECK_GE(byte_size, alloc_size);
2231 if (byte_size > alloc_size && byte_size - alloc_size < min_object_size) {
2232 // If remainder would be too small for a dummy object, retry with a larger request size.
2233 it = skipped_blocks_map_.lower_bound(alloc_size + min_object_size);
2234 if (it == skipped_blocks_map_.end()) {
2235 // Not found.
2236 return nullptr;
2237 }
Roland Levillain14d90572015-07-16 10:52:26 +01002238 CHECK_ALIGNED(it->first - alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002239 CHECK_GE(it->first - alloc_size, min_object_size)
2240 << "byte_size=" << byte_size << " it->first=" << it->first << " alloc_size=" << alloc_size;
2241 }
Mathieu Chartierd6636d32016-07-28 11:02:38 -07002242 // Found a block.
2243 CHECK(it != skipped_blocks_map_.end());
2244 byte_size = it->first;
2245 addr = it->second;
2246 CHECK_GE(byte_size, alloc_size);
2247 CHECK(region_space_->IsInToSpace(reinterpret_cast<mirror::Object*>(addr)));
2248 CHECK_ALIGNED(byte_size, space::RegionSpace::kAlignment);
2249 if (kVerboseMode) {
2250 LOG(INFO) << "Reusing skipped bytes : " << reinterpret_cast<void*>(addr) << ", " << byte_size;
2251 }
2252 skipped_blocks_map_.erase(it);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002253 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002254 memset(addr, 0, byte_size);
2255 if (byte_size > alloc_size) {
2256 // Return the remainder to the map.
Roland Levillain14d90572015-07-16 10:52:26 +01002257 CHECK_ALIGNED(byte_size - alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002258 CHECK_GE(byte_size - alloc_size, min_object_size);
Mathieu Chartierd6636d32016-07-28 11:02:38 -07002259 // FillWithDummyObject may mark an object, avoid holding skipped_blocks_lock_ to prevent lock
2260 // violation and possible deadlock. The deadlock case is a recursive case:
2261 // FillWithDummyObject -> IntArray::GetArrayClass -> Mark -> Copy -> AllocateInSkippedBlock.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002262 FillWithDummyObject(reinterpret_cast<mirror::Object*>(addr + alloc_size),
2263 byte_size - alloc_size);
2264 CHECK(region_space_->IsInToSpace(reinterpret_cast<mirror::Object*>(addr + alloc_size)));
Mathieu Chartierd6636d32016-07-28 11:02:38 -07002265 {
2266 MutexLock mu(self, skipped_blocks_lock_);
2267 skipped_blocks_map_.insert(std::make_pair(byte_size - alloc_size, addr + alloc_size));
2268 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002269 }
2270 return reinterpret_cast<mirror::Object*>(addr);
2271}
2272
Mathieu Chartieref496d92017-04-28 18:58:59 -07002273mirror::Object* ConcurrentCopying::Copy(mirror::Object* from_ref,
2274 mirror::Object* holder,
2275 MemberOffset offset) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002276 DCHECK(region_space_->IsInFromSpace(from_ref));
Mathieu Chartieref496d92017-04-28 18:58:59 -07002277 // If the class pointer is null, the object is invalid. This could occur for a dangling pointer
2278 // from a previous GC that is either inside or outside the allocated region.
2279 mirror::Class* klass = from_ref->GetClass<kVerifyNone, kWithoutReadBarrier>();
2280 if (UNLIKELY(klass == nullptr)) {
2281 heap_->GetVerification()->LogHeapCorruption(holder, offset, from_ref, /* fatal */ true);
2282 }
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07002283 // There must not be a read barrier to avoid nested RB that might violate the to-space invariant.
2284 // Note that from_ref is a from space ref so the SizeOf() call will access the from-space meta
2285 // objects, but it's ok and necessary.
2286 size_t obj_size = from_ref->SizeOf<kDefaultVerifyFlags>();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002287 size_t region_space_alloc_size = RoundUp(obj_size, space::RegionSpace::kAlignment);
2288 size_t region_space_bytes_allocated = 0U;
2289 size_t non_moving_space_bytes_allocated = 0U;
2290 size_t bytes_allocated = 0U;
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07002291 size_t dummy;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002292 mirror::Object* to_ref = region_space_->AllocNonvirtual<true>(
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07002293 region_space_alloc_size, &region_space_bytes_allocated, nullptr, &dummy);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002294 bytes_allocated = region_space_bytes_allocated;
2295 if (to_ref != nullptr) {
2296 DCHECK_EQ(region_space_alloc_size, region_space_bytes_allocated);
2297 }
2298 bool fall_back_to_non_moving = false;
2299 if (UNLIKELY(to_ref == nullptr)) {
2300 // Failed to allocate in the region space. Try the skipped blocks.
2301 to_ref = AllocateInSkippedBlock(region_space_alloc_size);
2302 if (to_ref != nullptr) {
2303 // Succeeded to allocate in a skipped block.
2304 if (heap_->use_tlab_) {
2305 // This is necessary for the tlab case as it's not accounted in the space.
2306 region_space_->RecordAlloc(to_ref);
2307 }
2308 bytes_allocated = region_space_alloc_size;
2309 } else {
2310 // Fall back to the non-moving space.
2311 fall_back_to_non_moving = true;
2312 if (kVerboseMode) {
2313 LOG(INFO) << "Out of memory in the to-space. Fall back to non-moving. skipped_bytes="
2314 << to_space_bytes_skipped_.LoadSequentiallyConsistent()
2315 << " skipped_objects=" << to_space_objects_skipped_.LoadSequentiallyConsistent();
2316 }
2317 fall_back_to_non_moving = true;
2318 to_ref = heap_->non_moving_space_->Alloc(Thread::Current(), obj_size,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07002319 &non_moving_space_bytes_allocated, nullptr, &dummy);
Mathieu Chartierb01335c2017-03-22 13:15:01 -07002320 if (UNLIKELY(to_ref == nullptr)) {
2321 LOG(FATAL_WITHOUT_ABORT) << "Fall-back non-moving space allocation failed for a "
2322 << obj_size << " byte object in region type "
2323 << region_space_->GetRegionType(from_ref);
2324 LOG(FATAL) << "Object address=" << from_ref << " type=" << from_ref->PrettyTypeOf();
2325 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002326 bytes_allocated = non_moving_space_bytes_allocated;
2327 // Mark it in the mark bitmap.
2328 accounting::ContinuousSpaceBitmap* mark_bitmap =
2329 heap_mark_bitmap_->GetContinuousSpaceBitmap(to_ref);
2330 CHECK(mark_bitmap != nullptr);
2331 CHECK(!mark_bitmap->AtomicTestAndSet(to_ref));
2332 }
2333 }
2334 DCHECK(to_ref != nullptr);
2335
Mathieu Chartierd818adb2016-09-15 13:12:47 -07002336 // Copy the object excluding the lock word since that is handled in the loop.
Mathieu Chartieref496d92017-04-28 18:58:59 -07002337 to_ref->SetClass(klass);
Mathieu Chartierd818adb2016-09-15 13:12:47 -07002338 const size_t kObjectHeaderSize = sizeof(mirror::Object);
2339 DCHECK_GE(obj_size, kObjectHeaderSize);
2340 static_assert(kObjectHeaderSize == sizeof(mirror::HeapReference<mirror::Class>) +
2341 sizeof(LockWord),
2342 "Object header size does not match");
2343 // Memcpy can tear for words since it may do byte copy. It is only safe to do this since the
2344 // object in the from space is immutable other than the lock word. b/31423258
2345 memcpy(reinterpret_cast<uint8_t*>(to_ref) + kObjectHeaderSize,
2346 reinterpret_cast<const uint8_t*>(from_ref) + kObjectHeaderSize,
2347 obj_size - kObjectHeaderSize);
2348
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002349 // Attempt to install the forward pointer. This is in a loop as the
2350 // lock word atomic write can fail.
2351 while (true) {
Mathieu Chartierd818adb2016-09-15 13:12:47 -07002352 LockWord old_lock_word = from_ref->GetLockWord(false);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002353
2354 if (old_lock_word.GetState() == LockWord::kForwardingAddress) {
2355 // Lost the race. Another thread (either GC or mutator) stored
2356 // the forwarding pointer first. Make the lost copy (to_ref)
2357 // look like a valid but dead (dummy) object and keep it for
2358 // future reuse.
2359 FillWithDummyObject(to_ref, bytes_allocated);
2360 if (!fall_back_to_non_moving) {
2361 DCHECK(region_space_->IsInToSpace(to_ref));
2362 if (bytes_allocated > space::RegionSpace::kRegionSize) {
2363 // Free the large alloc.
2364 region_space_->FreeLarge(to_ref, bytes_allocated);
2365 } else {
2366 // Record the lost copy for later reuse.
2367 heap_->num_bytes_allocated_.FetchAndAddSequentiallyConsistent(bytes_allocated);
2368 to_space_bytes_skipped_.FetchAndAddSequentiallyConsistent(bytes_allocated);
2369 to_space_objects_skipped_.FetchAndAddSequentiallyConsistent(1);
2370 MutexLock mu(Thread::Current(), skipped_blocks_lock_);
2371 skipped_blocks_map_.insert(std::make_pair(bytes_allocated,
2372 reinterpret_cast<uint8_t*>(to_ref)));
2373 }
2374 } else {
2375 DCHECK(heap_->non_moving_space_->HasAddress(to_ref));
2376 DCHECK_EQ(bytes_allocated, non_moving_space_bytes_allocated);
2377 // Free the non-moving-space chunk.
2378 accounting::ContinuousSpaceBitmap* mark_bitmap =
2379 heap_mark_bitmap_->GetContinuousSpaceBitmap(to_ref);
2380 CHECK(mark_bitmap != nullptr);
2381 CHECK(mark_bitmap->Clear(to_ref));
2382 heap_->non_moving_space_->Free(Thread::Current(), to_ref);
2383 }
2384
2385 // Get the winner's forward ptr.
2386 mirror::Object* lost_fwd_ptr = to_ref;
2387 to_ref = reinterpret_cast<mirror::Object*>(old_lock_word.ForwardingAddress());
2388 CHECK(to_ref != nullptr);
2389 CHECK_NE(to_ref, lost_fwd_ptr);
Mathieu Chartierdfcd6f42016-09-13 10:02:48 -07002390 CHECK(region_space_->IsInToSpace(to_ref) || heap_->non_moving_space_->HasAddress(to_ref))
2391 << "to_ref=" << to_ref << " " << heap_->DumpSpaces();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002392 CHECK_NE(to_ref->GetLockWord(false).GetState(), LockWord::kForwardingAddress);
2393 return to_ref;
2394 }
2395
Mathieu Chartierd818adb2016-09-15 13:12:47 -07002396 // Copy the old lock word over since we did not copy it yet.
2397 to_ref->SetLockWord(old_lock_word, false);
Hiroshi Yamauchi60f63f52015-04-23 16:12:40 -07002398 // Set the gray ptr.
2399 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002400 to_ref->SetReadBarrierState(ReadBarrier::GrayState());
Hiroshi Yamauchi60f63f52015-04-23 16:12:40 -07002401 }
2402
Mathieu Chartiera8131262016-11-29 17:55:19 -08002403 // Do a fence to prevent the field CAS in ConcurrentCopying::Process from possibly reordering
2404 // before the object copy.
2405 QuasiAtomic::ThreadFenceRelease();
2406
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002407 LockWord new_lock_word = LockWord::FromForwardingAddress(reinterpret_cast<size_t>(to_ref));
2408
2409 // Try to atomically write the fwd ptr.
Mathieu Chartiera8131262016-11-29 17:55:19 -08002410 bool success = from_ref->CasLockWordWeakRelaxed(old_lock_word, new_lock_word);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002411 if (LIKELY(success)) {
2412 // The CAS succeeded.
Mathieu Chartiera8131262016-11-29 17:55:19 -08002413 objects_moved_.FetchAndAddRelaxed(1);
2414 bytes_moved_.FetchAndAddRelaxed(region_space_alloc_size);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002415 if (LIKELY(!fall_back_to_non_moving)) {
2416 DCHECK(region_space_->IsInToSpace(to_ref));
2417 } else {
2418 DCHECK(heap_->non_moving_space_->HasAddress(to_ref));
2419 DCHECK_EQ(bytes_allocated, non_moving_space_bytes_allocated);
2420 }
2421 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002422 DCHECK(to_ref->GetReadBarrierState() == ReadBarrier::GrayState());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002423 }
2424 DCHECK(GetFwdPtr(from_ref) == to_ref);
2425 CHECK_NE(to_ref->GetLockWord(false).GetState(), LockWord::kForwardingAddress);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002426 PushOntoMarkStack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002427 return to_ref;
2428 } else {
2429 // The CAS failed. It may have lost the race or may have failed
2430 // due to monitor/hashcode ops. Either way, retry.
2431 }
2432 }
2433}
2434
2435mirror::Object* ConcurrentCopying::IsMarked(mirror::Object* from_ref) {
2436 DCHECK(from_ref != nullptr);
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08002437 space::RegionSpace::RegionType rtype = region_space_->GetRegionType(from_ref);
2438 if (rtype == space::RegionSpace::RegionType::kRegionTypeToSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002439 // It's already marked.
2440 return from_ref;
2441 }
2442 mirror::Object* to_ref;
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08002443 if (rtype == space::RegionSpace::RegionType::kRegionTypeFromSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002444 to_ref = GetFwdPtr(from_ref);
2445 DCHECK(to_ref == nullptr || region_space_->IsInToSpace(to_ref) ||
2446 heap_->non_moving_space_->HasAddress(to_ref))
2447 << "from_ref=" << from_ref << " to_ref=" << to_ref;
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08002448 } else if (rtype == space::RegionSpace::RegionType::kRegionTypeUnevacFromSpace) {
Mathieu Chartierc381c362016-08-23 13:27:53 -07002449 if (IsMarkedInUnevacFromSpace(from_ref)) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002450 to_ref = from_ref;
2451 } else {
2452 to_ref = nullptr;
2453 }
2454 } else {
2455 // from_ref is in a non-moving space.
Mathieu Chartier763a31e2015-11-16 16:05:55 -08002456 if (immune_spaces_.ContainsObject(from_ref)) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002457 // An immune object is alive.
2458 to_ref = from_ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002459 } else {
2460 // Non-immune non-moving space. Use the mark bitmap.
2461 accounting::ContinuousSpaceBitmap* mark_bitmap =
2462 heap_mark_bitmap_->GetContinuousSpaceBitmap(from_ref);
2463 accounting::LargeObjectBitmap* los_bitmap =
2464 heap_mark_bitmap_->GetLargeObjectBitmap(from_ref);
2465 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
2466 bool is_los = mark_bitmap == nullptr;
2467 if (!is_los && mark_bitmap->Test(from_ref)) {
2468 // Already marked.
2469 to_ref = from_ref;
2470 } else if (is_los && los_bitmap->Test(from_ref)) {
2471 // Already marked in LOS.
2472 to_ref = from_ref;
2473 } else {
2474 // Not marked.
2475 if (IsOnAllocStack(from_ref)) {
2476 // If on the allocation stack, it's considered marked.
2477 to_ref = from_ref;
2478 } else {
2479 // Not marked.
2480 to_ref = nullptr;
2481 }
2482 }
2483 }
2484 }
2485 return to_ref;
2486}
2487
2488bool ConcurrentCopying::IsOnAllocStack(mirror::Object* ref) {
2489 QuasiAtomic::ThreadFenceAcquire();
2490 accounting::ObjectStack* alloc_stack = GetAllocationStack();
Mathieu Chartiercb535da2015-01-23 13:50:03 -08002491 return alloc_stack->Contains(ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002492}
2493
Mathieu Chartier1ca68902017-04-18 11:26:22 -07002494mirror::Object* ConcurrentCopying::MarkNonMoving(mirror::Object* ref,
2495 mirror::Object* holder,
2496 MemberOffset offset) {
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002497 // ref is in a non-moving space (from_ref == to_ref).
2498 DCHECK(!region_space_->HasAddress(ref)) << ref;
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002499 DCHECK(!immune_spaces_.ContainsObject(ref));
2500 // Use the mark bitmap.
2501 accounting::ContinuousSpaceBitmap* mark_bitmap =
2502 heap_mark_bitmap_->GetContinuousSpaceBitmap(ref);
2503 accounting::LargeObjectBitmap* los_bitmap =
2504 heap_mark_bitmap_->GetLargeObjectBitmap(ref);
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002505 bool is_los = mark_bitmap == nullptr;
2506 if (!is_los && mark_bitmap->Test(ref)) {
2507 // Already marked.
2508 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002509 DCHECK(ref->GetReadBarrierState() == ReadBarrier::GrayState() ||
2510 ref->GetReadBarrierState() == ReadBarrier::WhiteState());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002511 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002512 } else if (is_los && los_bitmap->Test(ref)) {
2513 // Already marked in LOS.
2514 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002515 DCHECK(ref->GetReadBarrierState() == ReadBarrier::GrayState() ||
2516 ref->GetReadBarrierState() == ReadBarrier::WhiteState());
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002517 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002518 } else {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002519 // Not marked.
2520 if (IsOnAllocStack(ref)) {
2521 // If it's on the allocation stack, it's considered marked. Keep it white.
2522 // Objects on the allocation stack need not be marked.
2523 if (!is_los) {
2524 DCHECK(!mark_bitmap->Test(ref));
2525 } else {
2526 DCHECK(!los_bitmap->Test(ref));
Nicolas Geoffrayddeb1722016-06-28 08:25:59 +00002527 }
Nicolas Geoffrayddeb1722016-06-28 08:25:59 +00002528 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002529 DCHECK_EQ(ref->GetReadBarrierState(), ReadBarrier::WhiteState());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002530 }
2531 } else {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002532 // For the baker-style RB, we need to handle 'false-gray' cases. See the
2533 // kRegionTypeUnevacFromSpace-case comment in Mark().
2534 if (kUseBakerReadBarrier) {
2535 // Test the bitmap first to reduce the chance of false gray cases.
2536 if ((!is_los && mark_bitmap->Test(ref)) ||
2537 (is_los && los_bitmap->Test(ref))) {
2538 return ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002539 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002540 }
Mathieu Chartier1ca68902017-04-18 11:26:22 -07002541 if (is_los && !IsAligned<kPageSize>(ref)) {
2542 // Ref is a large object that is not aligned, it must be heap corruption. Dump data before
2543 // AtomicSetReadBarrierState since it will fault if the address is not valid.
Mathieu Chartieref496d92017-04-28 18:58:59 -07002544 heap_->GetVerification()->LogHeapCorruption(holder, offset, ref, /* fatal */ true);
Mathieu Chartier1ca68902017-04-18 11:26:22 -07002545 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002546 // Not marked or on the allocation stack. Try to mark it.
2547 // This may or may not succeed, which is ok.
2548 bool cas_success = false;
2549 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002550 cas_success = ref->AtomicSetReadBarrierState(ReadBarrier::WhiteState(),
2551 ReadBarrier::GrayState());
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002552 }
2553 if (!is_los && mark_bitmap->AtomicTestAndSet(ref)) {
2554 // Already marked.
2555 if (kUseBakerReadBarrier && cas_success &&
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002556 ref->GetReadBarrierState() == ReadBarrier::GrayState()) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002557 PushOntoFalseGrayStack(ref);
2558 }
2559 } else if (is_los && los_bitmap->AtomicTestAndSet(ref)) {
2560 // Already marked in LOS.
2561 if (kUseBakerReadBarrier && cas_success &&
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002562 ref->GetReadBarrierState() == ReadBarrier::GrayState()) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002563 PushOntoFalseGrayStack(ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002564 }
2565 } else {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002566 // Newly marked.
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08002567 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002568 DCHECK_EQ(ref->GetReadBarrierState(), ReadBarrier::GrayState());
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08002569 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002570 PushOntoMarkStack(ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002571 }
2572 }
2573 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002574 return ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002575}
2576
2577void ConcurrentCopying::FinishPhase() {
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -08002578 Thread* const self = Thread::Current();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002579 {
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -08002580 MutexLock mu(self, mark_stack_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002581 CHECK_EQ(pooled_mark_stacks_.size(), kMarkStackPoolSize);
2582 }
Mathieu Chartiera1467d02017-02-22 09:22:50 -08002583 // kVerifyNoMissingCardMarks relies on the region space cards not being cleared to avoid false
2584 // positives.
2585 if (!kVerifyNoMissingCardMarks) {
Mathieu Chartier6e6078a2016-10-24 15:45:41 -07002586 TimingLogger::ScopedTiming split("ClearRegionSpaceCards", GetTimings());
2587 // We do not currently use the region space cards at all, madvise them away to save ram.
2588 heap_->GetCardTable()->ClearCardRange(region_space_->Begin(), region_space_->Limit());
Mathieu Chartier6e6078a2016-10-24 15:45:41 -07002589 }
2590 {
2591 MutexLock mu(self, skipped_blocks_lock_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002592 skipped_blocks_map_.clear();
2593 }
Mathieu Chartier56fe2582016-07-14 13:30:03 -07002594 {
2595 ReaderMutexLock mu(self, *Locks::mutator_lock_);
Mathieu Chartier21328a12016-07-22 10:47:45 -07002596 {
2597 WriterMutexLock mu2(self, *Locks::heap_bitmap_lock_);
2598 heap_->ClearMarkedObjects();
2599 }
2600 if (kUseBakerReadBarrier && kFilterModUnionCards) {
2601 TimingLogger::ScopedTiming split("FilterModUnionCards", GetTimings());
2602 ReaderMutexLock mu2(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier21328a12016-07-22 10:47:45 -07002603 for (space::ContinuousSpace* space : immune_spaces_.GetSpaces()) {
2604 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
Mathieu Chartier6e6078a2016-10-24 15:45:41 -07002605 accounting::ModUnionTable* table = heap_->FindModUnionTableFromSpace(space);
Mathieu Chartier21328a12016-07-22 10:47:45 -07002606 // Filter out cards that don't need to be set.
2607 if (table != nullptr) {
2608 table->FilterCards();
2609 }
2610 }
2611 }
Mathieu Chartier36a270a2016-07-28 18:08:51 -07002612 if (kUseBakerReadBarrier) {
2613 TimingLogger::ScopedTiming split("EmptyRBMarkBitStack", GetTimings());
Mathieu Chartier6e6078a2016-10-24 15:45:41 -07002614 DCHECK(rb_mark_bit_stack_ != nullptr);
Mathieu Chartier36a270a2016-07-28 18:08:51 -07002615 const auto* limit = rb_mark_bit_stack_->End();
2616 for (StackReference<mirror::Object>* it = rb_mark_bit_stack_->Begin(); it != limit; ++it) {
2617 CHECK(it->AsMirrorPtr()->AtomicSetMarkBit(1, 0));
2618 }
2619 rb_mark_bit_stack_->Reset();
2620 }
Mathieu Chartier56fe2582016-07-14 13:30:03 -07002621 }
2622 if (measure_read_barrier_slow_path_) {
2623 MutexLock mu(self, rb_slow_path_histogram_lock_);
2624 rb_slow_path_time_histogram_.AdjustAndAddValue(rb_slow_path_ns_.LoadRelaxed());
2625 rb_slow_path_count_total_ += rb_slow_path_count_.LoadRelaxed();
2626 rb_slow_path_count_gc_total_ += rb_slow_path_count_gc_.LoadRelaxed();
2627 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002628}
2629
Hiroshi Yamauchi65f5f242016-12-19 11:44:47 -08002630bool ConcurrentCopying::IsNullOrMarkedHeapReference(mirror::HeapReference<mirror::Object>* field,
2631 bool do_atomic_update) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002632 mirror::Object* from_ref = field->AsMirrorPtr();
Hiroshi Yamauchi65f5f242016-12-19 11:44:47 -08002633 if (from_ref == nullptr) {
2634 return true;
2635 }
Mathieu Chartier97509952015-07-13 14:35:43 -07002636 mirror::Object* to_ref = IsMarked(from_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002637 if (to_ref == nullptr) {
2638 return false;
2639 }
2640 if (from_ref != to_ref) {
Hiroshi Yamauchi65f5f242016-12-19 11:44:47 -08002641 if (do_atomic_update) {
2642 do {
2643 if (field->AsMirrorPtr() != from_ref) {
2644 // Concurrently overwritten by a mutator.
2645 break;
2646 }
2647 } while (!field->CasWeakRelaxed(from_ref, to_ref));
2648 } else {
2649 QuasiAtomic::ThreadFenceRelease();
2650 field->Assign(to_ref);
2651 QuasiAtomic::ThreadFenceSequentiallyConsistent();
2652 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002653 }
2654 return true;
2655}
2656
Mathieu Chartier97509952015-07-13 14:35:43 -07002657mirror::Object* ConcurrentCopying::MarkObject(mirror::Object* from_ref) {
2658 return Mark(from_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002659}
2660
Mathieu Chartier31e88222016-10-14 18:43:19 -07002661void ConcurrentCopying::DelayReferenceReferent(ObjPtr<mirror::Class> klass,
2662 ObjPtr<mirror::Reference> reference) {
Mathieu Chartier97509952015-07-13 14:35:43 -07002663 heap_->GetReferenceProcessor()->DelayReferenceReferent(klass, reference, this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002664}
2665
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002666void ConcurrentCopying::ProcessReferences(Thread* self) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002667 TimingLogger::ScopedTiming split("ProcessReferences", GetTimings());
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002668 // 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 -08002669 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
2670 GetHeap()->GetReferenceProcessor()->ProcessReferences(
Mathieu Chartier97509952015-07-13 14:35:43 -07002671 true /*concurrent*/, GetTimings(), GetCurrentIteration()->GetClearSoftReferences(), this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002672}
2673
2674void ConcurrentCopying::RevokeAllThreadLocalBuffers() {
2675 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
2676 region_space_->RevokeAllThreadLocalBuffers();
2677}
2678
Mathieu Chartier56fe2582016-07-14 13:30:03 -07002679mirror::Object* ConcurrentCopying::MarkFromReadBarrierWithMeasurements(mirror::Object* from_ref) {
2680 if (Thread::Current() != thread_running_gc_) {
2681 rb_slow_path_count_.FetchAndAddRelaxed(1u);
2682 } else {
2683 rb_slow_path_count_gc_.FetchAndAddRelaxed(1u);
2684 }
2685 ScopedTrace tr(__FUNCTION__);
2686 const uint64_t start_time = measure_read_barrier_slow_path_ ? NanoTime() : 0u;
2687 mirror::Object* ret = Mark(from_ref);
2688 if (measure_read_barrier_slow_path_) {
2689 rb_slow_path_ns_.FetchAndAddRelaxed(NanoTime() - start_time);
2690 }
2691 return ret;
2692}
2693
2694void ConcurrentCopying::DumpPerformanceInfo(std::ostream& os) {
2695 GarbageCollector::DumpPerformanceInfo(os);
2696 MutexLock mu(Thread::Current(), rb_slow_path_histogram_lock_);
2697 if (rb_slow_path_time_histogram_.SampleSize() > 0) {
2698 Histogram<uint64_t>::CumulativeData cumulative_data;
2699 rb_slow_path_time_histogram_.CreateHistogram(&cumulative_data);
2700 rb_slow_path_time_histogram_.PrintConfidenceIntervals(os, 0.99, cumulative_data);
2701 }
2702 if (rb_slow_path_count_total_ > 0) {
2703 os << "Slow path count " << rb_slow_path_count_total_ << "\n";
2704 }
2705 if (rb_slow_path_count_gc_total_ > 0) {
2706 os << "GC slow path count " << rb_slow_path_count_gc_total_ << "\n";
2707 }
Mathieu Chartiercca44a02016-08-17 10:07:29 -07002708 os << "Cumulative bytes moved " << cumulative_bytes_moved_.LoadRelaxed() << "\n";
2709 os << "Cumulative objects moved " << cumulative_objects_moved_.LoadRelaxed() << "\n";
Mathieu Chartier56fe2582016-07-14 13:30:03 -07002710}
2711
Hiroshi Yamauchid5307ec2014-03-27 21:07:51 -07002712} // namespace collector
2713} // namespace gc
2714} // namespace art