blob: b3780e6be4ea2e330fadab293ae5e138159c5bc1 [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),
80 is_active_(false),
81 is_asserting_to_space_invariant_(false),
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -070082 region_space_bitmap_(nullptr),
Andreas Gamped9911ee2017-03-27 13:27:24 -070083 heap_mark_bitmap_(nullptr),
84 live_stack_freeze_size_(0),
85 from_space_num_objects_at_first_pause_(0),
86 from_space_num_bytes_at_first_pause_(0),
87 mark_stack_mode_(kMarkStackModeOff),
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070088 weak_ref_access_enabled_(true),
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080089 skipped_blocks_lock_("concurrent copying bytes blocks lock", kMarkSweepMarkStackLock),
Mathieu Chartier56fe2582016-07-14 13:30:03 -070090 measure_read_barrier_slow_path_(measure_read_barrier_slow_path),
Andreas Gamped9911ee2017-03-27 13:27:24 -070091 mark_from_read_barrier_measurements_(false),
Mathieu Chartier56fe2582016-07-14 13:30:03 -070092 rb_slow_path_ns_(0),
93 rb_slow_path_count_(0),
94 rb_slow_path_count_gc_(0),
95 rb_slow_path_histogram_lock_("Read barrier histogram lock"),
96 rb_slow_path_time_histogram_("Mutator time in read barrier slow path", 500, 32),
97 rb_slow_path_count_total_(0),
98 rb_slow_path_count_gc_total_(0),
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080099 rb_table_(heap_->GetReadBarrierTable()),
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700100 force_evacuate_all_(false),
Andreas Gamped9911ee2017-03-27 13:27:24 -0700101 gc_grays_immune_objects_(false),
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700102 immune_gray_stack_lock_("concurrent copying immune gray stack lock",
103 kMarkSweepMarkStackLock) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800104 static_assert(space::RegionSpace::kRegionSize == accounting::ReadBarrierTable::kRegionSize,
105 "The region space size and the read barrier table region size must match");
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700106 Thread* self = Thread::Current();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800107 {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800108 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
109 // Cache this so that we won't have to lock heap_bitmap_lock_ in
110 // Mark() which could cause a nested lock on heap_bitmap_lock_
111 // when GC causes a RB while doing GC or a lock order violation
112 // (class_linker_lock_ and heap_bitmap_lock_).
113 heap_mark_bitmap_ = heap->GetMarkBitmap();
114 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700115 {
116 MutexLock mu(self, mark_stack_lock_);
117 for (size_t i = 0; i < kMarkStackPoolSize; ++i) {
118 accounting::AtomicStack<mirror::Object>* mark_stack =
119 accounting::AtomicStack<mirror::Object>::Create(
120 "thread local mark stack", kMarkStackSize, kMarkStackSize);
121 pooled_mark_stacks_.push_back(mark_stack);
122 }
123 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800124}
125
Hiroshi Yamauchi057d9772017-02-17 15:33:23 -0800126void ConcurrentCopying::MarkHeapReference(mirror::HeapReference<mirror::Object>* field,
127 bool do_atomic_update) {
128 if (UNLIKELY(do_atomic_update)) {
129 // Used to mark the referent in DelayReferenceReferent in transaction mode.
130 mirror::Object* from_ref = field->AsMirrorPtr();
131 if (from_ref == nullptr) {
132 return;
133 }
134 mirror::Object* to_ref = Mark(from_ref);
135 if (from_ref != to_ref) {
136 do {
137 if (field->AsMirrorPtr() != from_ref) {
138 // Concurrently overwritten by a mutator.
139 break;
140 }
141 } while (!field->CasWeakRelaxed(from_ref, to_ref));
142 }
143 } else {
144 // Used for preserving soft references, should be OK to not have a CAS here since there should be
145 // no other threads which can trigger read barriers on the same referent during reference
146 // processing.
147 field->Assign(Mark(field->AsMirrorPtr()));
148 }
Mathieu Chartier97509952015-07-13 14:35:43 -0700149}
150
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800151ConcurrentCopying::~ConcurrentCopying() {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700152 STLDeleteElements(&pooled_mark_stacks_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800153}
154
155void ConcurrentCopying::RunPhases() {
156 CHECK(kUseBakerReadBarrier || kUseTableLookupReadBarrier);
157 CHECK(!is_active_);
158 is_active_ = true;
159 Thread* self = Thread::Current();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700160 thread_running_gc_ = self;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800161 Locks::mutator_lock_->AssertNotHeld(self);
162 {
163 ReaderMutexLock mu(self, *Locks::mutator_lock_);
164 InitializePhase();
165 }
Mathieu Chartier88d329a2017-04-27 11:32:14 -0700166 if (kUseBakerReadBarrier && kGrayDirtyImmuneObjects) {
167 // Gray dirty immune objects concurrently to reduce GC pause times. We re-process gray cards in
168 // the pause.
169 ReaderMutexLock mu(self, *Locks::mutator_lock_);
170 GrayAllDirtyImmuneObjects();
171 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800172 FlipThreadRoots();
173 {
174 ReaderMutexLock mu(self, *Locks::mutator_lock_);
175 MarkingPhase();
176 }
177 // Verify no from space refs. This causes a pause.
Andreas Gampee3ce7872017-02-22 13:36:21 -0800178 if (kEnableNoFromSpaceRefsVerification) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800179 TimingLogger::ScopedTiming split("(Paused)VerifyNoFromSpaceReferences", GetTimings());
Andreas Gampe4934eb12017-01-30 13:15:26 -0800180 ScopedPause pause(this, false);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700181 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800182 if (kVerboseMode) {
183 LOG(INFO) << "Verifying no from-space refs";
184 }
185 VerifyNoFromSpaceReferences();
Mathieu Chartier720e71a2015-04-06 17:10:58 -0700186 if (kVerboseMode) {
187 LOG(INFO) << "Done verifying no from-space refs";
188 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700189 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800190 }
191 {
192 ReaderMutexLock mu(self, *Locks::mutator_lock_);
193 ReclaimPhase();
194 }
195 FinishPhase();
196 CHECK(is_active_);
197 is_active_ = false;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700198 thread_running_gc_ = nullptr;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800199}
200
201void ConcurrentCopying::BindBitmaps() {
202 Thread* self = Thread::Current();
203 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
204 // Mark all of the spaces we never collect as immune.
205 for (const auto& space : heap_->GetContinuousSpaces()) {
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800206 if (space->GetGcRetentionPolicy() == space::kGcRetentionPolicyNeverCollect ||
207 space->GetGcRetentionPolicy() == space::kGcRetentionPolicyFullCollect) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800208 CHECK(space->IsZygoteSpace() || space->IsImageSpace());
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800209 immune_spaces_.AddSpace(space);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800210 } else if (space == region_space_) {
Mathieu Chartier7ec38dc2016-10-07 15:24:46 -0700211 // It is OK to clear the bitmap with mutators running since the only place it is read is
212 // VisitObjects which has exclusion with CC.
213 region_space_bitmap_ = region_space_->GetMarkBitmap();
214 region_space_bitmap_->Clear();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800215 }
216 }
217}
218
219void ConcurrentCopying::InitializePhase() {
220 TimingLogger::ScopedTiming split("InitializePhase", GetTimings());
221 if (kVerboseMode) {
222 LOG(INFO) << "GC InitializePhase";
223 LOG(INFO) << "Region-space : " << reinterpret_cast<void*>(region_space_->Begin()) << "-"
224 << reinterpret_cast<void*>(region_space_->Limit());
225 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700226 CheckEmptyMarkStack();
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800227 if (kIsDebugBuild) {
228 MutexLock mu(Thread::Current(), mark_stack_lock_);
229 CHECK(false_gray_stack_.empty());
230 }
Mathieu Chartier56fe2582016-07-14 13:30:03 -0700231
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700232 rb_mark_bit_stack_full_ = false;
Mathieu Chartier56fe2582016-07-14 13:30:03 -0700233 mark_from_read_barrier_measurements_ = measure_read_barrier_slow_path_;
234 if (measure_read_barrier_slow_path_) {
235 rb_slow_path_ns_.StoreRelaxed(0);
236 rb_slow_path_count_.StoreRelaxed(0);
237 rb_slow_path_count_gc_.StoreRelaxed(0);
238 }
239
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800240 immune_spaces_.Reset();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800241 bytes_moved_.StoreRelaxed(0);
242 objects_moved_.StoreRelaxed(0);
Hiroshi Yamauchi60985b72016-08-24 13:53:12 -0700243 GcCause gc_cause = GetCurrentIteration()->GetGcCause();
244 if (gc_cause == kGcCauseExplicit ||
245 gc_cause == kGcCauseForNativeAlloc ||
246 gc_cause == kGcCauseCollectorTransition ||
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800247 GetCurrentIteration()->GetClearSoftReferences()) {
248 force_evacuate_all_ = true;
249 } else {
250 force_evacuate_all_ = false;
251 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700252 if (kUseBakerReadBarrier) {
253 updated_all_immune_objects_.StoreRelaxed(false);
254 // GC may gray immune objects in the thread flip.
255 gc_grays_immune_objects_ = true;
256 if (kIsDebugBuild) {
257 MutexLock mu(Thread::Current(), immune_gray_stack_lock_);
258 DCHECK(immune_gray_stack_.empty());
259 }
260 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800261 BindBitmaps();
262 if (kVerboseMode) {
263 LOG(INFO) << "force_evacuate_all=" << force_evacuate_all_;
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800264 LOG(INFO) << "Largest immune region: " << immune_spaces_.GetLargestImmuneRegion().Begin()
265 << "-" << immune_spaces_.GetLargestImmuneRegion().End();
266 for (space::ContinuousSpace* space : immune_spaces_.GetSpaces()) {
267 LOG(INFO) << "Immune space: " << *space;
268 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800269 LOG(INFO) << "GC end of InitializePhase";
270 }
Mathieu Chartier962cd7a2016-08-16 12:15:59 -0700271 // Mark all of the zygote large objects without graying them.
272 MarkZygoteLargeObjects();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800273}
274
275// Used to switch the thread roots of a thread from from-space refs to to-space refs.
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700276class ConcurrentCopying::ThreadFlipVisitor : public Closure, public RootVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800277 public:
Roland Levillain3887c462015-08-12 18:15:42 +0100278 ThreadFlipVisitor(ConcurrentCopying* concurrent_copying, bool use_tlab)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800279 : concurrent_copying_(concurrent_copying), use_tlab_(use_tlab) {
280 }
281
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700282 virtual void Run(Thread* thread) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800283 // Note: self is not necessarily equal to thread since thread may be suspended.
284 Thread* self = Thread::Current();
285 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
286 << thread->GetState() << " thread " << thread << " self " << self;
Mathieu Chartierfe814e82016-11-09 14:32:49 -0800287 thread->SetIsGcMarkingAndUpdateEntrypoints(true);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800288 if (use_tlab_ && thread->HasTlab()) {
289 if (ConcurrentCopying::kEnableFromSpaceAccountingCheck) {
290 // This must come before the revoke.
291 size_t thread_local_objects = thread->GetThreadLocalObjectsAllocated();
292 concurrent_copying_->region_space_->RevokeThreadLocalBuffers(thread);
293 reinterpret_cast<Atomic<size_t>*>(&concurrent_copying_->from_space_num_objects_at_first_pause_)->
294 FetchAndAddSequentiallyConsistent(thread_local_objects);
295 } else {
296 concurrent_copying_->region_space_->RevokeThreadLocalBuffers(thread);
297 }
298 }
299 if (kUseThreadLocalAllocationStack) {
300 thread->RevokeThreadLocalAllocationStack();
301 }
302 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700303 // We can use the non-CAS VisitRoots functions below because we update thread-local GC roots
304 // only.
305 thread->VisitRoots(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800306 concurrent_copying_->GetBarrier().Pass(self);
307 }
308
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700309 void VisitRoots(mirror::Object*** roots,
310 size_t count,
311 const RootInfo& info ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700312 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700313 for (size_t i = 0; i < count; ++i) {
314 mirror::Object** root = roots[i];
315 mirror::Object* ref = *root;
316 if (ref != nullptr) {
317 mirror::Object* to_ref = concurrent_copying_->Mark(ref);
318 if (to_ref != ref) {
319 *root = to_ref;
320 }
321 }
322 }
323 }
324
325 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots,
326 size_t count,
327 const RootInfo& info ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700328 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700329 for (size_t i = 0; i < count; ++i) {
330 mirror::CompressedReference<mirror::Object>* const root = roots[i];
331 if (!root->IsNull()) {
332 mirror::Object* ref = root->AsMirrorPtr();
333 mirror::Object* to_ref = concurrent_copying_->Mark(ref);
334 if (to_ref != ref) {
335 root->Assign(to_ref);
336 }
337 }
338 }
339 }
340
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800341 private:
342 ConcurrentCopying* const concurrent_copying_;
343 const bool use_tlab_;
344};
345
346// Called back from Runtime::FlipThreadRoots() during a pause.
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700347class ConcurrentCopying::FlipCallback : public Closure {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800348 public:
349 explicit FlipCallback(ConcurrentCopying* concurrent_copying)
350 : concurrent_copying_(concurrent_copying) {
351 }
352
Mathieu Chartier90443472015-07-16 20:32:27 -0700353 virtual void Run(Thread* thread) OVERRIDE REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800354 ConcurrentCopying* cc = concurrent_copying_;
355 TimingLogger::ScopedTiming split("(Paused)FlipCallback", cc->GetTimings());
356 // Note: self is not necessarily equal to thread since thread may be suspended.
357 Thread* self = Thread::Current();
Mathieu Chartiera1467d02017-02-22 09:22:50 -0800358 if (kVerifyNoMissingCardMarks) {
359 cc->VerifyNoMissingCardMarks();
360 }
Mathieu Chartier88d329a2017-04-27 11:32:14 -0700361 CHECK_EQ(thread, self);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800362 Locks::mutator_lock_->AssertExclusiveHeld(self);
Mathieu Chartier88d329a2017-04-27 11:32:14 -0700363 {
364 TimingLogger::ScopedTiming split2("(Paused)SetFromSpace", cc->GetTimings());
365 cc->region_space_->SetFromSpace(cc->rb_table_, cc->force_evacuate_all_);
366 }
Mathieu Chartiera4f6af92015-08-11 17:35:25 -0700367 cc->SwapStacks();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800368 if (ConcurrentCopying::kEnableFromSpaceAccountingCheck) {
369 cc->RecordLiveStackFreezeSize(self);
370 cc->from_space_num_objects_at_first_pause_ = cc->region_space_->GetObjectsAllocated();
371 cc->from_space_num_bytes_at_first_pause_ = cc->region_space_->GetBytesAllocated();
372 }
373 cc->is_marking_ = true;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700374 cc->mark_stack_mode_.StoreRelaxed(ConcurrentCopying::kMarkStackModeThreadLocal);
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800375 if (kIsDebugBuild) {
376 cc->region_space_->AssertAllRegionLiveBytesZeroOrCleared();
377 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800378 if (UNLIKELY(Runtime::Current()->IsActiveTransaction())) {
Mathieu Chartier184c9dc2015-03-05 13:20:54 -0800379 CHECK(Runtime::Current()->IsAotCompiler());
Mathieu Chartier88d329a2017-04-27 11:32:14 -0700380 TimingLogger::ScopedTiming split3("(Paused)VisitTransactionRoots", cc->GetTimings());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700381 Runtime::Current()->VisitTransactionRoots(cc);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800382 }
Mathieu Chartier21328a12016-07-22 10:47:45 -0700383 if (kUseBakerReadBarrier && kGrayDirtyImmuneObjects) {
Mathieu Chartier88d329a2017-04-27 11:32:14 -0700384 cc->GrayAllNewlyDirtyImmuneObjects();
Mathieu Chartier21328a12016-07-22 10:47:45 -0700385 if (kIsDebugBuild) {
386 // Check that all non-gray immune objects only refernce immune objects.
387 cc->VerifyGrayImmuneObjects();
388 }
389 }
Mathieu Chartier9aef9922017-04-23 13:53:50 -0700390 // May be null during runtime creation, in this case leave java_lang_Object null.
391 // This is safe since single threaded behavior should mean FillDummyObject does not
392 // happen when java_lang_Object_ is null.
393 if (WellKnownClasses::java_lang_Object != nullptr) {
394 cc->java_lang_Object_ = down_cast<mirror::Class*>(cc->Mark(
395 WellKnownClasses::ToClass(WellKnownClasses::java_lang_Object).Ptr()));
396 } else {
397 cc->java_lang_Object_ = nullptr;
398 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800399 }
400
401 private:
402 ConcurrentCopying* const concurrent_copying_;
403};
404
Mathieu Chartier21328a12016-07-22 10:47:45 -0700405class ConcurrentCopying::VerifyGrayImmuneObjectsVisitor {
406 public:
407 explicit VerifyGrayImmuneObjectsVisitor(ConcurrentCopying* collector)
408 : collector_(collector) {}
409
Mathieu Chartier31e88222016-10-14 18:43:19 -0700410 void operator()(ObjPtr<mirror::Object> obj, MemberOffset offset, bool /* is_static */)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700411 const ALWAYS_INLINE REQUIRES_SHARED(Locks::mutator_lock_)
412 REQUIRES_SHARED(Locks::heap_bitmap_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700413 CheckReference(obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(offset),
414 obj, offset);
415 }
416
Mathieu Chartier31e88222016-10-14 18:43:19 -0700417 void operator()(ObjPtr<mirror::Class> klass, ObjPtr<mirror::Reference> ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700418 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700419 CHECK(klass->IsTypeOfReferenceClass());
420 CheckReference(ref->GetReferent<kWithoutReadBarrier>(),
421 ref,
422 mirror::Reference::ReferentOffset());
423 }
424
425 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
426 ALWAYS_INLINE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700427 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700428 if (!root->IsNull()) {
429 VisitRoot(root);
430 }
431 }
432
433 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
434 ALWAYS_INLINE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700435 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700436 CheckReference(root->AsMirrorPtr(), nullptr, MemberOffset(0));
437 }
438
439 private:
440 ConcurrentCopying* const collector_;
441
Mathieu Chartier31e88222016-10-14 18:43:19 -0700442 void CheckReference(ObjPtr<mirror::Object> ref,
443 ObjPtr<mirror::Object> holder,
444 MemberOffset offset) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700445 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700446 if (ref != nullptr) {
Mathieu Chartier31e88222016-10-14 18:43:19 -0700447 if (!collector_->immune_spaces_.ContainsObject(ref.Ptr())) {
Mathieu Chartier962cd7a2016-08-16 12:15:59 -0700448 // Not immune, must be a zygote large object.
449 CHECK(Runtime::Current()->GetHeap()->GetLargeObjectsSpace()->IsZygoteLargeObject(
Mathieu Chartier31e88222016-10-14 18:43:19 -0700450 Thread::Current(), ref.Ptr()))
Mathieu Chartier962cd7a2016-08-16 12:15:59 -0700451 << "Non gray object references non immune, non zygote large object "<< ref << " "
David Sehr709b0702016-10-13 09:12:37 -0700452 << mirror::Object::PrettyTypeOf(ref) << " in holder " << holder << " "
453 << mirror::Object::PrettyTypeOf(holder) << " offset=" << offset.Uint32Value();
Mathieu Chartier962cd7a2016-08-16 12:15:59 -0700454 } else {
455 // Make sure the large object class is immune since we will never scan the large object.
456 CHECK(collector_->immune_spaces_.ContainsObject(
457 ref->GetClass<kVerifyNone, kWithoutReadBarrier>()));
458 }
Mathieu Chartier21328a12016-07-22 10:47:45 -0700459 }
460 }
461};
462
463void ConcurrentCopying::VerifyGrayImmuneObjects() {
464 TimingLogger::ScopedTiming split(__FUNCTION__, GetTimings());
465 for (auto& space : immune_spaces_.GetSpaces()) {
466 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
467 accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
468 VerifyGrayImmuneObjectsVisitor visitor(this);
469 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()),
470 reinterpret_cast<uintptr_t>(space->Limit()),
471 [&visitor](mirror::Object* obj)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700472 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700473 // If an object is not gray, it should only have references to things in the immune spaces.
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700474 if (obj->GetReadBarrierState() != ReadBarrier::GrayState()) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700475 obj->VisitReferences</*kVisitNativeRoots*/true,
476 kDefaultVerifyFlags,
477 kWithoutReadBarrier>(visitor, visitor);
478 }
479 });
480 }
481}
482
Mathieu Chartiera1467d02017-02-22 09:22:50 -0800483class ConcurrentCopying::VerifyNoMissingCardMarkVisitor {
484 public:
485 VerifyNoMissingCardMarkVisitor(ConcurrentCopying* cc, ObjPtr<mirror::Object> holder)
486 : cc_(cc),
487 holder_(holder) {}
488
489 void operator()(ObjPtr<mirror::Object> obj,
490 MemberOffset offset,
491 bool is_static ATTRIBUTE_UNUSED) const
492 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
493 if (offset.Uint32Value() != mirror::Object::ClassOffset().Uint32Value()) {
494 CheckReference(obj->GetFieldObject<mirror::Object, kDefaultVerifyFlags, kWithoutReadBarrier>(
495 offset), offset.Uint32Value());
496 }
497 }
498 void operator()(ObjPtr<mirror::Class> klass,
499 ObjPtr<mirror::Reference> ref) const
500 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
501 CHECK(klass->IsTypeOfReferenceClass());
502 this->operator()(ref, mirror::Reference::ReferentOffset(), false);
503 }
504
505 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
506 REQUIRES_SHARED(Locks::mutator_lock_) {
507 if (!root->IsNull()) {
508 VisitRoot(root);
509 }
510 }
511
512 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
513 REQUIRES_SHARED(Locks::mutator_lock_) {
514 CheckReference(root->AsMirrorPtr());
515 }
516
517 void CheckReference(mirror::Object* ref, int32_t offset = -1) const
518 REQUIRES_SHARED(Locks::mutator_lock_) {
519 CHECK(ref == nullptr || !cc_->region_space_->IsInNewlyAllocatedRegion(ref))
520 << holder_->PrettyTypeOf() << "(" << holder_.Ptr() << ") references object "
521 << ref->PrettyTypeOf() << "(" << ref << ") in newly allocated region at offset=" << offset;
522 }
523
524 private:
525 ConcurrentCopying* const cc_;
526 ObjPtr<mirror::Object> const holder_;
527};
528
529void ConcurrentCopying::VerifyNoMissingCardMarkCallback(mirror::Object* obj, void* arg) {
530 auto* collector = reinterpret_cast<ConcurrentCopying*>(arg);
Mathieu Chartier88d329a2017-04-27 11:32:14 -0700531 // Objects not on dirty or aged cards should never have references to newly allocated regions.
532 if (collector->heap_->GetCardTable()->GetCard(obj) == gc::accounting::CardTable::kCardClean) {
Mathieu Chartiera1467d02017-02-22 09:22:50 -0800533 VerifyNoMissingCardMarkVisitor visitor(collector, /*holder*/ obj);
534 obj->VisitReferences</*kVisitNativeRoots*/true, kVerifyNone, kWithoutReadBarrier>(
535 visitor,
536 visitor);
537 }
538}
539
540void ConcurrentCopying::VerifyNoMissingCardMarks() {
541 TimingLogger::ScopedTiming split(__FUNCTION__, GetTimings());
542 region_space_->Walk(&VerifyNoMissingCardMarkCallback, this);
543 {
544 ReaderMutexLock rmu(Thread::Current(), *Locks::heap_bitmap_lock_);
545 heap_->GetLiveBitmap()->Walk(&VerifyNoMissingCardMarkCallback, this);
546 }
547}
548
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800549// Switch threads that from from-space to to-space refs. Forward/mark the thread roots.
550void ConcurrentCopying::FlipThreadRoots() {
551 TimingLogger::ScopedTiming split("FlipThreadRoots", GetTimings());
552 if (kVerboseMode) {
553 LOG(INFO) << "time=" << region_space_->Time();
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700554 region_space_->DumpNonFreeRegions(LOG_STREAM(INFO));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800555 }
556 Thread* self = Thread::Current();
557 Locks::mutator_lock_->AssertNotHeld(self);
558 gc_barrier_->Init(self, 0);
559 ThreadFlipVisitor thread_flip_visitor(this, heap_->use_tlab_);
560 FlipCallback flip_callback(this);
Andreas Gampe4934eb12017-01-30 13:15:26 -0800561
562 // This is the point where Concurrent-Copying will pause all threads. We report a pause here, if
563 // necessary. This is slightly over-reporting, as this includes the time to actually suspend
564 // threads.
565 {
566 GcPauseListener* pause_listener = GetHeap()->GetGcPauseListener();
567 if (pause_listener != nullptr) {
568 pause_listener->StartPause();
569 }
570 }
571
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800572 size_t barrier_count = Runtime::Current()->FlipThreadRoots(
573 &thread_flip_visitor, &flip_callback, this);
Andreas Gampe4934eb12017-01-30 13:15:26 -0800574
575 {
576 GcPauseListener* pause_listener = GetHeap()->GetGcPauseListener();
577 if (pause_listener != nullptr) {
578 pause_listener->EndPause();
579 }
580 }
581
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800582 {
583 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
584 gc_barrier_->Increment(self, barrier_count);
585 }
586 is_asserting_to_space_invariant_ = true;
587 QuasiAtomic::ThreadFenceForConstructor();
588 if (kVerboseMode) {
589 LOG(INFO) << "time=" << region_space_->Time();
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700590 region_space_->DumpNonFreeRegions(LOG_STREAM(INFO));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800591 LOG(INFO) << "GC end of FlipThreadRoots";
592 }
593}
594
Mathieu Chartier88d329a2017-04-27 11:32:14 -0700595template <bool kConcurrent>
Mathieu Chartier21328a12016-07-22 10:47:45 -0700596class ConcurrentCopying::GrayImmuneObjectVisitor {
597 public:
Mathieu Chartier88d329a2017-04-27 11:32:14 -0700598 explicit GrayImmuneObjectVisitor(Thread* self) : self_(self) {}
Mathieu Chartier21328a12016-07-22 10:47:45 -0700599
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700600 ALWAYS_INLINE void operator()(mirror::Object* obj) const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier88d329a2017-04-27 11:32:14 -0700601 if (kUseBakerReadBarrier && obj->GetReadBarrierState() == ReadBarrier::WhiteState()) {
602 if (kConcurrent) {
603 Locks::mutator_lock_->AssertSharedHeld(self_);
604 obj->AtomicSetReadBarrierState(ReadBarrier::WhiteState(), ReadBarrier::GrayState());
605 // Mod union table VisitObjects may visit the same object multiple times so we can't check
606 // the result of the atomic set.
607 } else {
608 Locks::mutator_lock_->AssertExclusiveHeld(self_);
609 obj->SetReadBarrierState(ReadBarrier::GrayState());
Mathieu Chartier21328a12016-07-22 10:47:45 -0700610 }
Mathieu Chartier21328a12016-07-22 10:47:45 -0700611 }
612 }
613
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700614 static void Callback(mirror::Object* obj, void* arg) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier88d329a2017-04-27 11:32:14 -0700615 reinterpret_cast<GrayImmuneObjectVisitor<kConcurrent>*>(arg)->operator()(obj);
Mathieu Chartier21328a12016-07-22 10:47:45 -0700616 }
Mathieu Chartier88d329a2017-04-27 11:32:14 -0700617
618 private:
619 Thread* const self_;
Mathieu Chartier21328a12016-07-22 10:47:45 -0700620};
621
622void ConcurrentCopying::GrayAllDirtyImmuneObjects() {
Mathieu Chartier88d329a2017-04-27 11:32:14 -0700623 TimingLogger::ScopedTiming split("GrayAllDirtyImmuneObjects", GetTimings());
624 accounting::CardTable* const card_table = heap_->GetCardTable();
625 Thread* const self = Thread::Current();
626 using VisitorType = GrayImmuneObjectVisitor</* kIsConcurrent */ true>;
627 VisitorType visitor(self);
628 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier21328a12016-07-22 10:47:45 -0700629 for (space::ContinuousSpace* space : immune_spaces_.GetSpaces()) {
630 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
Mathieu Chartier88d329a2017-04-27 11:32:14 -0700631 accounting::ModUnionTable* table = heap_->FindModUnionTableFromSpace(space);
Mathieu Chartier21328a12016-07-22 10:47:45 -0700632 // Mark all the objects on dirty cards since these may point to objects in other space.
633 // Once these are marked, the GC will eventually clear them later.
634 // Table is non null for boot image and zygote spaces. It is only null for application image
635 // spaces.
636 if (table != nullptr) {
Mathieu Chartier6e6078a2016-10-24 15:45:41 -0700637 table->ProcessCards();
Mathieu Chartier88d329a2017-04-27 11:32:14 -0700638 table->VisitObjects(&VisitorType::Callback, &visitor);
639 // Don't clear cards here since we need to rescan in the pause. If we cleared the cards here,
640 // there would be races with the mutator marking new cards.
641 } else {
642 // Keep cards aged if we don't have a mod-union table since we may need to scan them in future
643 // GCs. This case is for app images.
644 card_table->ModifyCardsAtomic(
645 space->Begin(),
646 space->End(),
647 [](uint8_t card) {
648 return (card != gc::accounting::CardTable::kCardClean)
649 ? gc::accounting::CardTable::kCardAged
650 : card;
651 },
652 /* card modified visitor */ VoidFunctor());
653 card_table->Scan</* kClearCard */ false>(space->GetMarkBitmap(),
654 space->Begin(),
655 space->End(),
656 visitor,
657 gc::accounting::CardTable::kCardAged);
658 }
659 }
660}
661
662void ConcurrentCopying::GrayAllNewlyDirtyImmuneObjects() {
663 TimingLogger::ScopedTiming split("(Paused)GrayAllNewlyDirtyImmuneObjects", GetTimings());
664 accounting::CardTable* const card_table = heap_->GetCardTable();
665 using VisitorType = GrayImmuneObjectVisitor</* kIsConcurrent */ false>;
666 Thread* const self = Thread::Current();
667 VisitorType visitor(self);
668 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
669 for (space::ContinuousSpace* space : immune_spaces_.GetSpaces()) {
670 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
671 accounting::ModUnionTable* table = heap_->FindModUnionTableFromSpace(space);
672
673 // Don't need to scan aged cards since we did these before the pause. Note that scanning cards
674 // also handles the mod-union table cards.
675 card_table->Scan</* kClearCard */ false>(space->GetMarkBitmap(),
676 space->Begin(),
677 space->End(),
678 visitor,
679 gc::accounting::CardTable::kCardDirty);
680 if (table != nullptr) {
681 // Add the cards to the mod-union table so that we can clear cards to save RAM.
682 table->ProcessCards();
Mathieu Chartier6e6078a2016-10-24 15:45:41 -0700683 TimingLogger::ScopedTiming split2("(Paused)ClearCards", GetTimings());
684 card_table->ClearCardRange(space->Begin(),
685 AlignDown(space->End(), accounting::CardTable::kCardSize));
Mathieu Chartier21328a12016-07-22 10:47:45 -0700686 }
687 }
Mathieu Chartier88d329a2017-04-27 11:32:14 -0700688 // 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 -0700689 // barriers in the immune spaces.
690 updated_all_immune_objects_.StoreRelaxed(true);
691}
692
Mathieu Chartiera4f6af92015-08-11 17:35:25 -0700693void ConcurrentCopying::SwapStacks() {
694 heap_->SwapStacks();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800695}
696
697void ConcurrentCopying::RecordLiveStackFreezeSize(Thread* self) {
698 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
699 live_stack_freeze_size_ = heap_->GetLiveStack()->Size();
700}
701
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700702// Used to visit objects in the immune spaces.
703inline void ConcurrentCopying::ScanImmuneObject(mirror::Object* obj) {
704 DCHECK(obj != nullptr);
705 DCHECK(immune_spaces_.ContainsObject(obj));
706 // Update the fields without graying it or pushing it onto the mark stack.
707 Scan(obj);
708}
709
710class ConcurrentCopying::ImmuneSpaceScanObjVisitor {
711 public:
712 explicit ImmuneSpaceScanObjVisitor(ConcurrentCopying* cc)
713 : collector_(cc) {}
714
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700715 ALWAYS_INLINE void operator()(mirror::Object* obj) const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700716 if (kUseBakerReadBarrier && kGrayDirtyImmuneObjects) {
Mathieu Chartier88d329a2017-04-27 11:32:14 -0700717 // Only need to scan gray objects.
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700718 if (obj->GetReadBarrierState() == ReadBarrier::GrayState()) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700719 collector_->ScanImmuneObject(obj);
720 // Done scanning the object, go back to white.
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700721 bool success = obj->AtomicSetReadBarrierState(ReadBarrier::GrayState(),
722 ReadBarrier::WhiteState());
Mathieu Chartier21328a12016-07-22 10:47:45 -0700723 CHECK(success);
724 }
725 } else {
726 collector_->ScanImmuneObject(obj);
727 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700728 }
729
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700730 static void Callback(mirror::Object* obj, void* arg) REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi5408f232016-07-29 15:07:05 -0700731 reinterpret_cast<ImmuneSpaceScanObjVisitor*>(arg)->operator()(obj);
732 }
733
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700734 private:
735 ConcurrentCopying* const collector_;
736};
737
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800738// Concurrently mark roots that are guarded by read barriers and process the mark stack.
739void ConcurrentCopying::MarkingPhase() {
740 TimingLogger::ScopedTiming split("MarkingPhase", GetTimings());
741 if (kVerboseMode) {
742 LOG(INFO) << "GC MarkingPhase";
743 }
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -0700744 Thread* self = Thread::Current();
745 if (kIsDebugBuild) {
746 MutexLock mu(self, *Locks::thread_list_lock_);
747 CHECK(weak_ref_access_enabled_);
748 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700749
750 // Scan immune spaces.
751 // Update all the fields in the immune spaces first without graying the objects so that we
752 // minimize dirty pages in the immune spaces. Note mutators can concurrently access and gray some
753 // of the objects.
754 if (kUseBakerReadBarrier) {
755 gc_grays_immune_objects_ = false;
Hiroshi Yamauchi16292fc2016-06-20 20:23:34 -0700756 }
Mathieu Chartier21328a12016-07-22 10:47:45 -0700757 {
758 TimingLogger::ScopedTiming split2("ScanImmuneSpaces", GetTimings());
759 for (auto& space : immune_spaces_.GetSpaces()) {
760 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
761 accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
Hiroshi Yamauchi5408f232016-07-29 15:07:05 -0700762 accounting::ModUnionTable* table = heap_->FindModUnionTableFromSpace(space);
Mathieu Chartier21328a12016-07-22 10:47:45 -0700763 ImmuneSpaceScanObjVisitor visitor(this);
Hiroshi Yamauchi5408f232016-07-29 15:07:05 -0700764 if (kUseBakerReadBarrier && kGrayDirtyImmuneObjects && table != nullptr) {
765 table->VisitObjects(ImmuneSpaceScanObjVisitor::Callback, &visitor);
766 } else {
Mathieu Chartier88d329a2017-04-27 11:32:14 -0700767 // TODO: Scan only the aged cards.
Hiroshi Yamauchi5408f232016-07-29 15:07:05 -0700768 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()),
769 reinterpret_cast<uintptr_t>(space->Limit()),
770 visitor);
771 }
Mathieu Chartier21328a12016-07-22 10:47:45 -0700772 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700773 }
774 if (kUseBakerReadBarrier) {
775 // This release fence makes the field updates in the above loop visible before allowing mutator
776 // getting access to immune objects without graying it first.
777 updated_all_immune_objects_.StoreRelease(true);
778 // Now whiten immune objects concurrently accessed and grayed by mutators. We can't do this in
779 // the above loop because we would incorrectly disable the read barrier by whitening an object
780 // which may point to an unscanned, white object, breaking the to-space invariant.
781 //
782 // Make sure no mutators are in the middle of marking an immune object before whitening immune
783 // objects.
784 IssueEmptyCheckpoint();
785 MutexLock mu(Thread::Current(), immune_gray_stack_lock_);
786 if (kVerboseMode) {
787 LOG(INFO) << "immune gray stack size=" << immune_gray_stack_.size();
788 }
789 for (mirror::Object* obj : immune_gray_stack_) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700790 DCHECK(obj->GetReadBarrierState() == ReadBarrier::GrayState());
791 bool success = obj->AtomicSetReadBarrierState(ReadBarrier::GrayState(),
792 ReadBarrier::WhiteState());
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700793 DCHECK(success);
794 }
795 immune_gray_stack_.clear();
796 }
797
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800798 {
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -0700799 TimingLogger::ScopedTiming split2("VisitConcurrentRoots", GetTimings());
800 Runtime::Current()->VisitConcurrentRoots(this, kVisitRootFlagAllRoots);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800801 }
802 {
803 // TODO: don't visit the transaction roots if it's not active.
804 TimingLogger::ScopedTiming split5("VisitNonThreadRoots", GetTimings());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700805 Runtime::Current()->VisitNonThreadRoots(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800806 }
807
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800808 {
Mathieu Chartiera6b1ead2015-10-06 10:32:38 -0700809 TimingLogger::ScopedTiming split7("ProcessMarkStack", GetTimings());
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700810 // We transition through three mark stack modes (thread-local, shared, GC-exclusive). The
811 // primary reasons are the fact that we need to use a checkpoint to process thread-local mark
812 // stacks, but after we disable weak refs accesses, we can't use a checkpoint due to a deadlock
813 // issue because running threads potentially blocking at WaitHoldingLocks, and that once we
814 // reach the point where we process weak references, we can avoid using a lock when accessing
815 // the GC mark stack, which makes mark stack processing more efficient.
816
817 // Process the mark stack once in the thread local stack mode. This marks most of the live
818 // objects, aside from weak ref accesses with read barriers (Reference::GetReferent() and system
819 // weaks) that may happen concurrently while we processing the mark stack and newly mark/gray
820 // objects and push refs on the mark stack.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800821 ProcessMarkStack();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700822 // Switch to the shared mark stack mode. That is, revoke and process thread-local mark stacks
823 // for the last time before transitioning to the shared mark stack mode, which would process new
824 // refs that may have been concurrently pushed onto the mark stack during the ProcessMarkStack()
825 // call above. At the same time, disable weak ref accesses using a per-thread flag. It's
826 // important to do these together in a single checkpoint so that we can ensure that mutators
827 // won't newly gray objects and push new refs onto the mark stack due to weak ref accesses and
828 // mutators safely transition to the shared mark stack mode (without leaving unprocessed refs on
829 // the thread-local mark stacks), without a race. This is why we use a thread-local weak ref
830 // access flag Thread::tls32_.weak_ref_access_enabled_ instead of the global ones.
831 SwitchToSharedMarkStackMode();
832 CHECK(!self->GetWeakRefAccessEnabled());
833 // Now that weak refs accesses are disabled, once we exhaust the shared mark stack again here
834 // (which may be non-empty if there were refs found on thread-local mark stacks during the above
835 // SwitchToSharedMarkStackMode() call), we won't have new refs to process, that is, mutators
836 // (via read barriers) have no way to produce any more refs to process. Marking converges once
837 // before we process weak refs below.
838 ProcessMarkStack();
839 CheckEmptyMarkStack();
840 // Switch to the GC exclusive mark stack mode so that we can process the mark stack without a
841 // lock from this point on.
842 SwitchToGcExclusiveMarkStackMode();
843 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800844 if (kVerboseMode) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800845 LOG(INFO) << "ProcessReferences";
846 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700847 // Process weak references. This may produce new refs to process and have them processed via
Mathieu Chartier97509952015-07-13 14:35:43 -0700848 // ProcessMarkStack (in the GC exclusive mark stack mode).
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700849 ProcessReferences(self);
850 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800851 if (kVerboseMode) {
852 LOG(INFO) << "SweepSystemWeaks";
853 }
854 SweepSystemWeaks(self);
855 if (kVerboseMode) {
856 LOG(INFO) << "SweepSystemWeaks done";
857 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700858 // Process the mark stack here one last time because the above SweepSystemWeaks() call may have
859 // marked some objects (strings alive) as hash_set::Erase() can call the hash function for
860 // arbitrary elements in the weak intern table in InternTable::Table::SweepWeaks().
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800861 ProcessMarkStack();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700862 CheckEmptyMarkStack();
863 // Re-enable weak ref accesses.
864 ReenableWeakRefAccess(self);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -0700865 // Free data for class loaders that we unloaded.
866 Runtime::Current()->GetClassLinker()->CleanupClassLoaders();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700867 // Marking is done. Disable marking.
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700868 DisableMarking();
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800869 if (kUseBakerReadBarrier) {
870 ProcessFalseGrayStack();
871 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700872 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800873 }
874
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -0700875 if (kIsDebugBuild) {
876 MutexLock mu(self, *Locks::thread_list_lock_);
877 CHECK(weak_ref_access_enabled_);
878 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800879 if (kVerboseMode) {
880 LOG(INFO) << "GC end of MarkingPhase";
881 }
882}
883
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700884void ConcurrentCopying::ReenableWeakRefAccess(Thread* self) {
885 if (kVerboseMode) {
886 LOG(INFO) << "ReenableWeakRefAccess";
887 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700888 // Iterate all threads (don't need to or can't use a checkpoint) and re-enable weak ref access.
889 {
890 MutexLock mu(self, *Locks::thread_list_lock_);
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -0700891 weak_ref_access_enabled_ = true; // This is for new threads.
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700892 std::list<Thread*> thread_list = Runtime::Current()->GetThreadList()->GetList();
893 for (Thread* thread : thread_list) {
894 thread->SetWeakRefAccessEnabled(true);
895 }
896 }
897 // Unblock blocking threads.
898 GetHeap()->GetReferenceProcessor()->BroadcastForSlowPath(self);
899 Runtime::Current()->BroadcastForNewSystemWeaks();
900}
901
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700902class ConcurrentCopying::DisableMarkingCheckpoint : public Closure {
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700903 public:
904 explicit DisableMarkingCheckpoint(ConcurrentCopying* concurrent_copying)
905 : concurrent_copying_(concurrent_copying) {
906 }
907
908 void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
909 // Note: self is not necessarily equal to thread since thread may be suspended.
910 Thread* self = Thread::Current();
911 DCHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
912 << thread->GetState() << " thread " << thread << " self " << self;
913 // Disable the thread-local is_gc_marking flag.
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -0700914 // Note a thread that has just started right before this checkpoint may have already this flag
915 // set to false, which is ok.
Mathieu Chartierfe814e82016-11-09 14:32:49 -0800916 thread->SetIsGcMarkingAndUpdateEntrypoints(false);
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700917 // If thread is a running mutator, then act on behalf of the garbage collector.
918 // See the code in ThreadList::RunCheckpoint.
Mathieu Chartier10d25082015-10-28 18:36:09 -0700919 concurrent_copying_->GetBarrier().Pass(self);
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700920 }
921
922 private:
923 ConcurrentCopying* const concurrent_copying_;
924};
925
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -0700926class ConcurrentCopying::DisableMarkingCallback : public Closure {
927 public:
928 explicit DisableMarkingCallback(ConcurrentCopying* concurrent_copying)
929 : concurrent_copying_(concurrent_copying) {
930 }
931
932 void Run(Thread* self ATTRIBUTE_UNUSED) OVERRIDE REQUIRES(Locks::thread_list_lock_) {
933 // This needs to run under the thread_list_lock_ critical section in ThreadList::RunCheckpoint()
934 // to avoid a race with ThreadList::Register().
935 CHECK(concurrent_copying_->is_marking_);
936 concurrent_copying_->is_marking_ = false;
937 }
938
939 private:
940 ConcurrentCopying* const concurrent_copying_;
941};
942
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700943void ConcurrentCopying::IssueDisableMarkingCheckpoint() {
944 Thread* self = Thread::Current();
945 DisableMarkingCheckpoint check_point(this);
946 ThreadList* thread_list = Runtime::Current()->GetThreadList();
947 gc_barrier_->Init(self, 0);
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -0700948 DisableMarkingCallback dmc(this);
949 size_t barrier_count = thread_list->RunCheckpoint(&check_point, &dmc);
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700950 // If there are no threads to wait which implies that all the checkpoint functions are finished,
951 // then no need to release the mutator lock.
952 if (barrier_count == 0) {
953 return;
954 }
955 // Release locks then wait for all mutator threads to pass the barrier.
956 Locks::mutator_lock_->SharedUnlock(self);
957 {
958 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
959 gc_barrier_->Increment(self, barrier_count);
960 }
961 Locks::mutator_lock_->SharedLock(self);
962}
963
964void ConcurrentCopying::DisableMarking() {
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -0700965 // Use a checkpoint to turn off the global is_marking and the thread-local is_gc_marking flags and
966 // to ensure no threads are still in the middle of a read barrier which may have a from-space ref
967 // cached in a local variable.
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700968 IssueDisableMarkingCheckpoint();
969 if (kUseTableLookupReadBarrier) {
970 heap_->rb_table_->ClearAll();
971 DCHECK(heap_->rb_table_->IsAllCleared());
972 }
973 is_mark_stack_push_disallowed_.StoreSequentiallyConsistent(1);
974 mark_stack_mode_.StoreSequentiallyConsistent(kMarkStackModeOff);
975}
976
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800977void ConcurrentCopying::PushOntoFalseGrayStack(mirror::Object* ref) {
978 CHECK(kUseBakerReadBarrier);
979 DCHECK(ref != nullptr);
980 MutexLock mu(Thread::Current(), mark_stack_lock_);
981 false_gray_stack_.push_back(ref);
982}
983
984void ConcurrentCopying::ProcessFalseGrayStack() {
985 CHECK(kUseBakerReadBarrier);
986 // Change the objects on the false gray stack from gray to white.
987 MutexLock mu(Thread::Current(), mark_stack_lock_);
988 for (mirror::Object* obj : false_gray_stack_) {
989 DCHECK(IsMarked(obj));
990 // The object could be white here if a thread got preempted after a success at the
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700991 // AtomicSetReadBarrierState in Mark(), GC started marking through it (but not finished so
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800992 // still gray), and the thread ran to register it onto the false gray stack.
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700993 if (obj->GetReadBarrierState() == ReadBarrier::GrayState()) {
994 bool success = obj->AtomicSetReadBarrierState(ReadBarrier::GrayState(),
995 ReadBarrier::WhiteState());
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800996 DCHECK(success);
997 }
998 }
999 false_gray_stack_.clear();
1000}
1001
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001002void ConcurrentCopying::IssueEmptyCheckpoint() {
1003 Thread* self = Thread::Current();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001004 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001005 // Release locks then wait for all mutator threads to pass the barrier.
1006 Locks::mutator_lock_->SharedUnlock(self);
Hiroshi Yamauchia2224042017-02-08 16:35:45 -08001007 thread_list->RunEmptyCheckpoint();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001008 Locks::mutator_lock_->SharedLock(self);
1009}
1010
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -07001011void ConcurrentCopying::ExpandGcMarkStack() {
1012 DCHECK(gc_mark_stack_->IsFull());
1013 const size_t new_size = gc_mark_stack_->Capacity() * 2;
1014 std::vector<StackReference<mirror::Object>> temp(gc_mark_stack_->Begin(),
1015 gc_mark_stack_->End());
1016 gc_mark_stack_->Resize(new_size);
1017 for (auto& ref : temp) {
1018 gc_mark_stack_->PushBack(ref.AsMirrorPtr());
1019 }
1020 DCHECK(!gc_mark_stack_->IsFull());
1021}
1022
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001023void ConcurrentCopying::PushOntoMarkStack(mirror::Object* to_ref) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001024 CHECK_EQ(is_mark_stack_push_disallowed_.LoadRelaxed(), 0)
David Sehr709b0702016-10-13 09:12:37 -07001025 << " " << to_ref << " " << mirror::Object::PrettyTypeOf(to_ref);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001026 Thread* self = Thread::Current(); // TODO: pass self as an argument from call sites?
1027 CHECK(thread_running_gc_ != nullptr);
1028 MarkStackMode mark_stack_mode = mark_stack_mode_.LoadRelaxed();
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001029 if (LIKELY(mark_stack_mode == kMarkStackModeThreadLocal)) {
1030 if (LIKELY(self == thread_running_gc_)) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001031 // If GC-running thread, use the GC mark stack instead of a thread-local mark stack.
1032 CHECK(self->GetThreadLocalMarkStack() == nullptr);
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -07001033 if (UNLIKELY(gc_mark_stack_->IsFull())) {
1034 ExpandGcMarkStack();
1035 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001036 gc_mark_stack_->PushBack(to_ref);
1037 } else {
1038 // Otherwise, use a thread-local mark stack.
1039 accounting::AtomicStack<mirror::Object>* tl_mark_stack = self->GetThreadLocalMarkStack();
1040 if (UNLIKELY(tl_mark_stack == nullptr || tl_mark_stack->IsFull())) {
1041 MutexLock mu(self, mark_stack_lock_);
1042 // Get a new thread local mark stack.
1043 accounting::AtomicStack<mirror::Object>* new_tl_mark_stack;
1044 if (!pooled_mark_stacks_.empty()) {
1045 // Use a pooled mark stack.
1046 new_tl_mark_stack = pooled_mark_stacks_.back();
1047 pooled_mark_stacks_.pop_back();
1048 } else {
1049 // None pooled. Create a new one.
1050 new_tl_mark_stack =
1051 accounting::AtomicStack<mirror::Object>::Create(
1052 "thread local mark stack", 4 * KB, 4 * KB);
1053 }
1054 DCHECK(new_tl_mark_stack != nullptr);
1055 DCHECK(new_tl_mark_stack->IsEmpty());
1056 new_tl_mark_stack->PushBack(to_ref);
1057 self->SetThreadLocalMarkStack(new_tl_mark_stack);
1058 if (tl_mark_stack != nullptr) {
1059 // Store the old full stack into a vector.
1060 revoked_mark_stacks_.push_back(tl_mark_stack);
1061 }
1062 } else {
1063 tl_mark_stack->PushBack(to_ref);
1064 }
1065 }
1066 } else if (mark_stack_mode == kMarkStackModeShared) {
1067 // Access the shared GC mark stack with a lock.
1068 MutexLock mu(self, mark_stack_lock_);
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -07001069 if (UNLIKELY(gc_mark_stack_->IsFull())) {
1070 ExpandGcMarkStack();
1071 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001072 gc_mark_stack_->PushBack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001073 } else {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001074 CHECK_EQ(static_cast<uint32_t>(mark_stack_mode),
Hiroshi Yamauchifa755182015-09-30 20:12:11 -07001075 static_cast<uint32_t>(kMarkStackModeGcExclusive))
1076 << "ref=" << to_ref
1077 << " self->gc_marking=" << self->GetIsGcMarking()
1078 << " cc->is_marking=" << is_marking_;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001079 CHECK(self == thread_running_gc_)
1080 << "Only GC-running thread should access the mark stack "
1081 << "in the GC exclusive mark stack mode";
1082 // Access the GC mark stack without a lock.
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -07001083 if (UNLIKELY(gc_mark_stack_->IsFull())) {
1084 ExpandGcMarkStack();
1085 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001086 gc_mark_stack_->PushBack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001087 }
1088}
1089
1090accounting::ObjectStack* ConcurrentCopying::GetAllocationStack() {
1091 return heap_->allocation_stack_.get();
1092}
1093
1094accounting::ObjectStack* ConcurrentCopying::GetLiveStack() {
1095 return heap_->live_stack_.get();
1096}
1097
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001098// The following visitors are used to verify that there's no references to the from-space left after
1099// marking.
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001100class ConcurrentCopying::VerifyNoFromSpaceRefsVisitor : public SingleRootVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001101 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001102 explicit VerifyNoFromSpaceRefsVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001103 : collector_(collector) {}
1104
Mathieu Chartierbc632f02017-04-20 13:31:39 -07001105 void operator()(mirror::Object* ref,
1106 MemberOffset offset = MemberOffset(0),
1107 mirror::Object* holder = nullptr) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001108 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001109 if (ref == nullptr) {
1110 // OK.
1111 return;
1112 }
Mathieu Chartierbc632f02017-04-20 13:31:39 -07001113 collector_->AssertToSpaceInvariant(holder, offset, ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001114 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001115 CHECK_EQ(ref->GetReadBarrierState(), ReadBarrier::WhiteState())
David Sehr709b0702016-10-13 09:12:37 -07001116 << "Ref " << ref << " " << ref->PrettyTypeOf()
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001117 << " has non-white rb_state ";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001118 }
1119 }
1120
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001121 void VisitRoot(mirror::Object* root, const RootInfo& info ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001122 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001123 DCHECK(root != nullptr);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001124 operator()(root);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001125 }
1126
1127 private:
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001128 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001129};
1130
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001131class ConcurrentCopying::VerifyNoFromSpaceRefsFieldVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001132 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001133 explicit VerifyNoFromSpaceRefsFieldVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001134 : collector_(collector) {}
1135
Mathieu Chartier31e88222016-10-14 18:43:19 -07001136 void operator()(ObjPtr<mirror::Object> obj,
1137 MemberOffset offset,
1138 bool is_static ATTRIBUTE_UNUSED) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001139 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001140 mirror::Object* ref =
1141 obj->GetFieldObject<mirror::Object, kDefaultVerifyFlags, kWithoutReadBarrier>(offset);
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001142 VerifyNoFromSpaceRefsVisitor visitor(collector_);
Mathieu Chartierbc632f02017-04-20 13:31:39 -07001143 visitor(ref, offset, obj.Ptr());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001144 }
Mathieu Chartier31e88222016-10-14 18:43:19 -07001145 void operator()(ObjPtr<mirror::Class> klass,
1146 ObjPtr<mirror::Reference> ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001147 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001148 CHECK(klass->IsTypeOfReferenceClass());
1149 this->operator()(ref, mirror::Reference::ReferentOffset(), false);
1150 }
1151
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001152 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001153 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001154 if (!root->IsNull()) {
1155 VisitRoot(root);
1156 }
1157 }
1158
1159 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001160 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001161 VerifyNoFromSpaceRefsVisitor visitor(collector_);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001162 visitor(root->AsMirrorPtr());
1163 }
1164
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001165 private:
Mathieu Chartier97509952015-07-13 14:35:43 -07001166 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001167};
1168
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001169class ConcurrentCopying::VerifyNoFromSpaceRefsObjectVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001170 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001171 explicit VerifyNoFromSpaceRefsObjectVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001172 : collector_(collector) {}
1173 void operator()(mirror::Object* obj) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001174 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001175 ObjectCallback(obj, collector_);
1176 }
1177 static void ObjectCallback(mirror::Object* obj, void *arg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001178 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001179 CHECK(obj != nullptr);
1180 ConcurrentCopying* collector = reinterpret_cast<ConcurrentCopying*>(arg);
1181 space::RegionSpace* region_space = collector->RegionSpace();
1182 CHECK(!region_space->IsInFromSpace(obj)) << "Scanning object " << obj << " in from space";
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001183 VerifyNoFromSpaceRefsFieldVisitor visitor(collector);
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07001184 obj->VisitReferences</*kVisitNativeRoots*/true, kDefaultVerifyFlags, kWithoutReadBarrier>(
1185 visitor,
1186 visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001187 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001188 CHECK_EQ(obj->GetReadBarrierState(), ReadBarrier::WhiteState())
1189 << "obj=" << obj << " non-white rb_state " << obj->GetReadBarrierState();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001190 }
1191 }
1192
1193 private:
1194 ConcurrentCopying* const collector_;
1195};
1196
1197// Verify there's no from-space references left after the marking phase.
1198void ConcurrentCopying::VerifyNoFromSpaceReferences() {
1199 Thread* self = Thread::Current();
1200 DCHECK(Locks::mutator_lock_->IsExclusiveHeld(self));
Hiroshi Yamauchi00370822015-08-18 14:47:25 -07001201 // Verify all threads have is_gc_marking to be false
1202 {
1203 MutexLock mu(self, *Locks::thread_list_lock_);
1204 std::list<Thread*> thread_list = Runtime::Current()->GetThreadList()->GetList();
1205 for (Thread* thread : thread_list) {
1206 CHECK(!thread->GetIsGcMarking());
1207 }
1208 }
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001209 VerifyNoFromSpaceRefsObjectVisitor visitor(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001210 // Roots.
1211 {
1212 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001213 VerifyNoFromSpaceRefsVisitor ref_visitor(this);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001214 Runtime::Current()->VisitRoots(&ref_visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001215 }
1216 // The to-space.
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001217 region_space_->WalkToSpace(VerifyNoFromSpaceRefsObjectVisitor::ObjectCallback, this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001218 // Non-moving spaces.
1219 {
1220 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1221 heap_->GetMarkBitmap()->Visit(visitor);
1222 }
1223 // The alloc stack.
1224 {
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001225 VerifyNoFromSpaceRefsVisitor ref_visitor(this);
Mathieu Chartiercb535da2015-01-23 13:50:03 -08001226 for (auto* it = heap_->allocation_stack_->Begin(), *end = heap_->allocation_stack_->End();
1227 it < end; ++it) {
1228 mirror::Object* const obj = it->AsMirrorPtr();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001229 if (obj != nullptr && obj->GetClass() != nullptr) {
1230 // TODO: need to call this only if obj is alive?
1231 ref_visitor(obj);
1232 visitor(obj);
1233 }
1234 }
1235 }
1236 // TODO: LOS. But only refs in LOS are classes.
1237}
1238
1239// The following visitors are used to assert the to-space invariant.
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001240class ConcurrentCopying::AssertToSpaceInvariantRefsVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001241 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001242 explicit AssertToSpaceInvariantRefsVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001243 : collector_(collector) {}
1244
1245 void operator()(mirror::Object* ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001246 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001247 if (ref == nullptr) {
1248 // OK.
1249 return;
1250 }
1251 collector_->AssertToSpaceInvariant(nullptr, MemberOffset(0), ref);
1252 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001253
1254 private:
Mathieu Chartier97509952015-07-13 14:35:43 -07001255 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001256};
1257
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001258class ConcurrentCopying::AssertToSpaceInvariantFieldVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001259 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001260 explicit AssertToSpaceInvariantFieldVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001261 : collector_(collector) {}
1262
Mathieu Chartier31e88222016-10-14 18:43:19 -07001263 void operator()(ObjPtr<mirror::Object> obj,
1264 MemberOffset offset,
1265 bool is_static ATTRIBUTE_UNUSED) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001266 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001267 mirror::Object* ref =
1268 obj->GetFieldObject<mirror::Object, kDefaultVerifyFlags, kWithoutReadBarrier>(offset);
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001269 AssertToSpaceInvariantRefsVisitor visitor(collector_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001270 visitor(ref);
1271 }
Mathieu Chartier31e88222016-10-14 18:43:19 -07001272 void operator()(ObjPtr<mirror::Class> klass, ObjPtr<mirror::Reference> ref ATTRIBUTE_UNUSED) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001273 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001274 CHECK(klass->IsTypeOfReferenceClass());
1275 }
1276
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001277 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001278 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001279 if (!root->IsNull()) {
1280 VisitRoot(root);
1281 }
1282 }
1283
1284 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001285 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001286 AssertToSpaceInvariantRefsVisitor visitor(collector_);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001287 visitor(root->AsMirrorPtr());
1288 }
1289
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001290 private:
Mathieu Chartier97509952015-07-13 14:35:43 -07001291 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001292};
1293
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001294class ConcurrentCopying::AssertToSpaceInvariantObjectVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001295 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001296 explicit AssertToSpaceInvariantObjectVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001297 : collector_(collector) {}
1298 void operator()(mirror::Object* obj) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001299 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001300 ObjectCallback(obj, collector_);
1301 }
1302 static void ObjectCallback(mirror::Object* obj, void *arg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001303 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001304 CHECK(obj != nullptr);
1305 ConcurrentCopying* collector = reinterpret_cast<ConcurrentCopying*>(arg);
1306 space::RegionSpace* region_space = collector->RegionSpace();
1307 CHECK(!region_space->IsInFromSpace(obj)) << "Scanning object " << obj << " in from space";
1308 collector->AssertToSpaceInvariant(nullptr, MemberOffset(0), obj);
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001309 AssertToSpaceInvariantFieldVisitor visitor(collector);
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07001310 obj->VisitReferences</*kVisitNativeRoots*/true, kDefaultVerifyFlags, kWithoutReadBarrier>(
1311 visitor,
1312 visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001313 }
1314
1315 private:
Mathieu Chartier97509952015-07-13 14:35:43 -07001316 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001317};
1318
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001319class ConcurrentCopying::RevokeThreadLocalMarkStackCheckpoint : public Closure {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001320 public:
Roland Levillain3887c462015-08-12 18:15:42 +01001321 RevokeThreadLocalMarkStackCheckpoint(ConcurrentCopying* concurrent_copying,
1322 bool disable_weak_ref_access)
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001323 : concurrent_copying_(concurrent_copying),
1324 disable_weak_ref_access_(disable_weak_ref_access) {
1325 }
1326
1327 virtual void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
1328 // Note: self is not necessarily equal to thread since thread may be suspended.
1329 Thread* self = Thread::Current();
1330 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
1331 << thread->GetState() << " thread " << thread << " self " << self;
1332 // Revoke thread local mark stacks.
1333 accounting::AtomicStack<mirror::Object>* tl_mark_stack = thread->GetThreadLocalMarkStack();
1334 if (tl_mark_stack != nullptr) {
1335 MutexLock mu(self, concurrent_copying_->mark_stack_lock_);
1336 concurrent_copying_->revoked_mark_stacks_.push_back(tl_mark_stack);
1337 thread->SetThreadLocalMarkStack(nullptr);
1338 }
1339 // Disable weak ref access.
1340 if (disable_weak_ref_access_) {
1341 thread->SetWeakRefAccessEnabled(false);
1342 }
1343 // If thread is a running mutator, then act on behalf of the garbage collector.
1344 // See the code in ThreadList::RunCheckpoint.
Mathieu Chartier10d25082015-10-28 18:36:09 -07001345 concurrent_copying_->GetBarrier().Pass(self);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001346 }
1347
1348 private:
1349 ConcurrentCopying* const concurrent_copying_;
1350 const bool disable_weak_ref_access_;
1351};
1352
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001353void ConcurrentCopying::RevokeThreadLocalMarkStacks(bool disable_weak_ref_access,
1354 Closure* checkpoint_callback) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001355 Thread* self = Thread::Current();
1356 RevokeThreadLocalMarkStackCheckpoint check_point(this, disable_weak_ref_access);
1357 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1358 gc_barrier_->Init(self, 0);
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001359 size_t barrier_count = thread_list->RunCheckpoint(&check_point, checkpoint_callback);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001360 // If there are no threads to wait which implys that all the checkpoint functions are finished,
1361 // then no need to release the mutator lock.
1362 if (barrier_count == 0) {
1363 return;
1364 }
1365 Locks::mutator_lock_->SharedUnlock(self);
1366 {
1367 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
1368 gc_barrier_->Increment(self, barrier_count);
1369 }
1370 Locks::mutator_lock_->SharedLock(self);
1371}
1372
1373void ConcurrentCopying::RevokeThreadLocalMarkStack(Thread* thread) {
1374 Thread* self = Thread::Current();
1375 CHECK_EQ(self, thread);
1376 accounting::AtomicStack<mirror::Object>* tl_mark_stack = thread->GetThreadLocalMarkStack();
1377 if (tl_mark_stack != nullptr) {
1378 CHECK(is_marking_);
1379 MutexLock mu(self, mark_stack_lock_);
1380 revoked_mark_stacks_.push_back(tl_mark_stack);
1381 thread->SetThreadLocalMarkStack(nullptr);
1382 }
1383}
1384
1385void ConcurrentCopying::ProcessMarkStack() {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001386 if (kVerboseMode) {
1387 LOG(INFO) << "ProcessMarkStack. ";
1388 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001389 bool empty_prev = false;
1390 while (true) {
1391 bool empty = ProcessMarkStackOnce();
1392 if (empty_prev && empty) {
1393 // Saw empty mark stack for a second time, done.
1394 break;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001395 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001396 empty_prev = empty;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001397 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001398}
1399
1400bool ConcurrentCopying::ProcessMarkStackOnce() {
1401 Thread* self = Thread::Current();
1402 CHECK(thread_running_gc_ != nullptr);
1403 CHECK(self == thread_running_gc_);
1404 CHECK(self->GetThreadLocalMarkStack() == nullptr);
1405 size_t count = 0;
1406 MarkStackMode mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1407 if (mark_stack_mode == kMarkStackModeThreadLocal) {
1408 // Process the thread-local mark stacks and the GC mark stack.
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001409 count += ProcessThreadLocalMarkStacks(false, nullptr);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001410 while (!gc_mark_stack_->IsEmpty()) {
1411 mirror::Object* to_ref = gc_mark_stack_->PopBack();
1412 ProcessMarkStackRef(to_ref);
1413 ++count;
1414 }
1415 gc_mark_stack_->Reset();
1416 } else if (mark_stack_mode == kMarkStackModeShared) {
Hiroshi Yamauchi30493242016-11-03 13:06:52 -07001417 // Do an empty checkpoint to avoid a race with a mutator preempted in the middle of a read
1418 // barrier but before pushing onto the mark stack. b/32508093. Note the weak ref access is
1419 // disabled at this point.
1420 IssueEmptyCheckpoint();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001421 // Process the shared GC mark stack with a lock.
1422 {
1423 MutexLock mu(self, mark_stack_lock_);
1424 CHECK(revoked_mark_stacks_.empty());
1425 }
1426 while (true) {
1427 std::vector<mirror::Object*> refs;
1428 {
1429 // Copy refs with lock. Note the number of refs should be small.
1430 MutexLock mu(self, mark_stack_lock_);
1431 if (gc_mark_stack_->IsEmpty()) {
1432 break;
1433 }
1434 for (StackReference<mirror::Object>* p = gc_mark_stack_->Begin();
1435 p != gc_mark_stack_->End(); ++p) {
1436 refs.push_back(p->AsMirrorPtr());
1437 }
1438 gc_mark_stack_->Reset();
1439 }
1440 for (mirror::Object* ref : refs) {
1441 ProcessMarkStackRef(ref);
1442 ++count;
1443 }
1444 }
1445 } else {
1446 CHECK_EQ(static_cast<uint32_t>(mark_stack_mode),
1447 static_cast<uint32_t>(kMarkStackModeGcExclusive));
1448 {
1449 MutexLock mu(self, mark_stack_lock_);
1450 CHECK(revoked_mark_stacks_.empty());
1451 }
1452 // Process the GC mark stack in the exclusive mode. No need to take the lock.
1453 while (!gc_mark_stack_->IsEmpty()) {
1454 mirror::Object* to_ref = gc_mark_stack_->PopBack();
1455 ProcessMarkStackRef(to_ref);
1456 ++count;
1457 }
1458 gc_mark_stack_->Reset();
1459 }
1460
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001461 // Return true if the stack was empty.
1462 return count == 0;
1463}
1464
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001465size_t ConcurrentCopying::ProcessThreadLocalMarkStacks(bool disable_weak_ref_access,
1466 Closure* checkpoint_callback) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001467 // Run a checkpoint to collect all thread local mark stacks and iterate over them all.
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001468 RevokeThreadLocalMarkStacks(disable_weak_ref_access, checkpoint_callback);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001469 size_t count = 0;
1470 std::vector<accounting::AtomicStack<mirror::Object>*> mark_stacks;
1471 {
1472 MutexLock mu(Thread::Current(), mark_stack_lock_);
1473 // Make a copy of the mark stack vector.
1474 mark_stacks = revoked_mark_stacks_;
1475 revoked_mark_stacks_.clear();
1476 }
1477 for (accounting::AtomicStack<mirror::Object>* mark_stack : mark_stacks) {
1478 for (StackReference<mirror::Object>* p = mark_stack->Begin(); p != mark_stack->End(); ++p) {
1479 mirror::Object* to_ref = p->AsMirrorPtr();
1480 ProcessMarkStackRef(to_ref);
1481 ++count;
1482 }
1483 {
1484 MutexLock mu(Thread::Current(), mark_stack_lock_);
1485 if (pooled_mark_stacks_.size() >= kMarkStackPoolSize) {
1486 // The pool has enough. Delete it.
1487 delete mark_stack;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001488 } else {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001489 // Otherwise, put it into the pool for later reuse.
1490 mark_stack->Reset();
1491 pooled_mark_stacks_.push_back(mark_stack);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001492 }
1493 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001494 }
1495 return count;
1496}
1497
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001498inline void ConcurrentCopying::ProcessMarkStackRef(mirror::Object* to_ref) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001499 DCHECK(!region_space_->IsInFromSpace(to_ref));
1500 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001501 DCHECK(to_ref->GetReadBarrierState() == ReadBarrier::GrayState())
1502 << " " << to_ref << " " << to_ref->GetReadBarrierState()
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001503 << " is_marked=" << IsMarked(to_ref);
1504 }
Mathieu Chartierc381c362016-08-23 13:27:53 -07001505 bool add_to_live_bytes = false;
1506 if (region_space_->IsInUnevacFromSpace(to_ref)) {
1507 // Mark the bitmap only in the GC thread here so that we don't need a CAS.
1508 if (!kUseBakerReadBarrier || !region_space_bitmap_->Set(to_ref)) {
1509 // It may be already marked if we accidentally pushed the same object twice due to the racy
1510 // bitmap read in MarkUnevacFromSpaceRegion.
1511 Scan(to_ref);
1512 // Only add to the live bytes if the object was not already marked.
1513 add_to_live_bytes = true;
1514 }
1515 } else {
1516 Scan(to_ref);
1517 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001518 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001519 DCHECK(to_ref->GetReadBarrierState() == ReadBarrier::GrayState())
1520 << " " << to_ref << " " << to_ref->GetReadBarrierState()
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001521 << " is_marked=" << IsMarked(to_ref);
1522 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001523#ifdef USE_BAKER_OR_BROOKS_READ_BARRIER
Hiroshi Yamauchi39c12d42016-12-06 16:46:37 -08001524 mirror::Object* referent = nullptr;
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001525 if (UNLIKELY((to_ref->GetClass<kVerifyNone, kWithoutReadBarrier>()->IsTypeOfReferenceClass() &&
Hiroshi Yamauchi39c12d42016-12-06 16:46:37 -08001526 (referent = to_ref->AsReference()->GetReferent<kWithoutReadBarrier>()) != nullptr &&
1527 !IsInToSpace(referent)))) {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001528 // Leave this reference gray in the queue so that GetReferent() will trigger a read barrier. We
1529 // will change it to white later in ReferenceQueue::DequeuePendingReference().
Richard Uhlere3627402016-02-02 13:36:55 -08001530 DCHECK(to_ref->AsReference()->GetPendingNext() != nullptr) << "Left unenqueued ref gray " << to_ref;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001531 } else {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001532 // We may occasionally leave a reference white in the queue if its referent happens to be
1533 // concurrently marked after the Scan() call above has enqueued the Reference, in which case the
1534 // above IsInToSpace() evaluates to true and we change the color from gray to white here in this
1535 // else block.
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001536 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001537 bool success = to_ref->AtomicSetReadBarrierState</*kCasRelease*/true>(
1538 ReadBarrier::GrayState(),
1539 ReadBarrier::WhiteState());
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001540 DCHECK(success) << "Must succeed as we won the race.";
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001541 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001542 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001543#else
1544 DCHECK(!kUseBakerReadBarrier);
1545#endif
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001546
Mathieu Chartierc381c362016-08-23 13:27:53 -07001547 if (add_to_live_bytes) {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001548 // Add to the live bytes per unevacuated from space. Note this code is always run by the
1549 // GC-running thread (no synchronization required).
1550 DCHECK(region_space_bitmap_->Test(to_ref));
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07001551 size_t obj_size = to_ref->SizeOf<kDefaultVerifyFlags>();
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001552 size_t alloc_size = RoundUp(obj_size, space::RegionSpace::kAlignment);
1553 region_space_->AddLiveBytes(to_ref, alloc_size);
1554 }
Andreas Gampee3ce7872017-02-22 13:36:21 -08001555 if (ReadBarrier::kEnableToSpaceInvariantChecks) {
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001556 AssertToSpaceInvariantObjectVisitor visitor(this);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001557 visitor(to_ref);
1558 }
1559}
1560
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001561class ConcurrentCopying::DisableWeakRefAccessCallback : public Closure {
1562 public:
1563 explicit DisableWeakRefAccessCallback(ConcurrentCopying* concurrent_copying)
1564 : concurrent_copying_(concurrent_copying) {
1565 }
1566
1567 void Run(Thread* self ATTRIBUTE_UNUSED) OVERRIDE REQUIRES(Locks::thread_list_lock_) {
1568 // This needs to run under the thread_list_lock_ critical section in ThreadList::RunCheckpoint()
1569 // to avoid a deadlock b/31500969.
1570 CHECK(concurrent_copying_->weak_ref_access_enabled_);
1571 concurrent_copying_->weak_ref_access_enabled_ = false;
1572 }
1573
1574 private:
1575 ConcurrentCopying* const concurrent_copying_;
1576};
1577
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001578void ConcurrentCopying::SwitchToSharedMarkStackMode() {
1579 Thread* self = Thread::Current();
1580 CHECK(thread_running_gc_ != nullptr);
1581 CHECK_EQ(self, thread_running_gc_);
1582 CHECK(self->GetThreadLocalMarkStack() == nullptr);
1583 MarkStackMode before_mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1584 CHECK_EQ(static_cast<uint32_t>(before_mark_stack_mode),
1585 static_cast<uint32_t>(kMarkStackModeThreadLocal));
1586 mark_stack_mode_.StoreRelaxed(kMarkStackModeShared);
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001587 DisableWeakRefAccessCallback dwrac(this);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001588 // Process the thread local mark stacks one last time after switching to the shared mark stack
1589 // mode and disable weak ref accesses.
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001590 ProcessThreadLocalMarkStacks(true, &dwrac);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001591 if (kVerboseMode) {
1592 LOG(INFO) << "Switched to shared mark stack mode and disabled weak ref access";
1593 }
1594}
1595
1596void ConcurrentCopying::SwitchToGcExclusiveMarkStackMode() {
1597 Thread* self = Thread::Current();
1598 CHECK(thread_running_gc_ != nullptr);
1599 CHECK_EQ(self, thread_running_gc_);
1600 CHECK(self->GetThreadLocalMarkStack() == nullptr);
1601 MarkStackMode before_mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1602 CHECK_EQ(static_cast<uint32_t>(before_mark_stack_mode),
1603 static_cast<uint32_t>(kMarkStackModeShared));
1604 mark_stack_mode_.StoreRelaxed(kMarkStackModeGcExclusive);
1605 QuasiAtomic::ThreadFenceForConstructor();
1606 if (kVerboseMode) {
1607 LOG(INFO) << "Switched to GC exclusive mark stack mode";
1608 }
1609}
1610
1611void ConcurrentCopying::CheckEmptyMarkStack() {
1612 Thread* self = Thread::Current();
1613 CHECK(thread_running_gc_ != nullptr);
1614 CHECK_EQ(self, thread_running_gc_);
1615 CHECK(self->GetThreadLocalMarkStack() == nullptr);
1616 MarkStackMode mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1617 if (mark_stack_mode == kMarkStackModeThreadLocal) {
1618 // Thread-local mark stack mode.
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001619 RevokeThreadLocalMarkStacks(false, nullptr);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001620 MutexLock mu(Thread::Current(), mark_stack_lock_);
1621 if (!revoked_mark_stacks_.empty()) {
1622 for (accounting::AtomicStack<mirror::Object>* mark_stack : revoked_mark_stacks_) {
1623 while (!mark_stack->IsEmpty()) {
1624 mirror::Object* obj = mark_stack->PopBack();
1625 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001626 uint32_t rb_state = obj->GetReadBarrierState();
1627 LOG(INFO) << "On mark queue : " << obj << " " << obj->PrettyTypeOf() << " rb_state="
1628 << rb_state << " is_marked=" << IsMarked(obj);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001629 } else {
David Sehr709b0702016-10-13 09:12:37 -07001630 LOG(INFO) << "On mark queue : " << obj << " " << obj->PrettyTypeOf()
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001631 << " is_marked=" << IsMarked(obj);
1632 }
1633 }
1634 }
1635 LOG(FATAL) << "mark stack is not empty";
1636 }
1637 } else {
1638 // Shared, GC-exclusive, or off.
1639 MutexLock mu(Thread::Current(), mark_stack_lock_);
1640 CHECK(gc_mark_stack_->IsEmpty());
1641 CHECK(revoked_mark_stacks_.empty());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001642 }
1643}
1644
1645void ConcurrentCopying::SweepSystemWeaks(Thread* self) {
1646 TimingLogger::ScopedTiming split("SweepSystemWeaks", GetTimings());
1647 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier97509952015-07-13 14:35:43 -07001648 Runtime::Current()->SweepSystemWeaks(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001649}
1650
1651void ConcurrentCopying::Sweep(bool swap_bitmaps) {
1652 {
1653 TimingLogger::ScopedTiming t("MarkStackAsLive", GetTimings());
1654 accounting::ObjectStack* live_stack = heap_->GetLiveStack();
1655 if (kEnableFromSpaceAccountingCheck) {
1656 CHECK_GE(live_stack_freeze_size_, live_stack->Size());
1657 }
1658 heap_->MarkAllocStackAsLive(live_stack);
1659 live_stack->Reset();
1660 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001661 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001662 TimingLogger::ScopedTiming split("Sweep", GetTimings());
1663 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
1664 if (space->IsContinuousMemMapAllocSpace()) {
1665 space::ContinuousMemMapAllocSpace* alloc_space = space->AsContinuousMemMapAllocSpace();
Mathieu Chartier763a31e2015-11-16 16:05:55 -08001666 if (space == region_space_ || immune_spaces_.ContainsSpace(space)) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001667 continue;
1668 }
1669 TimingLogger::ScopedTiming split2(
1670 alloc_space->IsZygoteSpace() ? "SweepZygoteSpace" : "SweepAllocSpace", GetTimings());
1671 RecordFree(alloc_space->Sweep(swap_bitmaps));
1672 }
1673 }
1674 SweepLargeObjects(swap_bitmaps);
1675}
1676
Mathieu Chartier962cd7a2016-08-16 12:15:59 -07001677void ConcurrentCopying::MarkZygoteLargeObjects() {
1678 TimingLogger::ScopedTiming split(__FUNCTION__, GetTimings());
1679 Thread* const self = Thread::Current();
1680 WriterMutexLock rmu(self, *Locks::heap_bitmap_lock_);
1681 space::LargeObjectSpace* const los = heap_->GetLargeObjectsSpace();
1682 // Pick the current live bitmap (mark bitmap if swapped).
1683 accounting::LargeObjectBitmap* const live_bitmap = los->GetLiveBitmap();
1684 accounting::LargeObjectBitmap* const mark_bitmap = los->GetMarkBitmap();
1685 // Walk through all of the objects and explicitly mark the zygote ones so they don't get swept.
Mathieu Chartier208aaf02016-10-25 10:45:08 -07001686 std::pair<uint8_t*, uint8_t*> range = los->GetBeginEndAtomic();
1687 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(range.first),
1688 reinterpret_cast<uintptr_t>(range.second),
Mathieu Chartier962cd7a2016-08-16 12:15:59 -07001689 [mark_bitmap, los, self](mirror::Object* obj)
1690 REQUIRES(Locks::heap_bitmap_lock_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001691 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier962cd7a2016-08-16 12:15:59 -07001692 if (los->IsZygoteLargeObject(self, obj)) {
1693 mark_bitmap->Set(obj);
1694 }
1695 });
1696}
1697
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001698void ConcurrentCopying::SweepLargeObjects(bool swap_bitmaps) {
1699 TimingLogger::ScopedTiming split("SweepLargeObjects", GetTimings());
1700 RecordFreeLOS(heap_->GetLargeObjectsSpace()->Sweep(swap_bitmaps));
1701}
1702
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001703void ConcurrentCopying::ReclaimPhase() {
1704 TimingLogger::ScopedTiming split("ReclaimPhase", GetTimings());
1705 if (kVerboseMode) {
1706 LOG(INFO) << "GC ReclaimPhase";
1707 }
1708 Thread* self = Thread::Current();
1709
1710 {
1711 // Double-check that the mark stack is empty.
1712 // Note: need to set this after VerifyNoFromSpaceRef().
1713 is_asserting_to_space_invariant_ = false;
1714 QuasiAtomic::ThreadFenceForConstructor();
1715 if (kVerboseMode) {
1716 LOG(INFO) << "Issue an empty check point. ";
1717 }
1718 IssueEmptyCheckpoint();
1719 // Disable the check.
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001720 is_mark_stack_push_disallowed_.StoreSequentiallyConsistent(0);
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001721 if (kUseBakerReadBarrier) {
1722 updated_all_immune_objects_.StoreSequentiallyConsistent(false);
1723 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001724 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001725 }
1726
1727 {
1728 // Record freed objects.
1729 TimingLogger::ScopedTiming split2("RecordFree", GetTimings());
1730 // Don't include thread-locals that are in the to-space.
Mathieu Chartier371b0472017-02-27 16:37:21 -08001731 const uint64_t from_bytes = region_space_->GetBytesAllocatedInFromSpace();
1732 const uint64_t from_objects = region_space_->GetObjectsAllocatedInFromSpace();
1733 const uint64_t unevac_from_bytes = region_space_->GetBytesAllocatedInUnevacFromSpace();
1734 const uint64_t unevac_from_objects = region_space_->GetObjectsAllocatedInUnevacFromSpace();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001735 uint64_t to_bytes = bytes_moved_.LoadSequentiallyConsistent();
Mathieu Chartiercca44a02016-08-17 10:07:29 -07001736 cumulative_bytes_moved_.FetchAndAddRelaxed(to_bytes);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001737 uint64_t to_objects = objects_moved_.LoadSequentiallyConsistent();
Mathieu Chartiercca44a02016-08-17 10:07:29 -07001738 cumulative_objects_moved_.FetchAndAddRelaxed(to_objects);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001739 if (kEnableFromSpaceAccountingCheck) {
1740 CHECK_EQ(from_space_num_objects_at_first_pause_, from_objects + unevac_from_objects);
1741 CHECK_EQ(from_space_num_bytes_at_first_pause_, from_bytes + unevac_from_bytes);
1742 }
1743 CHECK_LE(to_objects, from_objects);
1744 CHECK_LE(to_bytes, from_bytes);
Mathieu Chartier371b0472017-02-27 16:37:21 -08001745 // cleared_bytes and cleared_objects may be greater than the from space equivalents since
1746 // ClearFromSpace may clear empty unevac regions.
1747 uint64_t cleared_bytes;
1748 uint64_t cleared_objects;
1749 {
1750 TimingLogger::ScopedTiming split4("ClearFromSpace", GetTimings());
1751 region_space_->ClearFromSpace(&cleared_bytes, &cleared_objects);
1752 CHECK_GE(cleared_bytes, from_bytes);
1753 CHECK_GE(cleared_objects, from_objects);
1754 }
1755 int64_t freed_bytes = cleared_bytes - to_bytes;
1756 int64_t freed_objects = cleared_objects - to_objects;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001757 if (kVerboseMode) {
1758 LOG(INFO) << "RecordFree:"
1759 << " from_bytes=" << from_bytes << " from_objects=" << from_objects
1760 << " unevac_from_bytes=" << unevac_from_bytes << " unevac_from_objects=" << unevac_from_objects
1761 << " to_bytes=" << to_bytes << " to_objects=" << to_objects
1762 << " freed_bytes=" << freed_bytes << " freed_objects=" << freed_objects
1763 << " from_space size=" << region_space_->FromSpaceSize()
1764 << " unevac_from_space size=" << region_space_->UnevacFromSpaceSize()
1765 << " to_space size=" << region_space_->ToSpaceSize();
1766 LOG(INFO) << "(before) num_bytes_allocated=" << heap_->num_bytes_allocated_.LoadSequentiallyConsistent();
1767 }
1768 RecordFree(ObjectBytePair(freed_objects, freed_bytes));
1769 if (kVerboseMode) {
1770 LOG(INFO) << "(after) num_bytes_allocated=" << heap_->num_bytes_allocated_.LoadSequentiallyConsistent();
1771 }
1772 }
1773
1774 {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001775 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001776 Sweep(false);
1777 SwapBitmaps();
1778 heap_->UnBindBitmaps();
1779
Mathieu Chartier7ec38dc2016-10-07 15:24:46 -07001780 // 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 -07001781 DCHECK(region_space_bitmap_ != nullptr);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001782 region_space_bitmap_ = nullptr;
1783 }
1784
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001785 CheckEmptyMarkStack();
1786
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001787 if (kVerboseMode) {
1788 LOG(INFO) << "GC end of ReclaimPhase";
1789 }
1790}
1791
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001792// Assert the to-space invariant.
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07001793void ConcurrentCopying::AssertToSpaceInvariant(mirror::Object* obj,
1794 MemberOffset offset,
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001795 mirror::Object* ref) {
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07001796 CHECK_EQ(heap_->collector_type_, kCollectorTypeCC);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001797 if (is_asserting_to_space_invariant_) {
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07001798 using RegionType = space::RegionSpace::RegionType;
1799 space::RegionSpace::RegionType type = region_space_->GetRegionType(ref);
1800 if (type == RegionType::kRegionTypeToSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001801 // OK.
1802 return;
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07001803 } else if (type == RegionType::kRegionTypeUnevacFromSpace) {
Mathieu Chartierc381c362016-08-23 13:27:53 -07001804 CHECK(IsMarkedInUnevacFromSpace(ref)) << ref;
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07001805 } else if (UNLIKELY(type == RegionType::kRegionTypeFromSpace)) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001806 // Not OK. Do extra logging.
1807 if (obj != nullptr) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001808 LogFromSpaceRefHolder(obj, offset);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001809 }
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07001810 ref->GetLockWord(false).Dump(LOG_STREAM(FATAL_WITHOUT_ABORT));
David Sehr709b0702016-10-13 09:12:37 -07001811 CHECK(false) << "Found from-space ref " << ref << " " << ref->PrettyTypeOf();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001812 } else {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001813 AssertToSpaceInvariantInNonMovingSpace(obj, ref);
1814 }
1815 }
1816}
1817
1818class RootPrinter {
1819 public:
1820 RootPrinter() { }
1821
1822 template <class MirrorType>
1823 ALWAYS_INLINE void VisitRootIfNonNull(mirror::CompressedReference<MirrorType>* root)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001824 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001825 if (!root->IsNull()) {
1826 VisitRoot(root);
1827 }
1828 }
1829
1830 template <class MirrorType>
1831 void VisitRoot(mirror::Object** root)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001832 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07001833 LOG(FATAL_WITHOUT_ABORT) << "root=" << root << " ref=" << *root;
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001834 }
1835
1836 template <class MirrorType>
1837 void VisitRoot(mirror::CompressedReference<MirrorType>* root)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001838 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07001839 LOG(FATAL_WITHOUT_ABORT) << "root=" << root << " ref=" << root->AsMirrorPtr();
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001840 }
1841};
1842
1843void ConcurrentCopying::AssertToSpaceInvariant(GcRootSource* gc_root_source,
1844 mirror::Object* ref) {
1845 CHECK(heap_->collector_type_ == kCollectorTypeCC) << static_cast<size_t>(heap_->collector_type_);
1846 if (is_asserting_to_space_invariant_) {
1847 if (region_space_->IsInToSpace(ref)) {
1848 // OK.
1849 return;
1850 } else if (region_space_->IsInUnevacFromSpace(ref)) {
Mathieu Chartierc381c362016-08-23 13:27:53 -07001851 CHECK(IsMarkedInUnevacFromSpace(ref)) << ref;
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001852 } else if (region_space_->IsInFromSpace(ref)) {
1853 // Not OK. Do extra logging.
1854 if (gc_root_source == nullptr) {
1855 // No info.
1856 } else if (gc_root_source->HasArtField()) {
1857 ArtField* field = gc_root_source->GetArtField();
David Sehr709b0702016-10-13 09:12:37 -07001858 LOG(FATAL_WITHOUT_ABORT) << "gc root in field " << field << " "
1859 << ArtField::PrettyField(field);
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001860 RootPrinter root_printer;
1861 field->VisitRoots(root_printer);
1862 } else if (gc_root_source->HasArtMethod()) {
1863 ArtMethod* method = gc_root_source->GetArtMethod();
David Sehr709b0702016-10-13 09:12:37 -07001864 LOG(FATAL_WITHOUT_ABORT) << "gc root in method " << method << " "
1865 << ArtMethod::PrettyMethod(method);
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001866 RootPrinter root_printer;
Andreas Gampe542451c2016-07-26 09:02:02 -07001867 method->VisitRoots(root_printer, kRuntimePointerSize);
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001868 }
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07001869 ref->GetLockWord(false).Dump(LOG_STREAM(FATAL_WITHOUT_ABORT));
1870 region_space_->DumpNonFreeRegions(LOG_STREAM(FATAL_WITHOUT_ABORT));
1871 PrintFileToLog("/proc/self/maps", LogSeverity::FATAL_WITHOUT_ABORT);
1872 MemMap::DumpMaps(LOG_STREAM(FATAL_WITHOUT_ABORT), true);
David Sehr709b0702016-10-13 09:12:37 -07001873 CHECK(false) << "Found from-space ref " << ref << " " << ref->PrettyTypeOf();
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001874 } else {
1875 AssertToSpaceInvariantInNonMovingSpace(nullptr, ref);
1876 }
1877 }
1878}
1879
1880void ConcurrentCopying::LogFromSpaceRefHolder(mirror::Object* obj, MemberOffset offset) {
1881 if (kUseBakerReadBarrier) {
David Sehr709b0702016-10-13 09:12:37 -07001882 LOG(INFO) << "holder=" << obj << " " << obj->PrettyTypeOf()
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001883 << " holder rb_state=" << obj->GetReadBarrierState();
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001884 } else {
David Sehr709b0702016-10-13 09:12:37 -07001885 LOG(INFO) << "holder=" << obj << " " << obj->PrettyTypeOf();
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001886 }
1887 if (region_space_->IsInFromSpace(obj)) {
1888 LOG(INFO) << "holder is in the from-space.";
1889 } else if (region_space_->IsInToSpace(obj)) {
1890 LOG(INFO) << "holder is in the to-space.";
1891 } else if (region_space_->IsInUnevacFromSpace(obj)) {
1892 LOG(INFO) << "holder is in the unevac from-space.";
Mathieu Chartierc381c362016-08-23 13:27:53 -07001893 if (IsMarkedInUnevacFromSpace(obj)) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001894 LOG(INFO) << "holder is marked in the region space bitmap.";
1895 } else {
1896 LOG(INFO) << "holder is not marked in the region space bitmap.";
1897 }
1898 } else {
1899 // In a non-moving space.
Mathieu Chartier763a31e2015-11-16 16:05:55 -08001900 if (immune_spaces_.ContainsObject(obj)) {
1901 LOG(INFO) << "holder is in an immune image or the zygote space.";
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001902 } else {
Mathieu Chartier763a31e2015-11-16 16:05:55 -08001903 LOG(INFO) << "holder is in a non-immune, non-moving (or main) space.";
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001904 accounting::ContinuousSpaceBitmap* mark_bitmap =
1905 heap_mark_bitmap_->GetContinuousSpaceBitmap(obj);
1906 accounting::LargeObjectBitmap* los_bitmap =
1907 heap_mark_bitmap_->GetLargeObjectBitmap(obj);
1908 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
1909 bool is_los = mark_bitmap == nullptr;
1910 if (!is_los && mark_bitmap->Test(obj)) {
1911 LOG(INFO) << "holder is marked in the mark bit map.";
1912 } else if (is_los && los_bitmap->Test(obj)) {
1913 LOG(INFO) << "holder is marked in the los bit map.";
1914 } else {
1915 // If ref is on the allocation stack, then it is considered
1916 // mark/alive (but not necessarily on the live stack.)
1917 if (IsOnAllocStack(obj)) {
1918 LOG(INFO) << "holder is on the alloc stack.";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001919 } else {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001920 LOG(INFO) << "holder is not marked or on the alloc stack.";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001921 }
1922 }
1923 }
1924 }
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001925 LOG(INFO) << "offset=" << offset.SizeValue();
1926}
1927
1928void ConcurrentCopying::AssertToSpaceInvariantInNonMovingSpace(mirror::Object* obj,
1929 mirror::Object* ref) {
1930 // In a non-moving spaces. Check that the ref is marked.
Mathieu Chartier763a31e2015-11-16 16:05:55 -08001931 if (immune_spaces_.ContainsObject(ref)) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001932 if (kUseBakerReadBarrier) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001933 // Immune object may not be gray if called from the GC.
1934 if (Thread::Current() == thread_running_gc_ && !gc_grays_immune_objects_) {
1935 return;
1936 }
1937 bool updated_all_immune_objects = updated_all_immune_objects_.LoadSequentiallyConsistent();
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001938 CHECK(updated_all_immune_objects || ref->GetReadBarrierState() == ReadBarrier::GrayState())
1939 << "Unmarked immune space ref. obj=" << obj << " rb_state="
1940 << (obj != nullptr ? obj->GetReadBarrierState() : 0U)
1941 << " ref=" << ref << " ref rb_state=" << ref->GetReadBarrierState()
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001942 << " updated_all_immune_objects=" << updated_all_immune_objects;
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001943 }
1944 } else {
1945 accounting::ContinuousSpaceBitmap* mark_bitmap =
1946 heap_mark_bitmap_->GetContinuousSpaceBitmap(ref);
1947 accounting::LargeObjectBitmap* los_bitmap =
1948 heap_mark_bitmap_->GetLargeObjectBitmap(ref);
1949 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
1950 bool is_los = mark_bitmap == nullptr;
1951 if ((!is_los && mark_bitmap->Test(ref)) ||
1952 (is_los && los_bitmap->Test(ref))) {
1953 // OK.
1954 } else {
1955 // If ref is on the allocation stack, then it may not be
1956 // marked live, but considered marked/alive (but not
1957 // necessarily on the live stack).
1958 CHECK(IsOnAllocStack(ref)) << "Unmarked ref that's not on the allocation stack. "
1959 << "obj=" << obj << " ref=" << ref;
1960 }
1961 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001962}
1963
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001964// Used to scan ref fields of an object.
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001965class ConcurrentCopying::RefFieldsVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001966 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001967 explicit RefFieldsVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001968 : collector_(collector) {}
1969
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07001970 void operator()(mirror::Object* obj, MemberOffset offset, bool /* is_static */)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001971 const ALWAYS_INLINE REQUIRES_SHARED(Locks::mutator_lock_)
1972 REQUIRES_SHARED(Locks::heap_bitmap_lock_) {
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07001973 collector_->Process(obj, offset);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001974 }
1975
Mathieu Chartier31e88222016-10-14 18:43:19 -07001976 void operator()(ObjPtr<mirror::Class> klass, ObjPtr<mirror::Reference> ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001977 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001978 CHECK(klass->IsTypeOfReferenceClass());
1979 collector_->DelayReferenceReferent(klass, ref);
1980 }
1981
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001982 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001983 ALWAYS_INLINE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001984 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001985 if (!root->IsNull()) {
1986 VisitRoot(root);
1987 }
1988 }
1989
1990 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001991 ALWAYS_INLINE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001992 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001993 collector_->MarkRoot</*kGrayImmuneObject*/false>(root);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001994 }
1995
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001996 private:
1997 ConcurrentCopying* const collector_;
1998};
1999
2000// Scan ref fields of an object.
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002001inline void ConcurrentCopying::Scan(mirror::Object* to_ref) {
Hiroshi Yamauchi9b60d502017-02-03 15:09:26 -08002002 if (kDisallowReadBarrierDuringScan && !Runtime::Current()->IsActiveTransaction()) {
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07002003 // Avoid all read barriers during visit references to help performance.
Hiroshi Yamauchi9b60d502017-02-03 15:09:26 -08002004 // Don't do this in transaction mode because we may read the old value of an field which may
2005 // trigger read barriers.
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07002006 Thread::Current()->ModifyDebugDisallowReadBarrier(1);
2007 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002008 DCHECK(!region_space_->IsInFromSpace(to_ref));
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002009 DCHECK_EQ(Thread::Current(), thread_running_gc_);
Mathieu Chartiera07f5592016-06-16 11:44:28 -07002010 RefFieldsVisitor visitor(this);
Hiroshi Yamauchi5496f692016-02-17 13:29:59 -08002011 // Disable the read barrier for a performance reason.
2012 to_ref->VisitReferences</*kVisitNativeRoots*/true, kDefaultVerifyFlags, kWithoutReadBarrier>(
2013 visitor, visitor);
Hiroshi Yamauchi9b60d502017-02-03 15:09:26 -08002014 if (kDisallowReadBarrierDuringScan && !Runtime::Current()->IsActiveTransaction()) {
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07002015 Thread::Current()->ModifyDebugDisallowReadBarrier(-1);
2016 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002017}
2018
2019// Process a field.
2020inline void ConcurrentCopying::Process(mirror::Object* obj, MemberOffset offset) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002021 DCHECK_EQ(Thread::Current(), thread_running_gc_);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002022 mirror::Object* ref = obj->GetFieldObject<
2023 mirror::Object, kVerifyNone, kWithoutReadBarrier, false>(offset);
Mathieu Chartierc381c362016-08-23 13:27:53 -07002024 mirror::Object* to_ref = Mark</*kGrayImmuneObject*/false, /*kFromGCThread*/true>(ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002025 if (to_ref == ref) {
2026 return;
2027 }
2028 // This may fail if the mutator writes to the field at the same time. But it's ok.
2029 mirror::Object* expected_ref = ref;
2030 mirror::Object* new_ref = to_ref;
2031 do {
2032 if (expected_ref !=
2033 obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier, false>(offset)) {
2034 // It was updated by the mutator.
2035 break;
2036 }
Hiroshi Yamauchifed3e2f2015-10-20 11:11:56 -07002037 } while (!obj->CasFieldWeakRelaxedObjectWithoutWriteBarrier<
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002038 false, false, kVerifyNone>(offset, expected_ref, new_ref));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002039}
2040
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002041// Process some roots.
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002042inline void ConcurrentCopying::VisitRoots(
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002043 mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED) {
2044 for (size_t i = 0; i < count; ++i) {
2045 mirror::Object** root = roots[i];
2046 mirror::Object* ref = *root;
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002047 mirror::Object* to_ref = Mark(ref);
2048 if (to_ref == ref) {
Mathieu Chartier4809d0a2015-04-07 10:39:04 -07002049 continue;
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002050 }
2051 Atomic<mirror::Object*>* addr = reinterpret_cast<Atomic<mirror::Object*>*>(root);
2052 mirror::Object* expected_ref = ref;
2053 mirror::Object* new_ref = to_ref;
2054 do {
2055 if (expected_ref != addr->LoadRelaxed()) {
2056 // It was updated by the mutator.
2057 break;
2058 }
Hiroshi Yamauchifed3e2f2015-10-20 11:11:56 -07002059 } while (!addr->CompareExchangeWeakRelaxed(expected_ref, new_ref));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002060 }
2061}
2062
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002063template<bool kGrayImmuneObject>
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002064inline void ConcurrentCopying::MarkRoot(mirror::CompressedReference<mirror::Object>* root) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002065 DCHECK(!root->IsNull());
2066 mirror::Object* const ref = root->AsMirrorPtr();
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002067 mirror::Object* to_ref = Mark<kGrayImmuneObject>(ref);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002068 if (to_ref != ref) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002069 auto* addr = reinterpret_cast<Atomic<mirror::CompressedReference<mirror::Object>>*>(root);
2070 auto expected_ref = mirror::CompressedReference<mirror::Object>::FromMirrorPtr(ref);
2071 auto new_ref = mirror::CompressedReference<mirror::Object>::FromMirrorPtr(to_ref);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002072 // If the cas fails, then it was updated by the mutator.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002073 do {
2074 if (ref != addr->LoadRelaxed().AsMirrorPtr()) {
2075 // It was updated by the mutator.
2076 break;
2077 }
Hiroshi Yamauchifed3e2f2015-10-20 11:11:56 -07002078 } while (!addr->CompareExchangeWeakRelaxed(expected_ref, new_ref));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002079 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002080}
2081
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002082inline void ConcurrentCopying::VisitRoots(
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002083 mirror::CompressedReference<mirror::Object>** roots, size_t count,
2084 const RootInfo& info ATTRIBUTE_UNUSED) {
2085 for (size_t i = 0; i < count; ++i) {
2086 mirror::CompressedReference<mirror::Object>* const root = roots[i];
2087 if (!root->IsNull()) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002088 // kGrayImmuneObject is true because this is used for the thread flip.
2089 MarkRoot</*kGrayImmuneObject*/true>(root);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002090 }
2091 }
2092}
2093
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002094// Temporary set gc_grays_immune_objects_ to true in a scope if the current thread is GC.
2095class ConcurrentCopying::ScopedGcGraysImmuneObjects {
2096 public:
2097 explicit ScopedGcGraysImmuneObjects(ConcurrentCopying* collector)
2098 : collector_(collector), enabled_(false) {
2099 if (kUseBakerReadBarrier &&
2100 collector_->thread_running_gc_ == Thread::Current() &&
2101 !collector_->gc_grays_immune_objects_) {
2102 collector_->gc_grays_immune_objects_ = true;
2103 enabled_ = true;
2104 }
2105 }
2106
2107 ~ScopedGcGraysImmuneObjects() {
2108 if (kUseBakerReadBarrier &&
2109 collector_->thread_running_gc_ == Thread::Current() &&
2110 enabled_) {
2111 DCHECK(collector_->gc_grays_immune_objects_);
2112 collector_->gc_grays_immune_objects_ = false;
2113 }
2114 }
2115
2116 private:
2117 ConcurrentCopying* const collector_;
2118 bool enabled_;
2119};
2120
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002121// Fill the given memory block with a dummy object. Used to fill in a
2122// copy of objects that was lost in race.
2123void ConcurrentCopying::FillWithDummyObject(mirror::Object* dummy_obj, size_t byte_size) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002124 // GC doesn't gray immune objects while scanning immune objects. But we need to trigger the read
2125 // barriers here because we need the updated reference to the int array class, etc. Temporary set
2126 // gc_grays_immune_objects_ to true so that we won't cause a DCHECK failure in MarkImmuneSpace().
2127 ScopedGcGraysImmuneObjects scoped_gc_gray_immune_objects(this);
Roland Levillain14d90572015-07-16 10:52:26 +01002128 CHECK_ALIGNED(byte_size, kObjectAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002129 memset(dummy_obj, 0, byte_size);
Mathieu Chartierd6636d32016-07-28 11:02:38 -07002130 // Avoid going through read barrier for since kDisallowReadBarrierDuringScan may be enabled.
2131 // Explicitly mark to make sure to get an object in the to-space.
2132 mirror::Class* int_array_class = down_cast<mirror::Class*>(
2133 Mark(mirror::IntArray::GetArrayClass<kWithoutReadBarrier>()));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002134 CHECK(int_array_class != nullptr);
2135 AssertToSpaceInvariant(nullptr, MemberOffset(0), int_array_class);
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07002136 size_t component_size = int_array_class->GetComponentSize<kWithoutReadBarrier>();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002137 CHECK_EQ(component_size, sizeof(int32_t));
2138 size_t data_offset = mirror::Array::DataOffset(component_size).SizeValue();
2139 if (data_offset > byte_size) {
2140 // An int array is too big. Use java.lang.Object.
Mathieu Chartier9aef9922017-04-23 13:53:50 -07002141 CHECK(java_lang_Object_ != nullptr);
Mathieu Chartier3ed8ec12017-04-20 19:28:54 -07002142 AssertToSpaceInvariant(nullptr, MemberOffset(0), java_lang_Object_);
2143 CHECK_EQ(byte_size, (java_lang_Object_->GetObjectSize<kVerifyNone, kWithoutReadBarrier>()));
2144 dummy_obj->SetClass(java_lang_Object_);
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07002145 CHECK_EQ(byte_size, (dummy_obj->SizeOf<kVerifyNone>()));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002146 } else {
2147 // Use an int array.
2148 dummy_obj->SetClass(int_array_class);
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07002149 CHECK((dummy_obj->IsArrayInstance<kVerifyNone, kWithoutReadBarrier>()));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002150 int32_t length = (byte_size - data_offset) / component_size;
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07002151 mirror::Array* dummy_arr = dummy_obj->AsArray<kVerifyNone, kWithoutReadBarrier>();
2152 dummy_arr->SetLength(length);
2153 CHECK_EQ(dummy_arr->GetLength(), length)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002154 << "byte_size=" << byte_size << " length=" << length
2155 << " component_size=" << component_size << " data_offset=" << data_offset;
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07002156 CHECK_EQ(byte_size, (dummy_obj->SizeOf<kVerifyNone>()))
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002157 << "byte_size=" << byte_size << " length=" << length
2158 << " component_size=" << component_size << " data_offset=" << data_offset;
2159 }
2160}
2161
2162// Reuse the memory blocks that were copy of objects that were lost in race.
2163mirror::Object* ConcurrentCopying::AllocateInSkippedBlock(size_t alloc_size) {
2164 // Try to reuse the blocks that were unused due to CAS failures.
Roland Levillain14d90572015-07-16 10:52:26 +01002165 CHECK_ALIGNED(alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002166 Thread* self = Thread::Current();
2167 size_t min_object_size = RoundUp(sizeof(mirror::Object), space::RegionSpace::kAlignment);
Mathieu Chartierd6636d32016-07-28 11:02:38 -07002168 size_t byte_size;
2169 uint8_t* addr;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002170 {
Mathieu Chartierd6636d32016-07-28 11:02:38 -07002171 MutexLock mu(self, skipped_blocks_lock_);
2172 auto it = skipped_blocks_map_.lower_bound(alloc_size);
2173 if (it == skipped_blocks_map_.end()) {
2174 // Not found.
2175 return nullptr;
2176 }
2177 byte_size = it->first;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002178 CHECK_GE(byte_size, alloc_size);
2179 if (byte_size > alloc_size && byte_size - alloc_size < min_object_size) {
2180 // If remainder would be too small for a dummy object, retry with a larger request size.
2181 it = skipped_blocks_map_.lower_bound(alloc_size + min_object_size);
2182 if (it == skipped_blocks_map_.end()) {
2183 // Not found.
2184 return nullptr;
2185 }
Roland Levillain14d90572015-07-16 10:52:26 +01002186 CHECK_ALIGNED(it->first - alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002187 CHECK_GE(it->first - alloc_size, min_object_size)
2188 << "byte_size=" << byte_size << " it->first=" << it->first << " alloc_size=" << alloc_size;
2189 }
Mathieu Chartierd6636d32016-07-28 11:02:38 -07002190 // Found a block.
2191 CHECK(it != skipped_blocks_map_.end());
2192 byte_size = it->first;
2193 addr = it->second;
2194 CHECK_GE(byte_size, alloc_size);
2195 CHECK(region_space_->IsInToSpace(reinterpret_cast<mirror::Object*>(addr)));
2196 CHECK_ALIGNED(byte_size, space::RegionSpace::kAlignment);
2197 if (kVerboseMode) {
2198 LOG(INFO) << "Reusing skipped bytes : " << reinterpret_cast<void*>(addr) << ", " << byte_size;
2199 }
2200 skipped_blocks_map_.erase(it);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002201 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002202 memset(addr, 0, byte_size);
2203 if (byte_size > alloc_size) {
2204 // Return the remainder to the map.
Roland Levillain14d90572015-07-16 10:52:26 +01002205 CHECK_ALIGNED(byte_size - alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002206 CHECK_GE(byte_size - alloc_size, min_object_size);
Mathieu Chartierd6636d32016-07-28 11:02:38 -07002207 // FillWithDummyObject may mark an object, avoid holding skipped_blocks_lock_ to prevent lock
2208 // violation and possible deadlock. The deadlock case is a recursive case:
2209 // FillWithDummyObject -> IntArray::GetArrayClass -> Mark -> Copy -> AllocateInSkippedBlock.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002210 FillWithDummyObject(reinterpret_cast<mirror::Object*>(addr + alloc_size),
2211 byte_size - alloc_size);
2212 CHECK(region_space_->IsInToSpace(reinterpret_cast<mirror::Object*>(addr + alloc_size)));
Mathieu Chartierd6636d32016-07-28 11:02:38 -07002213 {
2214 MutexLock mu(self, skipped_blocks_lock_);
2215 skipped_blocks_map_.insert(std::make_pair(byte_size - alloc_size, addr + alloc_size));
2216 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002217 }
2218 return reinterpret_cast<mirror::Object*>(addr);
2219}
2220
Mathieu Chartieref496d92017-04-28 18:58:59 -07002221mirror::Object* ConcurrentCopying::Copy(mirror::Object* from_ref,
2222 mirror::Object* holder,
2223 MemberOffset offset) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002224 DCHECK(region_space_->IsInFromSpace(from_ref));
Mathieu Chartieref496d92017-04-28 18:58:59 -07002225 // If the class pointer is null, the object is invalid. This could occur for a dangling pointer
2226 // from a previous GC that is either inside or outside the allocated region.
2227 mirror::Class* klass = from_ref->GetClass<kVerifyNone, kWithoutReadBarrier>();
2228 if (UNLIKELY(klass == nullptr)) {
2229 heap_->GetVerification()->LogHeapCorruption(holder, offset, from_ref, /* fatal */ true);
2230 }
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07002231 // There must not be a read barrier to avoid nested RB that might violate the to-space invariant.
2232 // Note that from_ref is a from space ref so the SizeOf() call will access the from-space meta
2233 // objects, but it's ok and necessary.
2234 size_t obj_size = from_ref->SizeOf<kDefaultVerifyFlags>();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002235 size_t region_space_alloc_size = RoundUp(obj_size, space::RegionSpace::kAlignment);
2236 size_t region_space_bytes_allocated = 0U;
2237 size_t non_moving_space_bytes_allocated = 0U;
2238 size_t bytes_allocated = 0U;
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07002239 size_t dummy;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002240 mirror::Object* to_ref = region_space_->AllocNonvirtual<true>(
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07002241 region_space_alloc_size, &region_space_bytes_allocated, nullptr, &dummy);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002242 bytes_allocated = region_space_bytes_allocated;
2243 if (to_ref != nullptr) {
2244 DCHECK_EQ(region_space_alloc_size, region_space_bytes_allocated);
2245 }
2246 bool fall_back_to_non_moving = false;
2247 if (UNLIKELY(to_ref == nullptr)) {
2248 // Failed to allocate in the region space. Try the skipped blocks.
2249 to_ref = AllocateInSkippedBlock(region_space_alloc_size);
2250 if (to_ref != nullptr) {
2251 // Succeeded to allocate in a skipped block.
2252 if (heap_->use_tlab_) {
2253 // This is necessary for the tlab case as it's not accounted in the space.
2254 region_space_->RecordAlloc(to_ref);
2255 }
2256 bytes_allocated = region_space_alloc_size;
2257 } else {
2258 // Fall back to the non-moving space.
2259 fall_back_to_non_moving = true;
2260 if (kVerboseMode) {
2261 LOG(INFO) << "Out of memory in the to-space. Fall back to non-moving. skipped_bytes="
2262 << to_space_bytes_skipped_.LoadSequentiallyConsistent()
2263 << " skipped_objects=" << to_space_objects_skipped_.LoadSequentiallyConsistent();
2264 }
2265 fall_back_to_non_moving = true;
2266 to_ref = heap_->non_moving_space_->Alloc(Thread::Current(), obj_size,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07002267 &non_moving_space_bytes_allocated, nullptr, &dummy);
Mathieu Chartierb01335c2017-03-22 13:15:01 -07002268 if (UNLIKELY(to_ref == nullptr)) {
2269 LOG(FATAL_WITHOUT_ABORT) << "Fall-back non-moving space allocation failed for a "
2270 << obj_size << " byte object in region type "
2271 << region_space_->GetRegionType(from_ref);
2272 LOG(FATAL) << "Object address=" << from_ref << " type=" << from_ref->PrettyTypeOf();
2273 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002274 bytes_allocated = non_moving_space_bytes_allocated;
2275 // Mark it in the mark bitmap.
2276 accounting::ContinuousSpaceBitmap* mark_bitmap =
2277 heap_mark_bitmap_->GetContinuousSpaceBitmap(to_ref);
2278 CHECK(mark_bitmap != nullptr);
2279 CHECK(!mark_bitmap->AtomicTestAndSet(to_ref));
2280 }
2281 }
2282 DCHECK(to_ref != nullptr);
2283
Mathieu Chartierd818adb2016-09-15 13:12:47 -07002284 // Copy the object excluding the lock word since that is handled in the loop.
Mathieu Chartieref496d92017-04-28 18:58:59 -07002285 to_ref->SetClass(klass);
Mathieu Chartierd818adb2016-09-15 13:12:47 -07002286 const size_t kObjectHeaderSize = sizeof(mirror::Object);
2287 DCHECK_GE(obj_size, kObjectHeaderSize);
2288 static_assert(kObjectHeaderSize == sizeof(mirror::HeapReference<mirror::Class>) +
2289 sizeof(LockWord),
2290 "Object header size does not match");
2291 // Memcpy can tear for words since it may do byte copy. It is only safe to do this since the
2292 // object in the from space is immutable other than the lock word. b/31423258
2293 memcpy(reinterpret_cast<uint8_t*>(to_ref) + kObjectHeaderSize,
2294 reinterpret_cast<const uint8_t*>(from_ref) + kObjectHeaderSize,
2295 obj_size - kObjectHeaderSize);
2296
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002297 // Attempt to install the forward pointer. This is in a loop as the
2298 // lock word atomic write can fail.
2299 while (true) {
Mathieu Chartierd818adb2016-09-15 13:12:47 -07002300 LockWord old_lock_word = from_ref->GetLockWord(false);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002301
2302 if (old_lock_word.GetState() == LockWord::kForwardingAddress) {
2303 // Lost the race. Another thread (either GC or mutator) stored
2304 // the forwarding pointer first. Make the lost copy (to_ref)
2305 // look like a valid but dead (dummy) object and keep it for
2306 // future reuse.
2307 FillWithDummyObject(to_ref, bytes_allocated);
2308 if (!fall_back_to_non_moving) {
2309 DCHECK(region_space_->IsInToSpace(to_ref));
2310 if (bytes_allocated > space::RegionSpace::kRegionSize) {
2311 // Free the large alloc.
2312 region_space_->FreeLarge(to_ref, bytes_allocated);
2313 } else {
2314 // Record the lost copy for later reuse.
2315 heap_->num_bytes_allocated_.FetchAndAddSequentiallyConsistent(bytes_allocated);
2316 to_space_bytes_skipped_.FetchAndAddSequentiallyConsistent(bytes_allocated);
2317 to_space_objects_skipped_.FetchAndAddSequentiallyConsistent(1);
2318 MutexLock mu(Thread::Current(), skipped_blocks_lock_);
2319 skipped_blocks_map_.insert(std::make_pair(bytes_allocated,
2320 reinterpret_cast<uint8_t*>(to_ref)));
2321 }
2322 } else {
2323 DCHECK(heap_->non_moving_space_->HasAddress(to_ref));
2324 DCHECK_EQ(bytes_allocated, non_moving_space_bytes_allocated);
2325 // Free the non-moving-space chunk.
2326 accounting::ContinuousSpaceBitmap* mark_bitmap =
2327 heap_mark_bitmap_->GetContinuousSpaceBitmap(to_ref);
2328 CHECK(mark_bitmap != nullptr);
2329 CHECK(mark_bitmap->Clear(to_ref));
2330 heap_->non_moving_space_->Free(Thread::Current(), to_ref);
2331 }
2332
2333 // Get the winner's forward ptr.
2334 mirror::Object* lost_fwd_ptr = to_ref;
2335 to_ref = reinterpret_cast<mirror::Object*>(old_lock_word.ForwardingAddress());
2336 CHECK(to_ref != nullptr);
2337 CHECK_NE(to_ref, lost_fwd_ptr);
Mathieu Chartierdfcd6f42016-09-13 10:02:48 -07002338 CHECK(region_space_->IsInToSpace(to_ref) || heap_->non_moving_space_->HasAddress(to_ref))
2339 << "to_ref=" << to_ref << " " << heap_->DumpSpaces();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002340 CHECK_NE(to_ref->GetLockWord(false).GetState(), LockWord::kForwardingAddress);
2341 return to_ref;
2342 }
2343
Mathieu Chartierd818adb2016-09-15 13:12:47 -07002344 // Copy the old lock word over since we did not copy it yet.
2345 to_ref->SetLockWord(old_lock_word, false);
Hiroshi Yamauchi60f63f52015-04-23 16:12:40 -07002346 // Set the gray ptr.
2347 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002348 to_ref->SetReadBarrierState(ReadBarrier::GrayState());
Hiroshi Yamauchi60f63f52015-04-23 16:12:40 -07002349 }
2350
Mathieu Chartiera8131262016-11-29 17:55:19 -08002351 // Do a fence to prevent the field CAS in ConcurrentCopying::Process from possibly reordering
2352 // before the object copy.
2353 QuasiAtomic::ThreadFenceRelease();
2354
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002355 LockWord new_lock_word = LockWord::FromForwardingAddress(reinterpret_cast<size_t>(to_ref));
2356
2357 // Try to atomically write the fwd ptr.
Mathieu Chartiera8131262016-11-29 17:55:19 -08002358 bool success = from_ref->CasLockWordWeakRelaxed(old_lock_word, new_lock_word);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002359 if (LIKELY(success)) {
2360 // The CAS succeeded.
Mathieu Chartiera8131262016-11-29 17:55:19 -08002361 objects_moved_.FetchAndAddRelaxed(1);
2362 bytes_moved_.FetchAndAddRelaxed(region_space_alloc_size);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002363 if (LIKELY(!fall_back_to_non_moving)) {
2364 DCHECK(region_space_->IsInToSpace(to_ref));
2365 } else {
2366 DCHECK(heap_->non_moving_space_->HasAddress(to_ref));
2367 DCHECK_EQ(bytes_allocated, non_moving_space_bytes_allocated);
2368 }
2369 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002370 DCHECK(to_ref->GetReadBarrierState() == ReadBarrier::GrayState());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002371 }
2372 DCHECK(GetFwdPtr(from_ref) == to_ref);
2373 CHECK_NE(to_ref->GetLockWord(false).GetState(), LockWord::kForwardingAddress);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002374 PushOntoMarkStack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002375 return to_ref;
2376 } else {
2377 // The CAS failed. It may have lost the race or may have failed
2378 // due to monitor/hashcode ops. Either way, retry.
2379 }
2380 }
2381}
2382
2383mirror::Object* ConcurrentCopying::IsMarked(mirror::Object* from_ref) {
2384 DCHECK(from_ref != nullptr);
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08002385 space::RegionSpace::RegionType rtype = region_space_->GetRegionType(from_ref);
2386 if (rtype == space::RegionSpace::RegionType::kRegionTypeToSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002387 // It's already marked.
2388 return from_ref;
2389 }
2390 mirror::Object* to_ref;
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08002391 if (rtype == space::RegionSpace::RegionType::kRegionTypeFromSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002392 to_ref = GetFwdPtr(from_ref);
2393 DCHECK(to_ref == nullptr || region_space_->IsInToSpace(to_ref) ||
2394 heap_->non_moving_space_->HasAddress(to_ref))
2395 << "from_ref=" << from_ref << " to_ref=" << to_ref;
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08002396 } else if (rtype == space::RegionSpace::RegionType::kRegionTypeUnevacFromSpace) {
Mathieu Chartierc381c362016-08-23 13:27:53 -07002397 if (IsMarkedInUnevacFromSpace(from_ref)) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002398 to_ref = from_ref;
2399 } else {
2400 to_ref = nullptr;
2401 }
2402 } else {
2403 // from_ref is in a non-moving space.
Mathieu Chartier763a31e2015-11-16 16:05:55 -08002404 if (immune_spaces_.ContainsObject(from_ref)) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002405 // An immune object is alive.
2406 to_ref = from_ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002407 } else {
2408 // Non-immune non-moving space. Use the mark bitmap.
2409 accounting::ContinuousSpaceBitmap* mark_bitmap =
2410 heap_mark_bitmap_->GetContinuousSpaceBitmap(from_ref);
2411 accounting::LargeObjectBitmap* los_bitmap =
2412 heap_mark_bitmap_->GetLargeObjectBitmap(from_ref);
2413 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
2414 bool is_los = mark_bitmap == nullptr;
2415 if (!is_los && mark_bitmap->Test(from_ref)) {
2416 // Already marked.
2417 to_ref = from_ref;
2418 } else if (is_los && los_bitmap->Test(from_ref)) {
2419 // Already marked in LOS.
2420 to_ref = from_ref;
2421 } else {
2422 // Not marked.
2423 if (IsOnAllocStack(from_ref)) {
2424 // If on the allocation stack, it's considered marked.
2425 to_ref = from_ref;
2426 } else {
2427 // Not marked.
2428 to_ref = nullptr;
2429 }
2430 }
2431 }
2432 }
2433 return to_ref;
2434}
2435
2436bool ConcurrentCopying::IsOnAllocStack(mirror::Object* ref) {
2437 QuasiAtomic::ThreadFenceAcquire();
2438 accounting::ObjectStack* alloc_stack = GetAllocationStack();
Mathieu Chartiercb535da2015-01-23 13:50:03 -08002439 return alloc_stack->Contains(ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002440}
2441
Mathieu Chartier1ca68902017-04-18 11:26:22 -07002442mirror::Object* ConcurrentCopying::MarkNonMoving(mirror::Object* ref,
2443 mirror::Object* holder,
2444 MemberOffset offset) {
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002445 // ref is in a non-moving space (from_ref == to_ref).
2446 DCHECK(!region_space_->HasAddress(ref)) << ref;
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002447 DCHECK(!immune_spaces_.ContainsObject(ref));
2448 // Use the mark bitmap.
2449 accounting::ContinuousSpaceBitmap* mark_bitmap =
2450 heap_mark_bitmap_->GetContinuousSpaceBitmap(ref);
2451 accounting::LargeObjectBitmap* los_bitmap =
2452 heap_mark_bitmap_->GetLargeObjectBitmap(ref);
2453 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
2454 bool is_los = mark_bitmap == nullptr;
2455 if (!is_los && mark_bitmap->Test(ref)) {
2456 // Already marked.
2457 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002458 DCHECK(ref->GetReadBarrierState() == ReadBarrier::GrayState() ||
2459 ref->GetReadBarrierState() == ReadBarrier::WhiteState());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002460 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002461 } else if (is_los && los_bitmap->Test(ref)) {
2462 // Already marked in LOS.
2463 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002464 DCHECK(ref->GetReadBarrierState() == ReadBarrier::GrayState() ||
2465 ref->GetReadBarrierState() == ReadBarrier::WhiteState());
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002466 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002467 } else {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002468 // Not marked.
2469 if (IsOnAllocStack(ref)) {
2470 // If it's on the allocation stack, it's considered marked. Keep it white.
2471 // Objects on the allocation stack need not be marked.
2472 if (!is_los) {
2473 DCHECK(!mark_bitmap->Test(ref));
2474 } else {
2475 DCHECK(!los_bitmap->Test(ref));
Nicolas Geoffrayddeb1722016-06-28 08:25:59 +00002476 }
Nicolas Geoffrayddeb1722016-06-28 08:25:59 +00002477 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002478 DCHECK_EQ(ref->GetReadBarrierState(), ReadBarrier::WhiteState());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002479 }
2480 } else {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002481 // For the baker-style RB, we need to handle 'false-gray' cases. See the
2482 // kRegionTypeUnevacFromSpace-case comment in Mark().
2483 if (kUseBakerReadBarrier) {
2484 // Test the bitmap first to reduce the chance of false gray cases.
2485 if ((!is_los && mark_bitmap->Test(ref)) ||
2486 (is_los && los_bitmap->Test(ref))) {
2487 return ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002488 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002489 }
Mathieu Chartier1ca68902017-04-18 11:26:22 -07002490 if (is_los && !IsAligned<kPageSize>(ref)) {
2491 // Ref is a large object that is not aligned, it must be heap corruption. Dump data before
2492 // AtomicSetReadBarrierState since it will fault if the address is not valid.
Mathieu Chartieref496d92017-04-28 18:58:59 -07002493 heap_->GetVerification()->LogHeapCorruption(holder, offset, ref, /* fatal */ true);
Mathieu Chartier1ca68902017-04-18 11:26:22 -07002494 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002495 // Not marked or on the allocation stack. Try to mark it.
2496 // This may or may not succeed, which is ok.
2497 bool cas_success = false;
2498 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002499 cas_success = ref->AtomicSetReadBarrierState(ReadBarrier::WhiteState(),
2500 ReadBarrier::GrayState());
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002501 }
2502 if (!is_los && mark_bitmap->AtomicTestAndSet(ref)) {
2503 // Already marked.
2504 if (kUseBakerReadBarrier && cas_success &&
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002505 ref->GetReadBarrierState() == ReadBarrier::GrayState()) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002506 PushOntoFalseGrayStack(ref);
2507 }
2508 } else if (is_los && los_bitmap->AtomicTestAndSet(ref)) {
2509 // Already marked in LOS.
2510 if (kUseBakerReadBarrier && cas_success &&
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002511 ref->GetReadBarrierState() == ReadBarrier::GrayState()) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002512 PushOntoFalseGrayStack(ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002513 }
2514 } else {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002515 // Newly marked.
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08002516 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002517 DCHECK_EQ(ref->GetReadBarrierState(), ReadBarrier::GrayState());
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08002518 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002519 PushOntoMarkStack(ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002520 }
2521 }
2522 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002523 return ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002524}
2525
2526void ConcurrentCopying::FinishPhase() {
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -08002527 Thread* const self = Thread::Current();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002528 {
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -08002529 MutexLock mu(self, mark_stack_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002530 CHECK_EQ(pooled_mark_stacks_.size(), kMarkStackPoolSize);
2531 }
Mathieu Chartiera1467d02017-02-22 09:22:50 -08002532 // kVerifyNoMissingCardMarks relies on the region space cards not being cleared to avoid false
2533 // positives.
2534 if (!kVerifyNoMissingCardMarks) {
Mathieu Chartier6e6078a2016-10-24 15:45:41 -07002535 TimingLogger::ScopedTiming split("ClearRegionSpaceCards", GetTimings());
2536 // We do not currently use the region space cards at all, madvise them away to save ram.
2537 heap_->GetCardTable()->ClearCardRange(region_space_->Begin(), region_space_->Limit());
Mathieu Chartier6e6078a2016-10-24 15:45:41 -07002538 }
2539 {
2540 MutexLock mu(self, skipped_blocks_lock_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002541 skipped_blocks_map_.clear();
2542 }
Mathieu Chartier56fe2582016-07-14 13:30:03 -07002543 {
2544 ReaderMutexLock mu(self, *Locks::mutator_lock_);
Mathieu Chartier21328a12016-07-22 10:47:45 -07002545 {
2546 WriterMutexLock mu2(self, *Locks::heap_bitmap_lock_);
2547 heap_->ClearMarkedObjects();
2548 }
2549 if (kUseBakerReadBarrier && kFilterModUnionCards) {
2550 TimingLogger::ScopedTiming split("FilterModUnionCards", GetTimings());
2551 ReaderMutexLock mu2(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier21328a12016-07-22 10:47:45 -07002552 for (space::ContinuousSpace* space : immune_spaces_.GetSpaces()) {
2553 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
Mathieu Chartier6e6078a2016-10-24 15:45:41 -07002554 accounting::ModUnionTable* table = heap_->FindModUnionTableFromSpace(space);
Mathieu Chartier21328a12016-07-22 10:47:45 -07002555 // Filter out cards that don't need to be set.
2556 if (table != nullptr) {
2557 table->FilterCards();
2558 }
2559 }
2560 }
Mathieu Chartier36a270a2016-07-28 18:08:51 -07002561 if (kUseBakerReadBarrier) {
2562 TimingLogger::ScopedTiming split("EmptyRBMarkBitStack", GetTimings());
Mathieu Chartier6e6078a2016-10-24 15:45:41 -07002563 DCHECK(rb_mark_bit_stack_ != nullptr);
Mathieu Chartier36a270a2016-07-28 18:08:51 -07002564 const auto* limit = rb_mark_bit_stack_->End();
2565 for (StackReference<mirror::Object>* it = rb_mark_bit_stack_->Begin(); it != limit; ++it) {
2566 CHECK(it->AsMirrorPtr()->AtomicSetMarkBit(1, 0));
2567 }
2568 rb_mark_bit_stack_->Reset();
2569 }
Mathieu Chartier56fe2582016-07-14 13:30:03 -07002570 }
2571 if (measure_read_barrier_slow_path_) {
2572 MutexLock mu(self, rb_slow_path_histogram_lock_);
2573 rb_slow_path_time_histogram_.AdjustAndAddValue(rb_slow_path_ns_.LoadRelaxed());
2574 rb_slow_path_count_total_ += rb_slow_path_count_.LoadRelaxed();
2575 rb_slow_path_count_gc_total_ += rb_slow_path_count_gc_.LoadRelaxed();
2576 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002577}
2578
Hiroshi Yamauchi65f5f242016-12-19 11:44:47 -08002579bool ConcurrentCopying::IsNullOrMarkedHeapReference(mirror::HeapReference<mirror::Object>* field,
2580 bool do_atomic_update) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002581 mirror::Object* from_ref = field->AsMirrorPtr();
Hiroshi Yamauchi65f5f242016-12-19 11:44:47 -08002582 if (from_ref == nullptr) {
2583 return true;
2584 }
Mathieu Chartier97509952015-07-13 14:35:43 -07002585 mirror::Object* to_ref = IsMarked(from_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002586 if (to_ref == nullptr) {
2587 return false;
2588 }
2589 if (from_ref != to_ref) {
Hiroshi Yamauchi65f5f242016-12-19 11:44:47 -08002590 if (do_atomic_update) {
2591 do {
2592 if (field->AsMirrorPtr() != from_ref) {
2593 // Concurrently overwritten by a mutator.
2594 break;
2595 }
2596 } while (!field->CasWeakRelaxed(from_ref, to_ref));
2597 } else {
2598 QuasiAtomic::ThreadFenceRelease();
2599 field->Assign(to_ref);
2600 QuasiAtomic::ThreadFenceSequentiallyConsistent();
2601 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002602 }
2603 return true;
2604}
2605
Mathieu Chartier97509952015-07-13 14:35:43 -07002606mirror::Object* ConcurrentCopying::MarkObject(mirror::Object* from_ref) {
2607 return Mark(from_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002608}
2609
Mathieu Chartier31e88222016-10-14 18:43:19 -07002610void ConcurrentCopying::DelayReferenceReferent(ObjPtr<mirror::Class> klass,
2611 ObjPtr<mirror::Reference> reference) {
Mathieu Chartier97509952015-07-13 14:35:43 -07002612 heap_->GetReferenceProcessor()->DelayReferenceReferent(klass, reference, this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002613}
2614
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002615void ConcurrentCopying::ProcessReferences(Thread* self) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002616 TimingLogger::ScopedTiming split("ProcessReferences", GetTimings());
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002617 // 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 -08002618 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
2619 GetHeap()->GetReferenceProcessor()->ProcessReferences(
Mathieu Chartier97509952015-07-13 14:35:43 -07002620 true /*concurrent*/, GetTimings(), GetCurrentIteration()->GetClearSoftReferences(), this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002621}
2622
2623void ConcurrentCopying::RevokeAllThreadLocalBuffers() {
2624 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
2625 region_space_->RevokeAllThreadLocalBuffers();
2626}
2627
Mathieu Chartier56fe2582016-07-14 13:30:03 -07002628mirror::Object* ConcurrentCopying::MarkFromReadBarrierWithMeasurements(mirror::Object* from_ref) {
2629 if (Thread::Current() != thread_running_gc_) {
2630 rb_slow_path_count_.FetchAndAddRelaxed(1u);
2631 } else {
2632 rb_slow_path_count_gc_.FetchAndAddRelaxed(1u);
2633 }
2634 ScopedTrace tr(__FUNCTION__);
2635 const uint64_t start_time = measure_read_barrier_slow_path_ ? NanoTime() : 0u;
2636 mirror::Object* ret = Mark(from_ref);
2637 if (measure_read_barrier_slow_path_) {
2638 rb_slow_path_ns_.FetchAndAddRelaxed(NanoTime() - start_time);
2639 }
2640 return ret;
2641}
2642
2643void ConcurrentCopying::DumpPerformanceInfo(std::ostream& os) {
2644 GarbageCollector::DumpPerformanceInfo(os);
2645 MutexLock mu(Thread::Current(), rb_slow_path_histogram_lock_);
2646 if (rb_slow_path_time_histogram_.SampleSize() > 0) {
2647 Histogram<uint64_t>::CumulativeData cumulative_data;
2648 rb_slow_path_time_histogram_.CreateHistogram(&cumulative_data);
2649 rb_slow_path_time_histogram_.PrintConfidenceIntervals(os, 0.99, cumulative_data);
2650 }
2651 if (rb_slow_path_count_total_ > 0) {
2652 os << "Slow path count " << rb_slow_path_count_total_ << "\n";
2653 }
2654 if (rb_slow_path_count_gc_total_ > 0) {
2655 os << "GC slow path count " << rb_slow_path_count_gc_total_ << "\n";
2656 }
Mathieu Chartiercca44a02016-08-17 10:07:29 -07002657 os << "Cumulative bytes moved " << cumulative_bytes_moved_.LoadRelaxed() << "\n";
2658 os << "Cumulative objects moved " << cumulative_objects_moved_.LoadRelaxed() << "\n";
Mathieu Chartier56fe2582016-07-14 13:30:03 -07002659}
2660
Hiroshi Yamauchid5307ec2014-03-27 21:07:51 -07002661} // namespace collector
2662} // namespace gc
2663} // namespace art