blob: 6b6f3c3482640123817d9a7edbd2453d7b1f8e1a [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 }
166 FlipThreadRoots();
167 {
168 ReaderMutexLock mu(self, *Locks::mutator_lock_);
169 MarkingPhase();
170 }
171 // Verify no from space refs. This causes a pause.
Andreas Gampee3ce7872017-02-22 13:36:21 -0800172 if (kEnableNoFromSpaceRefsVerification) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800173 TimingLogger::ScopedTiming split("(Paused)VerifyNoFromSpaceReferences", GetTimings());
Andreas Gampe4934eb12017-01-30 13:15:26 -0800174 ScopedPause pause(this, false);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700175 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800176 if (kVerboseMode) {
177 LOG(INFO) << "Verifying no from-space refs";
178 }
179 VerifyNoFromSpaceReferences();
Mathieu Chartier720e71a2015-04-06 17:10:58 -0700180 if (kVerboseMode) {
181 LOG(INFO) << "Done verifying no from-space refs";
182 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700183 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800184 }
185 {
186 ReaderMutexLock mu(self, *Locks::mutator_lock_);
187 ReclaimPhase();
188 }
189 FinishPhase();
190 CHECK(is_active_);
191 is_active_ = false;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700192 thread_running_gc_ = nullptr;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800193}
194
195void ConcurrentCopying::BindBitmaps() {
196 Thread* self = Thread::Current();
197 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
198 // Mark all of the spaces we never collect as immune.
199 for (const auto& space : heap_->GetContinuousSpaces()) {
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800200 if (space->GetGcRetentionPolicy() == space::kGcRetentionPolicyNeverCollect ||
201 space->GetGcRetentionPolicy() == space::kGcRetentionPolicyFullCollect) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800202 CHECK(space->IsZygoteSpace() || space->IsImageSpace());
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800203 immune_spaces_.AddSpace(space);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800204 } else if (space == region_space_) {
Mathieu Chartier7ec38dc2016-10-07 15:24:46 -0700205 // It is OK to clear the bitmap with mutators running since the only place it is read is
206 // VisitObjects which has exclusion with CC.
207 region_space_bitmap_ = region_space_->GetMarkBitmap();
208 region_space_bitmap_->Clear();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800209 }
210 }
211}
212
213void ConcurrentCopying::InitializePhase() {
214 TimingLogger::ScopedTiming split("InitializePhase", GetTimings());
215 if (kVerboseMode) {
216 LOG(INFO) << "GC InitializePhase";
217 LOG(INFO) << "Region-space : " << reinterpret_cast<void*>(region_space_->Begin()) << "-"
218 << reinterpret_cast<void*>(region_space_->Limit());
219 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700220 CheckEmptyMarkStack();
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800221 if (kIsDebugBuild) {
222 MutexLock mu(Thread::Current(), mark_stack_lock_);
223 CHECK(false_gray_stack_.empty());
224 }
Mathieu Chartier56fe2582016-07-14 13:30:03 -0700225
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700226 rb_mark_bit_stack_full_ = false;
Mathieu Chartier56fe2582016-07-14 13:30:03 -0700227 mark_from_read_barrier_measurements_ = measure_read_barrier_slow_path_;
228 if (measure_read_barrier_slow_path_) {
229 rb_slow_path_ns_.StoreRelaxed(0);
230 rb_slow_path_count_.StoreRelaxed(0);
231 rb_slow_path_count_gc_.StoreRelaxed(0);
232 }
233
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800234 immune_spaces_.Reset();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800235 bytes_moved_.StoreRelaxed(0);
236 objects_moved_.StoreRelaxed(0);
Hiroshi Yamauchi60985b72016-08-24 13:53:12 -0700237 GcCause gc_cause = GetCurrentIteration()->GetGcCause();
238 if (gc_cause == kGcCauseExplicit ||
239 gc_cause == kGcCauseForNativeAlloc ||
240 gc_cause == kGcCauseCollectorTransition ||
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800241 GetCurrentIteration()->GetClearSoftReferences()) {
242 force_evacuate_all_ = true;
243 } else {
244 force_evacuate_all_ = false;
245 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700246 if (kUseBakerReadBarrier) {
247 updated_all_immune_objects_.StoreRelaxed(false);
248 // GC may gray immune objects in the thread flip.
249 gc_grays_immune_objects_ = true;
250 if (kIsDebugBuild) {
251 MutexLock mu(Thread::Current(), immune_gray_stack_lock_);
252 DCHECK(immune_gray_stack_.empty());
253 }
254 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800255 BindBitmaps();
256 if (kVerboseMode) {
257 LOG(INFO) << "force_evacuate_all=" << force_evacuate_all_;
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800258 LOG(INFO) << "Largest immune region: " << immune_spaces_.GetLargestImmuneRegion().Begin()
259 << "-" << immune_spaces_.GetLargestImmuneRegion().End();
260 for (space::ContinuousSpace* space : immune_spaces_.GetSpaces()) {
261 LOG(INFO) << "Immune space: " << *space;
262 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800263 LOG(INFO) << "GC end of InitializePhase";
264 }
Mathieu Chartier962cd7a2016-08-16 12:15:59 -0700265 // Mark all of the zygote large objects without graying them.
266 MarkZygoteLargeObjects();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800267}
268
269// Used to switch the thread roots of a thread from from-space refs to to-space refs.
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700270class ConcurrentCopying::ThreadFlipVisitor : public Closure, public RootVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800271 public:
Roland Levillain3887c462015-08-12 18:15:42 +0100272 ThreadFlipVisitor(ConcurrentCopying* concurrent_copying, bool use_tlab)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800273 : concurrent_copying_(concurrent_copying), use_tlab_(use_tlab) {
274 }
275
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700276 virtual void Run(Thread* thread) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800277 // Note: self is not necessarily equal to thread since thread may be suspended.
278 Thread* self = Thread::Current();
279 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
280 << thread->GetState() << " thread " << thread << " self " << self;
Mathieu Chartierfe814e82016-11-09 14:32:49 -0800281 thread->SetIsGcMarkingAndUpdateEntrypoints(true);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800282 if (use_tlab_ && thread->HasTlab()) {
283 if (ConcurrentCopying::kEnableFromSpaceAccountingCheck) {
284 // This must come before the revoke.
285 size_t thread_local_objects = thread->GetThreadLocalObjectsAllocated();
286 concurrent_copying_->region_space_->RevokeThreadLocalBuffers(thread);
287 reinterpret_cast<Atomic<size_t>*>(&concurrent_copying_->from_space_num_objects_at_first_pause_)->
288 FetchAndAddSequentiallyConsistent(thread_local_objects);
289 } else {
290 concurrent_copying_->region_space_->RevokeThreadLocalBuffers(thread);
291 }
292 }
293 if (kUseThreadLocalAllocationStack) {
294 thread->RevokeThreadLocalAllocationStack();
295 }
296 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700297 // We can use the non-CAS VisitRoots functions below because we update thread-local GC roots
298 // only.
299 thread->VisitRoots(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800300 concurrent_copying_->GetBarrier().Pass(self);
301 }
302
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700303 void VisitRoots(mirror::Object*** roots,
304 size_t count,
305 const RootInfo& info ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700306 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700307 for (size_t i = 0; i < count; ++i) {
308 mirror::Object** root = roots[i];
309 mirror::Object* ref = *root;
310 if (ref != nullptr) {
311 mirror::Object* to_ref = concurrent_copying_->Mark(ref);
312 if (to_ref != ref) {
313 *root = to_ref;
314 }
315 }
316 }
317 }
318
319 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots,
320 size_t count,
321 const RootInfo& info ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700322 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700323 for (size_t i = 0; i < count; ++i) {
324 mirror::CompressedReference<mirror::Object>* const root = roots[i];
325 if (!root->IsNull()) {
326 mirror::Object* ref = root->AsMirrorPtr();
327 mirror::Object* to_ref = concurrent_copying_->Mark(ref);
328 if (to_ref != ref) {
329 root->Assign(to_ref);
330 }
331 }
332 }
333 }
334
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800335 private:
336 ConcurrentCopying* const concurrent_copying_;
337 const bool use_tlab_;
338};
339
340// Called back from Runtime::FlipThreadRoots() during a pause.
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700341class ConcurrentCopying::FlipCallback : public Closure {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800342 public:
343 explicit FlipCallback(ConcurrentCopying* concurrent_copying)
344 : concurrent_copying_(concurrent_copying) {
345 }
346
Mathieu Chartier90443472015-07-16 20:32:27 -0700347 virtual void Run(Thread* thread) OVERRIDE REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800348 ConcurrentCopying* cc = concurrent_copying_;
349 TimingLogger::ScopedTiming split("(Paused)FlipCallback", cc->GetTimings());
350 // Note: self is not necessarily equal to thread since thread may be suspended.
351 Thread* self = Thread::Current();
Mathieu Chartiera1467d02017-02-22 09:22:50 -0800352 if (kVerifyNoMissingCardMarks) {
353 cc->VerifyNoMissingCardMarks();
354 }
Mathieu Chartierc83dd7b2017-05-02 04:14:17 +0000355 CHECK(thread == self);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800356 Locks::mutator_lock_->AssertExclusiveHeld(self);
Mathieu Chartierc83dd7b2017-05-02 04:14:17 +0000357 cc->region_space_->SetFromSpace(cc->rb_table_, cc->force_evacuate_all_);
Mathieu Chartiera4f6af92015-08-11 17:35:25 -0700358 cc->SwapStacks();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800359 if (ConcurrentCopying::kEnableFromSpaceAccountingCheck) {
360 cc->RecordLiveStackFreezeSize(self);
361 cc->from_space_num_objects_at_first_pause_ = cc->region_space_->GetObjectsAllocated();
362 cc->from_space_num_bytes_at_first_pause_ = cc->region_space_->GetBytesAllocated();
363 }
364 cc->is_marking_ = true;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700365 cc->mark_stack_mode_.StoreRelaxed(ConcurrentCopying::kMarkStackModeThreadLocal);
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800366 if (kIsDebugBuild) {
367 cc->region_space_->AssertAllRegionLiveBytesZeroOrCleared();
368 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800369 if (UNLIKELY(Runtime::Current()->IsActiveTransaction())) {
Mathieu Chartier184c9dc2015-03-05 13:20:54 -0800370 CHECK(Runtime::Current()->IsAotCompiler());
Mathieu Chartierc83dd7b2017-05-02 04:14:17 +0000371 TimingLogger::ScopedTiming split2("(Paused)VisitTransactionRoots", cc->GetTimings());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700372 Runtime::Current()->VisitTransactionRoots(cc);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800373 }
Mathieu Chartier21328a12016-07-22 10:47:45 -0700374 if (kUseBakerReadBarrier && kGrayDirtyImmuneObjects) {
Mathieu Chartierc83dd7b2017-05-02 04:14:17 +0000375 cc->GrayAllDirtyImmuneObjects();
Mathieu Chartier21328a12016-07-22 10:47:45 -0700376 if (kIsDebugBuild) {
377 // Check that all non-gray immune objects only refernce immune objects.
378 cc->VerifyGrayImmuneObjects();
379 }
380 }
Mathieu Chartier9aef9922017-04-23 13:53:50 -0700381 // May be null during runtime creation, in this case leave java_lang_Object null.
382 // This is safe since single threaded behavior should mean FillDummyObject does not
383 // happen when java_lang_Object_ is null.
384 if (WellKnownClasses::java_lang_Object != nullptr) {
385 cc->java_lang_Object_ = down_cast<mirror::Class*>(cc->Mark(
386 WellKnownClasses::ToClass(WellKnownClasses::java_lang_Object).Ptr()));
387 } else {
388 cc->java_lang_Object_ = nullptr;
389 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800390 }
391
392 private:
393 ConcurrentCopying* const concurrent_copying_;
394};
395
Mathieu Chartier21328a12016-07-22 10:47:45 -0700396class ConcurrentCopying::VerifyGrayImmuneObjectsVisitor {
397 public:
398 explicit VerifyGrayImmuneObjectsVisitor(ConcurrentCopying* collector)
399 : collector_(collector) {}
400
Mathieu Chartier31e88222016-10-14 18:43:19 -0700401 void operator()(ObjPtr<mirror::Object> obj, MemberOffset offset, bool /* is_static */)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700402 const ALWAYS_INLINE REQUIRES_SHARED(Locks::mutator_lock_)
403 REQUIRES_SHARED(Locks::heap_bitmap_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700404 CheckReference(obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(offset),
405 obj, offset);
406 }
407
Mathieu Chartier31e88222016-10-14 18:43:19 -0700408 void operator()(ObjPtr<mirror::Class> klass, ObjPtr<mirror::Reference> ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700409 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700410 CHECK(klass->IsTypeOfReferenceClass());
411 CheckReference(ref->GetReferent<kWithoutReadBarrier>(),
412 ref,
413 mirror::Reference::ReferentOffset());
414 }
415
416 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
417 ALWAYS_INLINE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700418 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700419 if (!root->IsNull()) {
420 VisitRoot(root);
421 }
422 }
423
424 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
425 ALWAYS_INLINE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700426 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700427 CheckReference(root->AsMirrorPtr(), nullptr, MemberOffset(0));
428 }
429
430 private:
431 ConcurrentCopying* const collector_;
432
Mathieu Chartier31e88222016-10-14 18:43:19 -0700433 void CheckReference(ObjPtr<mirror::Object> ref,
434 ObjPtr<mirror::Object> holder,
435 MemberOffset offset) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700436 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700437 if (ref != nullptr) {
Mathieu Chartier31e88222016-10-14 18:43:19 -0700438 if (!collector_->immune_spaces_.ContainsObject(ref.Ptr())) {
Mathieu Chartier962cd7a2016-08-16 12:15:59 -0700439 // Not immune, must be a zygote large object.
440 CHECK(Runtime::Current()->GetHeap()->GetLargeObjectsSpace()->IsZygoteLargeObject(
Mathieu Chartier31e88222016-10-14 18:43:19 -0700441 Thread::Current(), ref.Ptr()))
Mathieu Chartier962cd7a2016-08-16 12:15:59 -0700442 << "Non gray object references non immune, non zygote large object "<< ref << " "
David Sehr709b0702016-10-13 09:12:37 -0700443 << mirror::Object::PrettyTypeOf(ref) << " in holder " << holder << " "
444 << mirror::Object::PrettyTypeOf(holder) << " offset=" << offset.Uint32Value();
Mathieu Chartier962cd7a2016-08-16 12:15:59 -0700445 } else {
446 // Make sure the large object class is immune since we will never scan the large object.
447 CHECK(collector_->immune_spaces_.ContainsObject(
448 ref->GetClass<kVerifyNone, kWithoutReadBarrier>()));
449 }
Mathieu Chartier21328a12016-07-22 10:47:45 -0700450 }
451 }
452};
453
454void ConcurrentCopying::VerifyGrayImmuneObjects() {
455 TimingLogger::ScopedTiming split(__FUNCTION__, GetTimings());
456 for (auto& space : immune_spaces_.GetSpaces()) {
457 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
458 accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
459 VerifyGrayImmuneObjectsVisitor visitor(this);
460 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()),
461 reinterpret_cast<uintptr_t>(space->Limit()),
462 [&visitor](mirror::Object* obj)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700463 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700464 // If an object is not gray, it should only have references to things in the immune spaces.
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700465 if (obj->GetReadBarrierState() != ReadBarrier::GrayState()) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700466 obj->VisitReferences</*kVisitNativeRoots*/true,
467 kDefaultVerifyFlags,
468 kWithoutReadBarrier>(visitor, visitor);
469 }
470 });
471 }
472}
473
Mathieu Chartiera1467d02017-02-22 09:22:50 -0800474class ConcurrentCopying::VerifyNoMissingCardMarkVisitor {
475 public:
476 VerifyNoMissingCardMarkVisitor(ConcurrentCopying* cc, ObjPtr<mirror::Object> holder)
477 : cc_(cc),
478 holder_(holder) {}
479
480 void operator()(ObjPtr<mirror::Object> obj,
481 MemberOffset offset,
482 bool is_static ATTRIBUTE_UNUSED) const
483 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
484 if (offset.Uint32Value() != mirror::Object::ClassOffset().Uint32Value()) {
485 CheckReference(obj->GetFieldObject<mirror::Object, kDefaultVerifyFlags, kWithoutReadBarrier>(
486 offset), offset.Uint32Value());
487 }
488 }
489 void operator()(ObjPtr<mirror::Class> klass,
490 ObjPtr<mirror::Reference> ref) const
491 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
492 CHECK(klass->IsTypeOfReferenceClass());
493 this->operator()(ref, mirror::Reference::ReferentOffset(), false);
494 }
495
496 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
497 REQUIRES_SHARED(Locks::mutator_lock_) {
498 if (!root->IsNull()) {
499 VisitRoot(root);
500 }
501 }
502
503 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
504 REQUIRES_SHARED(Locks::mutator_lock_) {
505 CheckReference(root->AsMirrorPtr());
506 }
507
508 void CheckReference(mirror::Object* ref, int32_t offset = -1) const
509 REQUIRES_SHARED(Locks::mutator_lock_) {
510 CHECK(ref == nullptr || !cc_->region_space_->IsInNewlyAllocatedRegion(ref))
511 << holder_->PrettyTypeOf() << "(" << holder_.Ptr() << ") references object "
512 << ref->PrettyTypeOf() << "(" << ref << ") in newly allocated region at offset=" << offset;
513 }
514
515 private:
516 ConcurrentCopying* const cc_;
517 ObjPtr<mirror::Object> const holder_;
518};
519
520void ConcurrentCopying::VerifyNoMissingCardMarkCallback(mirror::Object* obj, void* arg) {
521 auto* collector = reinterpret_cast<ConcurrentCopying*>(arg);
Mathieu Chartierc83dd7b2017-05-02 04:14:17 +0000522 // Objects not on dirty cards should never have references to newly allocated regions.
523 if (!collector->heap_->GetCardTable()->IsDirty(obj)) {
Mathieu Chartiera1467d02017-02-22 09:22:50 -0800524 VerifyNoMissingCardMarkVisitor visitor(collector, /*holder*/ obj);
525 obj->VisitReferences</*kVisitNativeRoots*/true, kVerifyNone, kWithoutReadBarrier>(
526 visitor,
527 visitor);
528 }
529}
530
531void ConcurrentCopying::VerifyNoMissingCardMarks() {
532 TimingLogger::ScopedTiming split(__FUNCTION__, GetTimings());
533 region_space_->Walk(&VerifyNoMissingCardMarkCallback, this);
534 {
535 ReaderMutexLock rmu(Thread::Current(), *Locks::heap_bitmap_lock_);
536 heap_->GetLiveBitmap()->Walk(&VerifyNoMissingCardMarkCallback, this);
537 }
538}
539
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800540// Switch threads that from from-space to to-space refs. Forward/mark the thread roots.
541void ConcurrentCopying::FlipThreadRoots() {
542 TimingLogger::ScopedTiming split("FlipThreadRoots", GetTimings());
543 if (kVerboseMode) {
544 LOG(INFO) << "time=" << region_space_->Time();
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700545 region_space_->DumpNonFreeRegions(LOG_STREAM(INFO));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800546 }
547 Thread* self = Thread::Current();
548 Locks::mutator_lock_->AssertNotHeld(self);
549 gc_barrier_->Init(self, 0);
550 ThreadFlipVisitor thread_flip_visitor(this, heap_->use_tlab_);
551 FlipCallback flip_callback(this);
Andreas Gampe4934eb12017-01-30 13:15:26 -0800552
553 // This is the point where Concurrent-Copying will pause all threads. We report a pause here, if
554 // necessary. This is slightly over-reporting, as this includes the time to actually suspend
555 // threads.
556 {
557 GcPauseListener* pause_listener = GetHeap()->GetGcPauseListener();
558 if (pause_listener != nullptr) {
559 pause_listener->StartPause();
560 }
561 }
562
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800563 size_t barrier_count = Runtime::Current()->FlipThreadRoots(
564 &thread_flip_visitor, &flip_callback, this);
Andreas Gampe4934eb12017-01-30 13:15:26 -0800565
566 {
567 GcPauseListener* pause_listener = GetHeap()->GetGcPauseListener();
568 if (pause_listener != nullptr) {
569 pause_listener->EndPause();
570 }
571 }
572
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800573 {
574 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
575 gc_barrier_->Increment(self, barrier_count);
576 }
577 is_asserting_to_space_invariant_ = true;
578 QuasiAtomic::ThreadFenceForConstructor();
579 if (kVerboseMode) {
580 LOG(INFO) << "time=" << region_space_->Time();
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700581 region_space_->DumpNonFreeRegions(LOG_STREAM(INFO));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800582 LOG(INFO) << "GC end of FlipThreadRoots";
583 }
584}
585
Mathieu Chartier21328a12016-07-22 10:47:45 -0700586class ConcurrentCopying::GrayImmuneObjectVisitor {
587 public:
Mathieu Chartierc83dd7b2017-05-02 04:14:17 +0000588 explicit GrayImmuneObjectVisitor() {}
Mathieu Chartier21328a12016-07-22 10:47:45 -0700589
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700590 ALWAYS_INLINE void operator()(mirror::Object* obj) const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierc83dd7b2017-05-02 04:14:17 +0000591 if (kUseBakerReadBarrier) {
592 if (kIsDebugBuild) {
593 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartier21328a12016-07-22 10:47:45 -0700594 }
Mathieu Chartierc83dd7b2017-05-02 04:14:17 +0000595 obj->SetReadBarrierState(ReadBarrier::GrayState());
Mathieu Chartier21328a12016-07-22 10:47:45 -0700596 }
597 }
598
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700599 static void Callback(mirror::Object* obj, void* arg) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierc83dd7b2017-05-02 04:14:17 +0000600 reinterpret_cast<GrayImmuneObjectVisitor*>(arg)->operator()(obj);
Mathieu Chartier21328a12016-07-22 10:47:45 -0700601 }
602};
603
604void ConcurrentCopying::GrayAllDirtyImmuneObjects() {
Mathieu Chartierc83dd7b2017-05-02 04:14:17 +0000605 TimingLogger::ScopedTiming split(__FUNCTION__, GetTimings());
606 gc::Heap* const heap = Runtime::Current()->GetHeap();
607 accounting::CardTable* const card_table = heap->GetCardTable();
608 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartier21328a12016-07-22 10:47:45 -0700609 for (space::ContinuousSpace* space : immune_spaces_.GetSpaces()) {
610 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
Mathieu Chartierc83dd7b2017-05-02 04:14:17 +0000611 GrayImmuneObjectVisitor visitor;
612 accounting::ModUnionTable* table = heap->FindModUnionTableFromSpace(space);
Mathieu Chartier21328a12016-07-22 10:47:45 -0700613 // Mark all the objects on dirty cards since these may point to objects in other space.
614 // Once these are marked, the GC will eventually clear them later.
615 // Table is non null for boot image and zygote spaces. It is only null for application image
616 // spaces.
617 if (table != nullptr) {
Mathieu Chartierc83dd7b2017-05-02 04:14:17 +0000618 // TODO: Consider adding precleaning outside the pause.
Mathieu Chartier6e6078a2016-10-24 15:45:41 -0700619 table->ProcessCards();
Mathieu Chartierc83dd7b2017-05-02 04:14:17 +0000620 table->VisitObjects(GrayImmuneObjectVisitor::Callback, &visitor);
621 // Since the cards are recorded in the mod-union table and this is paused, we can clear
622 // the cards for the space (to madvise).
Mathieu Chartier6e6078a2016-10-24 15:45:41 -0700623 TimingLogger::ScopedTiming split2("(Paused)ClearCards", GetTimings());
624 card_table->ClearCardRange(space->Begin(),
625 AlignDown(space->End(), accounting::CardTable::kCardSize));
Mathieu Chartierc83dd7b2017-05-02 04:14:17 +0000626 } else {
627 // TODO: Consider having a mark bitmap for app image spaces and avoid scanning during the
628 // pause because app image spaces are all dirty pages anyways.
629 card_table->Scan<false>(space->GetMarkBitmap(), space->Begin(), space->End(), visitor);
Mathieu Chartier21328a12016-07-22 10:47:45 -0700630 }
631 }
Mathieu Chartierc83dd7b2017-05-02 04:14:17 +0000632 // Since all of the objects that may point to other spaces are marked, we can avoid all the read
Mathieu Chartier21328a12016-07-22 10:47:45 -0700633 // barriers in the immune spaces.
634 updated_all_immune_objects_.StoreRelaxed(true);
635}
636
Mathieu Chartiera4f6af92015-08-11 17:35:25 -0700637void ConcurrentCopying::SwapStacks() {
638 heap_->SwapStacks();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800639}
640
641void ConcurrentCopying::RecordLiveStackFreezeSize(Thread* self) {
642 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
643 live_stack_freeze_size_ = heap_->GetLiveStack()->Size();
644}
645
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700646// Used to visit objects in the immune spaces.
647inline void ConcurrentCopying::ScanImmuneObject(mirror::Object* obj) {
648 DCHECK(obj != nullptr);
649 DCHECK(immune_spaces_.ContainsObject(obj));
650 // Update the fields without graying it or pushing it onto the mark stack.
651 Scan(obj);
652}
653
654class ConcurrentCopying::ImmuneSpaceScanObjVisitor {
655 public:
656 explicit ImmuneSpaceScanObjVisitor(ConcurrentCopying* cc)
657 : collector_(cc) {}
658
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700659 ALWAYS_INLINE void operator()(mirror::Object* obj) const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700660 if (kUseBakerReadBarrier && kGrayDirtyImmuneObjects) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700661 if (obj->GetReadBarrierState() == ReadBarrier::GrayState()) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700662 collector_->ScanImmuneObject(obj);
663 // Done scanning the object, go back to white.
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700664 bool success = obj->AtomicSetReadBarrierState(ReadBarrier::GrayState(),
665 ReadBarrier::WhiteState());
Mathieu Chartier21328a12016-07-22 10:47:45 -0700666 CHECK(success);
667 }
668 } else {
669 collector_->ScanImmuneObject(obj);
670 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700671 }
672
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700673 static void Callback(mirror::Object* obj, void* arg) REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi5408f232016-07-29 15:07:05 -0700674 reinterpret_cast<ImmuneSpaceScanObjVisitor*>(arg)->operator()(obj);
675 }
676
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700677 private:
678 ConcurrentCopying* const collector_;
679};
680
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800681// Concurrently mark roots that are guarded by read barriers and process the mark stack.
682void ConcurrentCopying::MarkingPhase() {
683 TimingLogger::ScopedTiming split("MarkingPhase", GetTimings());
684 if (kVerboseMode) {
685 LOG(INFO) << "GC MarkingPhase";
686 }
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -0700687 Thread* self = Thread::Current();
688 if (kIsDebugBuild) {
689 MutexLock mu(self, *Locks::thread_list_lock_);
690 CHECK(weak_ref_access_enabled_);
691 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700692
693 // Scan immune spaces.
694 // Update all the fields in the immune spaces first without graying the objects so that we
695 // minimize dirty pages in the immune spaces. Note mutators can concurrently access and gray some
696 // of the objects.
697 if (kUseBakerReadBarrier) {
698 gc_grays_immune_objects_ = false;
Hiroshi Yamauchi16292fc2016-06-20 20:23:34 -0700699 }
Mathieu Chartier21328a12016-07-22 10:47:45 -0700700 {
701 TimingLogger::ScopedTiming split2("ScanImmuneSpaces", GetTimings());
702 for (auto& space : immune_spaces_.GetSpaces()) {
703 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
704 accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
Hiroshi Yamauchi5408f232016-07-29 15:07:05 -0700705 accounting::ModUnionTable* table = heap_->FindModUnionTableFromSpace(space);
Mathieu Chartier21328a12016-07-22 10:47:45 -0700706 ImmuneSpaceScanObjVisitor visitor(this);
Hiroshi Yamauchi5408f232016-07-29 15:07:05 -0700707 if (kUseBakerReadBarrier && kGrayDirtyImmuneObjects && table != nullptr) {
708 table->VisitObjects(ImmuneSpaceScanObjVisitor::Callback, &visitor);
709 } else {
710 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()),
711 reinterpret_cast<uintptr_t>(space->Limit()),
712 visitor);
713 }
Mathieu Chartier21328a12016-07-22 10:47:45 -0700714 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700715 }
716 if (kUseBakerReadBarrier) {
717 // This release fence makes the field updates in the above loop visible before allowing mutator
718 // getting access to immune objects without graying it first.
719 updated_all_immune_objects_.StoreRelease(true);
720 // Now whiten immune objects concurrently accessed and grayed by mutators. We can't do this in
721 // the above loop because we would incorrectly disable the read barrier by whitening an object
722 // which may point to an unscanned, white object, breaking the to-space invariant.
723 //
724 // Make sure no mutators are in the middle of marking an immune object before whitening immune
725 // objects.
726 IssueEmptyCheckpoint();
727 MutexLock mu(Thread::Current(), immune_gray_stack_lock_);
728 if (kVerboseMode) {
729 LOG(INFO) << "immune gray stack size=" << immune_gray_stack_.size();
730 }
731 for (mirror::Object* obj : immune_gray_stack_) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700732 DCHECK(obj->GetReadBarrierState() == ReadBarrier::GrayState());
733 bool success = obj->AtomicSetReadBarrierState(ReadBarrier::GrayState(),
734 ReadBarrier::WhiteState());
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700735 DCHECK(success);
736 }
737 immune_gray_stack_.clear();
738 }
739
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800740 {
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -0700741 TimingLogger::ScopedTiming split2("VisitConcurrentRoots", GetTimings());
742 Runtime::Current()->VisitConcurrentRoots(this, kVisitRootFlagAllRoots);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800743 }
744 {
745 // TODO: don't visit the transaction roots if it's not active.
746 TimingLogger::ScopedTiming split5("VisitNonThreadRoots", GetTimings());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700747 Runtime::Current()->VisitNonThreadRoots(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800748 }
749
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800750 {
Mathieu Chartiera6b1ead2015-10-06 10:32:38 -0700751 TimingLogger::ScopedTiming split7("ProcessMarkStack", GetTimings());
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700752 // We transition through three mark stack modes (thread-local, shared, GC-exclusive). The
753 // primary reasons are the fact that we need to use a checkpoint to process thread-local mark
754 // stacks, but after we disable weak refs accesses, we can't use a checkpoint due to a deadlock
755 // issue because running threads potentially blocking at WaitHoldingLocks, and that once we
756 // reach the point where we process weak references, we can avoid using a lock when accessing
757 // the GC mark stack, which makes mark stack processing more efficient.
758
759 // Process the mark stack once in the thread local stack mode. This marks most of the live
760 // objects, aside from weak ref accesses with read barriers (Reference::GetReferent() and system
761 // weaks) that may happen concurrently while we processing the mark stack and newly mark/gray
762 // objects and push refs on the mark stack.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800763 ProcessMarkStack();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700764 // Switch to the shared mark stack mode. That is, revoke and process thread-local mark stacks
765 // for the last time before transitioning to the shared mark stack mode, which would process new
766 // refs that may have been concurrently pushed onto the mark stack during the ProcessMarkStack()
767 // call above. At the same time, disable weak ref accesses using a per-thread flag. It's
768 // important to do these together in a single checkpoint so that we can ensure that mutators
769 // won't newly gray objects and push new refs onto the mark stack due to weak ref accesses and
770 // mutators safely transition to the shared mark stack mode (without leaving unprocessed refs on
771 // the thread-local mark stacks), without a race. This is why we use a thread-local weak ref
772 // access flag Thread::tls32_.weak_ref_access_enabled_ instead of the global ones.
773 SwitchToSharedMarkStackMode();
774 CHECK(!self->GetWeakRefAccessEnabled());
775 // Now that weak refs accesses are disabled, once we exhaust the shared mark stack again here
776 // (which may be non-empty if there were refs found on thread-local mark stacks during the above
777 // SwitchToSharedMarkStackMode() call), we won't have new refs to process, that is, mutators
778 // (via read barriers) have no way to produce any more refs to process. Marking converges once
779 // before we process weak refs below.
780 ProcessMarkStack();
781 CheckEmptyMarkStack();
782 // Switch to the GC exclusive mark stack mode so that we can process the mark stack without a
783 // lock from this point on.
784 SwitchToGcExclusiveMarkStackMode();
785 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800786 if (kVerboseMode) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800787 LOG(INFO) << "ProcessReferences";
788 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700789 // Process weak references. This may produce new refs to process and have them processed via
Mathieu Chartier97509952015-07-13 14:35:43 -0700790 // ProcessMarkStack (in the GC exclusive mark stack mode).
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700791 ProcessReferences(self);
792 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800793 if (kVerboseMode) {
794 LOG(INFO) << "SweepSystemWeaks";
795 }
796 SweepSystemWeaks(self);
797 if (kVerboseMode) {
798 LOG(INFO) << "SweepSystemWeaks done";
799 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700800 // Process the mark stack here one last time because the above SweepSystemWeaks() call may have
801 // marked some objects (strings alive) as hash_set::Erase() can call the hash function for
802 // arbitrary elements in the weak intern table in InternTable::Table::SweepWeaks().
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800803 ProcessMarkStack();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700804 CheckEmptyMarkStack();
805 // Re-enable weak ref accesses.
806 ReenableWeakRefAccess(self);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -0700807 // Free data for class loaders that we unloaded.
808 Runtime::Current()->GetClassLinker()->CleanupClassLoaders();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700809 // Marking is done. Disable marking.
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700810 DisableMarking();
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800811 if (kUseBakerReadBarrier) {
812 ProcessFalseGrayStack();
813 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700814 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800815 }
816
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -0700817 if (kIsDebugBuild) {
818 MutexLock mu(self, *Locks::thread_list_lock_);
819 CHECK(weak_ref_access_enabled_);
820 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800821 if (kVerboseMode) {
822 LOG(INFO) << "GC end of MarkingPhase";
823 }
824}
825
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700826void ConcurrentCopying::ReenableWeakRefAccess(Thread* self) {
827 if (kVerboseMode) {
828 LOG(INFO) << "ReenableWeakRefAccess";
829 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700830 // Iterate all threads (don't need to or can't use a checkpoint) and re-enable weak ref access.
831 {
832 MutexLock mu(self, *Locks::thread_list_lock_);
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -0700833 weak_ref_access_enabled_ = true; // This is for new threads.
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700834 std::list<Thread*> thread_list = Runtime::Current()->GetThreadList()->GetList();
835 for (Thread* thread : thread_list) {
836 thread->SetWeakRefAccessEnabled(true);
837 }
838 }
839 // Unblock blocking threads.
840 GetHeap()->GetReferenceProcessor()->BroadcastForSlowPath(self);
841 Runtime::Current()->BroadcastForNewSystemWeaks();
842}
843
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700844class ConcurrentCopying::DisableMarkingCheckpoint : public Closure {
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700845 public:
846 explicit DisableMarkingCheckpoint(ConcurrentCopying* concurrent_copying)
847 : concurrent_copying_(concurrent_copying) {
848 }
849
850 void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
851 // Note: self is not necessarily equal to thread since thread may be suspended.
852 Thread* self = Thread::Current();
853 DCHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
854 << thread->GetState() << " thread " << thread << " self " << self;
855 // Disable the thread-local is_gc_marking flag.
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -0700856 // Note a thread that has just started right before this checkpoint may have already this flag
857 // set to false, which is ok.
Mathieu Chartierfe814e82016-11-09 14:32:49 -0800858 thread->SetIsGcMarkingAndUpdateEntrypoints(false);
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700859 // If thread is a running mutator, then act on behalf of the garbage collector.
860 // See the code in ThreadList::RunCheckpoint.
Mathieu Chartier10d25082015-10-28 18:36:09 -0700861 concurrent_copying_->GetBarrier().Pass(self);
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700862 }
863
864 private:
865 ConcurrentCopying* const concurrent_copying_;
866};
867
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -0700868class ConcurrentCopying::DisableMarkingCallback : public Closure {
869 public:
870 explicit DisableMarkingCallback(ConcurrentCopying* concurrent_copying)
871 : concurrent_copying_(concurrent_copying) {
872 }
873
874 void Run(Thread* self ATTRIBUTE_UNUSED) OVERRIDE REQUIRES(Locks::thread_list_lock_) {
875 // This needs to run under the thread_list_lock_ critical section in ThreadList::RunCheckpoint()
876 // to avoid a race with ThreadList::Register().
877 CHECK(concurrent_copying_->is_marking_);
878 concurrent_copying_->is_marking_ = false;
879 }
880
881 private:
882 ConcurrentCopying* const concurrent_copying_;
883};
884
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700885void ConcurrentCopying::IssueDisableMarkingCheckpoint() {
886 Thread* self = Thread::Current();
887 DisableMarkingCheckpoint check_point(this);
888 ThreadList* thread_list = Runtime::Current()->GetThreadList();
889 gc_barrier_->Init(self, 0);
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -0700890 DisableMarkingCallback dmc(this);
891 size_t barrier_count = thread_list->RunCheckpoint(&check_point, &dmc);
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700892 // If there are no threads to wait which implies that all the checkpoint functions are finished,
893 // then no need to release the mutator lock.
894 if (barrier_count == 0) {
895 return;
896 }
897 // Release locks then wait for all mutator threads to pass the barrier.
898 Locks::mutator_lock_->SharedUnlock(self);
899 {
900 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
901 gc_barrier_->Increment(self, barrier_count);
902 }
903 Locks::mutator_lock_->SharedLock(self);
904}
905
906void ConcurrentCopying::DisableMarking() {
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -0700907 // Use a checkpoint to turn off the global is_marking and the thread-local is_gc_marking flags and
908 // to ensure no threads are still in the middle of a read barrier which may have a from-space ref
909 // cached in a local variable.
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700910 IssueDisableMarkingCheckpoint();
911 if (kUseTableLookupReadBarrier) {
912 heap_->rb_table_->ClearAll();
913 DCHECK(heap_->rb_table_->IsAllCleared());
914 }
915 is_mark_stack_push_disallowed_.StoreSequentiallyConsistent(1);
916 mark_stack_mode_.StoreSequentiallyConsistent(kMarkStackModeOff);
917}
918
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800919void ConcurrentCopying::PushOntoFalseGrayStack(mirror::Object* ref) {
920 CHECK(kUseBakerReadBarrier);
921 DCHECK(ref != nullptr);
922 MutexLock mu(Thread::Current(), mark_stack_lock_);
923 false_gray_stack_.push_back(ref);
924}
925
926void ConcurrentCopying::ProcessFalseGrayStack() {
927 CHECK(kUseBakerReadBarrier);
928 // Change the objects on the false gray stack from gray to white.
929 MutexLock mu(Thread::Current(), mark_stack_lock_);
930 for (mirror::Object* obj : false_gray_stack_) {
931 DCHECK(IsMarked(obj));
932 // The object could be white here if a thread got preempted after a success at the
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700933 // AtomicSetReadBarrierState in Mark(), GC started marking through it (but not finished so
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800934 // still gray), and the thread ran to register it onto the false gray stack.
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700935 if (obj->GetReadBarrierState() == ReadBarrier::GrayState()) {
936 bool success = obj->AtomicSetReadBarrierState(ReadBarrier::GrayState(),
937 ReadBarrier::WhiteState());
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800938 DCHECK(success);
939 }
940 }
941 false_gray_stack_.clear();
942}
943
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800944void ConcurrentCopying::IssueEmptyCheckpoint() {
945 Thread* self = Thread::Current();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800946 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800947 // Release locks then wait for all mutator threads to pass the barrier.
948 Locks::mutator_lock_->SharedUnlock(self);
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800949 thread_list->RunEmptyCheckpoint();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800950 Locks::mutator_lock_->SharedLock(self);
951}
952
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -0700953void ConcurrentCopying::ExpandGcMarkStack() {
954 DCHECK(gc_mark_stack_->IsFull());
955 const size_t new_size = gc_mark_stack_->Capacity() * 2;
956 std::vector<StackReference<mirror::Object>> temp(gc_mark_stack_->Begin(),
957 gc_mark_stack_->End());
958 gc_mark_stack_->Resize(new_size);
959 for (auto& ref : temp) {
960 gc_mark_stack_->PushBack(ref.AsMirrorPtr());
961 }
962 DCHECK(!gc_mark_stack_->IsFull());
963}
964
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800965void ConcurrentCopying::PushOntoMarkStack(mirror::Object* to_ref) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700966 CHECK_EQ(is_mark_stack_push_disallowed_.LoadRelaxed(), 0)
David Sehr709b0702016-10-13 09:12:37 -0700967 << " " << to_ref << " " << mirror::Object::PrettyTypeOf(to_ref);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700968 Thread* self = Thread::Current(); // TODO: pass self as an argument from call sites?
969 CHECK(thread_running_gc_ != nullptr);
970 MarkStackMode mark_stack_mode = mark_stack_mode_.LoadRelaxed();
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -0700971 if (LIKELY(mark_stack_mode == kMarkStackModeThreadLocal)) {
972 if (LIKELY(self == thread_running_gc_)) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700973 // If GC-running thread, use the GC mark stack instead of a thread-local mark stack.
974 CHECK(self->GetThreadLocalMarkStack() == nullptr);
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -0700975 if (UNLIKELY(gc_mark_stack_->IsFull())) {
976 ExpandGcMarkStack();
977 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700978 gc_mark_stack_->PushBack(to_ref);
979 } else {
980 // Otherwise, use a thread-local mark stack.
981 accounting::AtomicStack<mirror::Object>* tl_mark_stack = self->GetThreadLocalMarkStack();
982 if (UNLIKELY(tl_mark_stack == nullptr || tl_mark_stack->IsFull())) {
983 MutexLock mu(self, mark_stack_lock_);
984 // Get a new thread local mark stack.
985 accounting::AtomicStack<mirror::Object>* new_tl_mark_stack;
986 if (!pooled_mark_stacks_.empty()) {
987 // Use a pooled mark stack.
988 new_tl_mark_stack = pooled_mark_stacks_.back();
989 pooled_mark_stacks_.pop_back();
990 } else {
991 // None pooled. Create a new one.
992 new_tl_mark_stack =
993 accounting::AtomicStack<mirror::Object>::Create(
994 "thread local mark stack", 4 * KB, 4 * KB);
995 }
996 DCHECK(new_tl_mark_stack != nullptr);
997 DCHECK(new_tl_mark_stack->IsEmpty());
998 new_tl_mark_stack->PushBack(to_ref);
999 self->SetThreadLocalMarkStack(new_tl_mark_stack);
1000 if (tl_mark_stack != nullptr) {
1001 // Store the old full stack into a vector.
1002 revoked_mark_stacks_.push_back(tl_mark_stack);
1003 }
1004 } else {
1005 tl_mark_stack->PushBack(to_ref);
1006 }
1007 }
1008 } else if (mark_stack_mode == kMarkStackModeShared) {
1009 // Access the shared GC mark stack with a lock.
1010 MutexLock mu(self, mark_stack_lock_);
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -07001011 if (UNLIKELY(gc_mark_stack_->IsFull())) {
1012 ExpandGcMarkStack();
1013 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001014 gc_mark_stack_->PushBack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001015 } else {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001016 CHECK_EQ(static_cast<uint32_t>(mark_stack_mode),
Hiroshi Yamauchifa755182015-09-30 20:12:11 -07001017 static_cast<uint32_t>(kMarkStackModeGcExclusive))
1018 << "ref=" << to_ref
1019 << " self->gc_marking=" << self->GetIsGcMarking()
1020 << " cc->is_marking=" << is_marking_;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001021 CHECK(self == thread_running_gc_)
1022 << "Only GC-running thread should access the mark stack "
1023 << "in the GC exclusive mark stack mode";
1024 // Access the GC mark stack without a lock.
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -07001025 if (UNLIKELY(gc_mark_stack_->IsFull())) {
1026 ExpandGcMarkStack();
1027 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001028 gc_mark_stack_->PushBack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001029 }
1030}
1031
1032accounting::ObjectStack* ConcurrentCopying::GetAllocationStack() {
1033 return heap_->allocation_stack_.get();
1034}
1035
1036accounting::ObjectStack* ConcurrentCopying::GetLiveStack() {
1037 return heap_->live_stack_.get();
1038}
1039
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001040// The following visitors are used to verify that there's no references to the from-space left after
1041// marking.
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001042class ConcurrentCopying::VerifyNoFromSpaceRefsVisitor : public SingleRootVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001043 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001044 explicit VerifyNoFromSpaceRefsVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001045 : collector_(collector) {}
1046
Mathieu Chartierbc632f02017-04-20 13:31:39 -07001047 void operator()(mirror::Object* ref,
1048 MemberOffset offset = MemberOffset(0),
1049 mirror::Object* holder = nullptr) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001050 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001051 if (ref == nullptr) {
1052 // OK.
1053 return;
1054 }
Mathieu Chartierbc632f02017-04-20 13:31:39 -07001055 collector_->AssertToSpaceInvariant(holder, offset, ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001056 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001057 CHECK_EQ(ref->GetReadBarrierState(), ReadBarrier::WhiteState())
David Sehr709b0702016-10-13 09:12:37 -07001058 << "Ref " << ref << " " << ref->PrettyTypeOf()
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001059 << " has non-white rb_state ";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001060 }
1061 }
1062
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001063 void VisitRoot(mirror::Object* root, const RootInfo& info ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001064 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001065 DCHECK(root != nullptr);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001066 operator()(root);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001067 }
1068
1069 private:
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001070 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001071};
1072
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001073class ConcurrentCopying::VerifyNoFromSpaceRefsFieldVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001074 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001075 explicit VerifyNoFromSpaceRefsFieldVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001076 : collector_(collector) {}
1077
Mathieu Chartier31e88222016-10-14 18:43:19 -07001078 void operator()(ObjPtr<mirror::Object> obj,
1079 MemberOffset offset,
1080 bool is_static ATTRIBUTE_UNUSED) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001081 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001082 mirror::Object* ref =
1083 obj->GetFieldObject<mirror::Object, kDefaultVerifyFlags, kWithoutReadBarrier>(offset);
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001084 VerifyNoFromSpaceRefsVisitor visitor(collector_);
Mathieu Chartierbc632f02017-04-20 13:31:39 -07001085 visitor(ref, offset, obj.Ptr());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001086 }
Mathieu Chartier31e88222016-10-14 18:43:19 -07001087 void operator()(ObjPtr<mirror::Class> klass,
1088 ObjPtr<mirror::Reference> ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001089 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001090 CHECK(klass->IsTypeOfReferenceClass());
1091 this->operator()(ref, mirror::Reference::ReferentOffset(), false);
1092 }
1093
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001094 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001095 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001096 if (!root->IsNull()) {
1097 VisitRoot(root);
1098 }
1099 }
1100
1101 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001102 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001103 VerifyNoFromSpaceRefsVisitor visitor(collector_);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001104 visitor(root->AsMirrorPtr());
1105 }
1106
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001107 private:
Mathieu Chartier97509952015-07-13 14:35:43 -07001108 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001109};
1110
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001111class ConcurrentCopying::VerifyNoFromSpaceRefsObjectVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001112 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001113 explicit VerifyNoFromSpaceRefsObjectVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001114 : collector_(collector) {}
1115 void operator()(mirror::Object* obj) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001116 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001117 ObjectCallback(obj, collector_);
1118 }
1119 static void ObjectCallback(mirror::Object* obj, void *arg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001120 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001121 CHECK(obj != nullptr);
1122 ConcurrentCopying* collector = reinterpret_cast<ConcurrentCopying*>(arg);
1123 space::RegionSpace* region_space = collector->RegionSpace();
1124 CHECK(!region_space->IsInFromSpace(obj)) << "Scanning object " << obj << " in from space";
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001125 VerifyNoFromSpaceRefsFieldVisitor visitor(collector);
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07001126 obj->VisitReferences</*kVisitNativeRoots*/true, kDefaultVerifyFlags, kWithoutReadBarrier>(
1127 visitor,
1128 visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001129 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001130 CHECK_EQ(obj->GetReadBarrierState(), ReadBarrier::WhiteState())
1131 << "obj=" << obj << " non-white rb_state " << obj->GetReadBarrierState();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001132 }
1133 }
1134
1135 private:
1136 ConcurrentCopying* const collector_;
1137};
1138
1139// Verify there's no from-space references left after the marking phase.
1140void ConcurrentCopying::VerifyNoFromSpaceReferences() {
1141 Thread* self = Thread::Current();
1142 DCHECK(Locks::mutator_lock_->IsExclusiveHeld(self));
Hiroshi Yamauchi00370822015-08-18 14:47:25 -07001143 // Verify all threads have is_gc_marking to be false
1144 {
1145 MutexLock mu(self, *Locks::thread_list_lock_);
1146 std::list<Thread*> thread_list = Runtime::Current()->GetThreadList()->GetList();
1147 for (Thread* thread : thread_list) {
1148 CHECK(!thread->GetIsGcMarking());
1149 }
1150 }
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001151 VerifyNoFromSpaceRefsObjectVisitor visitor(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001152 // Roots.
1153 {
1154 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001155 VerifyNoFromSpaceRefsVisitor ref_visitor(this);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001156 Runtime::Current()->VisitRoots(&ref_visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001157 }
1158 // The to-space.
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001159 region_space_->WalkToSpace(VerifyNoFromSpaceRefsObjectVisitor::ObjectCallback, this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001160 // Non-moving spaces.
1161 {
1162 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1163 heap_->GetMarkBitmap()->Visit(visitor);
1164 }
1165 // The alloc stack.
1166 {
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001167 VerifyNoFromSpaceRefsVisitor ref_visitor(this);
Mathieu Chartiercb535da2015-01-23 13:50:03 -08001168 for (auto* it = heap_->allocation_stack_->Begin(), *end = heap_->allocation_stack_->End();
1169 it < end; ++it) {
1170 mirror::Object* const obj = it->AsMirrorPtr();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001171 if (obj != nullptr && obj->GetClass() != nullptr) {
1172 // TODO: need to call this only if obj is alive?
1173 ref_visitor(obj);
1174 visitor(obj);
1175 }
1176 }
1177 }
1178 // TODO: LOS. But only refs in LOS are classes.
1179}
1180
1181// The following visitors are used to assert the to-space invariant.
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001182class ConcurrentCopying::AssertToSpaceInvariantRefsVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001183 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001184 explicit AssertToSpaceInvariantRefsVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001185 : collector_(collector) {}
1186
1187 void operator()(mirror::Object* ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001188 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001189 if (ref == nullptr) {
1190 // OK.
1191 return;
1192 }
1193 collector_->AssertToSpaceInvariant(nullptr, MemberOffset(0), ref);
1194 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001195
1196 private:
Mathieu Chartier97509952015-07-13 14:35:43 -07001197 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001198};
1199
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001200class ConcurrentCopying::AssertToSpaceInvariantFieldVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001201 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001202 explicit AssertToSpaceInvariantFieldVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001203 : collector_(collector) {}
1204
Mathieu Chartier31e88222016-10-14 18:43:19 -07001205 void operator()(ObjPtr<mirror::Object> obj,
1206 MemberOffset offset,
1207 bool is_static ATTRIBUTE_UNUSED) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001208 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001209 mirror::Object* ref =
1210 obj->GetFieldObject<mirror::Object, kDefaultVerifyFlags, kWithoutReadBarrier>(offset);
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001211 AssertToSpaceInvariantRefsVisitor visitor(collector_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001212 visitor(ref);
1213 }
Mathieu Chartier31e88222016-10-14 18:43:19 -07001214 void operator()(ObjPtr<mirror::Class> klass, ObjPtr<mirror::Reference> ref ATTRIBUTE_UNUSED) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001215 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001216 CHECK(klass->IsTypeOfReferenceClass());
1217 }
1218
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001219 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001220 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001221 if (!root->IsNull()) {
1222 VisitRoot(root);
1223 }
1224 }
1225
1226 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001227 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001228 AssertToSpaceInvariantRefsVisitor visitor(collector_);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001229 visitor(root->AsMirrorPtr());
1230 }
1231
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001232 private:
Mathieu Chartier97509952015-07-13 14:35:43 -07001233 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001234};
1235
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001236class ConcurrentCopying::AssertToSpaceInvariantObjectVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001237 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001238 explicit AssertToSpaceInvariantObjectVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001239 : collector_(collector) {}
1240 void operator()(mirror::Object* obj) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001241 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001242 ObjectCallback(obj, collector_);
1243 }
1244 static void ObjectCallback(mirror::Object* obj, void *arg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001245 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001246 CHECK(obj != nullptr);
1247 ConcurrentCopying* collector = reinterpret_cast<ConcurrentCopying*>(arg);
1248 space::RegionSpace* region_space = collector->RegionSpace();
1249 CHECK(!region_space->IsInFromSpace(obj)) << "Scanning object " << obj << " in from space";
1250 collector->AssertToSpaceInvariant(nullptr, MemberOffset(0), obj);
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001251 AssertToSpaceInvariantFieldVisitor visitor(collector);
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07001252 obj->VisitReferences</*kVisitNativeRoots*/true, kDefaultVerifyFlags, kWithoutReadBarrier>(
1253 visitor,
1254 visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001255 }
1256
1257 private:
Mathieu Chartier97509952015-07-13 14:35:43 -07001258 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001259};
1260
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001261class ConcurrentCopying::RevokeThreadLocalMarkStackCheckpoint : public Closure {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001262 public:
Roland Levillain3887c462015-08-12 18:15:42 +01001263 RevokeThreadLocalMarkStackCheckpoint(ConcurrentCopying* concurrent_copying,
1264 bool disable_weak_ref_access)
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001265 : concurrent_copying_(concurrent_copying),
1266 disable_weak_ref_access_(disable_weak_ref_access) {
1267 }
1268
1269 virtual void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
1270 // Note: self is not necessarily equal to thread since thread may be suspended.
1271 Thread* self = Thread::Current();
1272 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
1273 << thread->GetState() << " thread " << thread << " self " << self;
1274 // Revoke thread local mark stacks.
1275 accounting::AtomicStack<mirror::Object>* tl_mark_stack = thread->GetThreadLocalMarkStack();
1276 if (tl_mark_stack != nullptr) {
1277 MutexLock mu(self, concurrent_copying_->mark_stack_lock_);
1278 concurrent_copying_->revoked_mark_stacks_.push_back(tl_mark_stack);
1279 thread->SetThreadLocalMarkStack(nullptr);
1280 }
1281 // Disable weak ref access.
1282 if (disable_weak_ref_access_) {
1283 thread->SetWeakRefAccessEnabled(false);
1284 }
1285 // If thread is a running mutator, then act on behalf of the garbage collector.
1286 // See the code in ThreadList::RunCheckpoint.
Mathieu Chartier10d25082015-10-28 18:36:09 -07001287 concurrent_copying_->GetBarrier().Pass(self);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001288 }
1289
1290 private:
1291 ConcurrentCopying* const concurrent_copying_;
1292 const bool disable_weak_ref_access_;
1293};
1294
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001295void ConcurrentCopying::RevokeThreadLocalMarkStacks(bool disable_weak_ref_access,
1296 Closure* checkpoint_callback) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001297 Thread* self = Thread::Current();
1298 RevokeThreadLocalMarkStackCheckpoint check_point(this, disable_weak_ref_access);
1299 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1300 gc_barrier_->Init(self, 0);
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001301 size_t barrier_count = thread_list->RunCheckpoint(&check_point, checkpoint_callback);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001302 // If there are no threads to wait which implys that all the checkpoint functions are finished,
1303 // then no need to release the mutator lock.
1304 if (barrier_count == 0) {
1305 return;
1306 }
1307 Locks::mutator_lock_->SharedUnlock(self);
1308 {
1309 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
1310 gc_barrier_->Increment(self, barrier_count);
1311 }
1312 Locks::mutator_lock_->SharedLock(self);
1313}
1314
1315void ConcurrentCopying::RevokeThreadLocalMarkStack(Thread* thread) {
1316 Thread* self = Thread::Current();
1317 CHECK_EQ(self, thread);
1318 accounting::AtomicStack<mirror::Object>* tl_mark_stack = thread->GetThreadLocalMarkStack();
1319 if (tl_mark_stack != nullptr) {
1320 CHECK(is_marking_);
1321 MutexLock mu(self, mark_stack_lock_);
1322 revoked_mark_stacks_.push_back(tl_mark_stack);
1323 thread->SetThreadLocalMarkStack(nullptr);
1324 }
1325}
1326
1327void ConcurrentCopying::ProcessMarkStack() {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001328 if (kVerboseMode) {
1329 LOG(INFO) << "ProcessMarkStack. ";
1330 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001331 bool empty_prev = false;
1332 while (true) {
1333 bool empty = ProcessMarkStackOnce();
1334 if (empty_prev && empty) {
1335 // Saw empty mark stack for a second time, done.
1336 break;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001337 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001338 empty_prev = empty;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001339 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001340}
1341
1342bool ConcurrentCopying::ProcessMarkStackOnce() {
1343 Thread* self = Thread::Current();
1344 CHECK(thread_running_gc_ != nullptr);
1345 CHECK(self == thread_running_gc_);
1346 CHECK(self->GetThreadLocalMarkStack() == nullptr);
1347 size_t count = 0;
1348 MarkStackMode mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1349 if (mark_stack_mode == kMarkStackModeThreadLocal) {
1350 // Process the thread-local mark stacks and the GC mark stack.
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001351 count += ProcessThreadLocalMarkStacks(false, nullptr);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001352 while (!gc_mark_stack_->IsEmpty()) {
1353 mirror::Object* to_ref = gc_mark_stack_->PopBack();
1354 ProcessMarkStackRef(to_ref);
1355 ++count;
1356 }
1357 gc_mark_stack_->Reset();
1358 } else if (mark_stack_mode == kMarkStackModeShared) {
Hiroshi Yamauchi30493242016-11-03 13:06:52 -07001359 // Do an empty checkpoint to avoid a race with a mutator preempted in the middle of a read
1360 // barrier but before pushing onto the mark stack. b/32508093. Note the weak ref access is
1361 // disabled at this point.
1362 IssueEmptyCheckpoint();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001363 // Process the shared GC mark stack with a lock.
1364 {
1365 MutexLock mu(self, mark_stack_lock_);
1366 CHECK(revoked_mark_stacks_.empty());
1367 }
1368 while (true) {
1369 std::vector<mirror::Object*> refs;
1370 {
1371 // Copy refs with lock. Note the number of refs should be small.
1372 MutexLock mu(self, mark_stack_lock_);
1373 if (gc_mark_stack_->IsEmpty()) {
1374 break;
1375 }
1376 for (StackReference<mirror::Object>* p = gc_mark_stack_->Begin();
1377 p != gc_mark_stack_->End(); ++p) {
1378 refs.push_back(p->AsMirrorPtr());
1379 }
1380 gc_mark_stack_->Reset();
1381 }
1382 for (mirror::Object* ref : refs) {
1383 ProcessMarkStackRef(ref);
1384 ++count;
1385 }
1386 }
1387 } else {
1388 CHECK_EQ(static_cast<uint32_t>(mark_stack_mode),
1389 static_cast<uint32_t>(kMarkStackModeGcExclusive));
1390 {
1391 MutexLock mu(self, mark_stack_lock_);
1392 CHECK(revoked_mark_stacks_.empty());
1393 }
1394 // Process the GC mark stack in the exclusive mode. No need to take the lock.
1395 while (!gc_mark_stack_->IsEmpty()) {
1396 mirror::Object* to_ref = gc_mark_stack_->PopBack();
1397 ProcessMarkStackRef(to_ref);
1398 ++count;
1399 }
1400 gc_mark_stack_->Reset();
1401 }
1402
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001403 // Return true if the stack was empty.
1404 return count == 0;
1405}
1406
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001407size_t ConcurrentCopying::ProcessThreadLocalMarkStacks(bool disable_weak_ref_access,
1408 Closure* checkpoint_callback) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001409 // Run a checkpoint to collect all thread local mark stacks and iterate over them all.
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001410 RevokeThreadLocalMarkStacks(disable_weak_ref_access, checkpoint_callback);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001411 size_t count = 0;
1412 std::vector<accounting::AtomicStack<mirror::Object>*> mark_stacks;
1413 {
1414 MutexLock mu(Thread::Current(), mark_stack_lock_);
1415 // Make a copy of the mark stack vector.
1416 mark_stacks = revoked_mark_stacks_;
1417 revoked_mark_stacks_.clear();
1418 }
1419 for (accounting::AtomicStack<mirror::Object>* mark_stack : mark_stacks) {
1420 for (StackReference<mirror::Object>* p = mark_stack->Begin(); p != mark_stack->End(); ++p) {
1421 mirror::Object* to_ref = p->AsMirrorPtr();
1422 ProcessMarkStackRef(to_ref);
1423 ++count;
1424 }
1425 {
1426 MutexLock mu(Thread::Current(), mark_stack_lock_);
1427 if (pooled_mark_stacks_.size() >= kMarkStackPoolSize) {
1428 // The pool has enough. Delete it.
1429 delete mark_stack;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001430 } else {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001431 // Otherwise, put it into the pool for later reuse.
1432 mark_stack->Reset();
1433 pooled_mark_stacks_.push_back(mark_stack);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001434 }
1435 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001436 }
1437 return count;
1438}
1439
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001440inline void ConcurrentCopying::ProcessMarkStackRef(mirror::Object* to_ref) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001441 DCHECK(!region_space_->IsInFromSpace(to_ref));
1442 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001443 DCHECK(to_ref->GetReadBarrierState() == ReadBarrier::GrayState())
1444 << " " << to_ref << " " << to_ref->GetReadBarrierState()
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001445 << " is_marked=" << IsMarked(to_ref);
1446 }
Mathieu Chartierc381c362016-08-23 13:27:53 -07001447 bool add_to_live_bytes = false;
1448 if (region_space_->IsInUnevacFromSpace(to_ref)) {
1449 // Mark the bitmap only in the GC thread here so that we don't need a CAS.
1450 if (!kUseBakerReadBarrier || !region_space_bitmap_->Set(to_ref)) {
1451 // It may be already marked if we accidentally pushed the same object twice due to the racy
1452 // bitmap read in MarkUnevacFromSpaceRegion.
1453 Scan(to_ref);
1454 // Only add to the live bytes if the object was not already marked.
1455 add_to_live_bytes = true;
1456 }
1457 } else {
1458 Scan(to_ref);
1459 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001460 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001461 DCHECK(to_ref->GetReadBarrierState() == ReadBarrier::GrayState())
1462 << " " << to_ref << " " << to_ref->GetReadBarrierState()
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001463 << " is_marked=" << IsMarked(to_ref);
1464 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001465#ifdef USE_BAKER_OR_BROOKS_READ_BARRIER
Hiroshi Yamauchi39c12d42016-12-06 16:46:37 -08001466 mirror::Object* referent = nullptr;
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001467 if (UNLIKELY((to_ref->GetClass<kVerifyNone, kWithoutReadBarrier>()->IsTypeOfReferenceClass() &&
Hiroshi Yamauchi39c12d42016-12-06 16:46:37 -08001468 (referent = to_ref->AsReference()->GetReferent<kWithoutReadBarrier>()) != nullptr &&
1469 !IsInToSpace(referent)))) {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001470 // Leave this reference gray in the queue so that GetReferent() will trigger a read barrier. We
1471 // will change it to white later in ReferenceQueue::DequeuePendingReference().
Richard Uhlere3627402016-02-02 13:36:55 -08001472 DCHECK(to_ref->AsReference()->GetPendingNext() != nullptr) << "Left unenqueued ref gray " << to_ref;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001473 } else {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001474 // We may occasionally leave a reference white in the queue if its referent happens to be
1475 // concurrently marked after the Scan() call above has enqueued the Reference, in which case the
1476 // above IsInToSpace() evaluates to true and we change the color from gray to white here in this
1477 // else block.
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001478 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001479 bool success = to_ref->AtomicSetReadBarrierState</*kCasRelease*/true>(
1480 ReadBarrier::GrayState(),
1481 ReadBarrier::WhiteState());
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001482 DCHECK(success) << "Must succeed as we won the race.";
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001483 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001484 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001485#else
1486 DCHECK(!kUseBakerReadBarrier);
1487#endif
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001488
Mathieu Chartierc381c362016-08-23 13:27:53 -07001489 if (add_to_live_bytes) {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001490 // Add to the live bytes per unevacuated from space. Note this code is always run by the
1491 // GC-running thread (no synchronization required).
1492 DCHECK(region_space_bitmap_->Test(to_ref));
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07001493 size_t obj_size = to_ref->SizeOf<kDefaultVerifyFlags>();
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001494 size_t alloc_size = RoundUp(obj_size, space::RegionSpace::kAlignment);
1495 region_space_->AddLiveBytes(to_ref, alloc_size);
1496 }
Andreas Gampee3ce7872017-02-22 13:36:21 -08001497 if (ReadBarrier::kEnableToSpaceInvariantChecks) {
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001498 AssertToSpaceInvariantObjectVisitor visitor(this);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001499 visitor(to_ref);
1500 }
1501}
1502
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001503class ConcurrentCopying::DisableWeakRefAccessCallback : public Closure {
1504 public:
1505 explicit DisableWeakRefAccessCallback(ConcurrentCopying* concurrent_copying)
1506 : concurrent_copying_(concurrent_copying) {
1507 }
1508
1509 void Run(Thread* self ATTRIBUTE_UNUSED) OVERRIDE REQUIRES(Locks::thread_list_lock_) {
1510 // This needs to run under the thread_list_lock_ critical section in ThreadList::RunCheckpoint()
1511 // to avoid a deadlock b/31500969.
1512 CHECK(concurrent_copying_->weak_ref_access_enabled_);
1513 concurrent_copying_->weak_ref_access_enabled_ = false;
1514 }
1515
1516 private:
1517 ConcurrentCopying* const concurrent_copying_;
1518};
1519
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001520void ConcurrentCopying::SwitchToSharedMarkStackMode() {
1521 Thread* self = Thread::Current();
1522 CHECK(thread_running_gc_ != nullptr);
1523 CHECK_EQ(self, thread_running_gc_);
1524 CHECK(self->GetThreadLocalMarkStack() == nullptr);
1525 MarkStackMode before_mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1526 CHECK_EQ(static_cast<uint32_t>(before_mark_stack_mode),
1527 static_cast<uint32_t>(kMarkStackModeThreadLocal));
1528 mark_stack_mode_.StoreRelaxed(kMarkStackModeShared);
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001529 DisableWeakRefAccessCallback dwrac(this);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001530 // Process the thread local mark stacks one last time after switching to the shared mark stack
1531 // mode and disable weak ref accesses.
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001532 ProcessThreadLocalMarkStacks(true, &dwrac);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001533 if (kVerboseMode) {
1534 LOG(INFO) << "Switched to shared mark stack mode and disabled weak ref access";
1535 }
1536}
1537
1538void ConcurrentCopying::SwitchToGcExclusiveMarkStackMode() {
1539 Thread* self = Thread::Current();
1540 CHECK(thread_running_gc_ != nullptr);
1541 CHECK_EQ(self, thread_running_gc_);
1542 CHECK(self->GetThreadLocalMarkStack() == nullptr);
1543 MarkStackMode before_mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1544 CHECK_EQ(static_cast<uint32_t>(before_mark_stack_mode),
1545 static_cast<uint32_t>(kMarkStackModeShared));
1546 mark_stack_mode_.StoreRelaxed(kMarkStackModeGcExclusive);
1547 QuasiAtomic::ThreadFenceForConstructor();
1548 if (kVerboseMode) {
1549 LOG(INFO) << "Switched to GC exclusive mark stack mode";
1550 }
1551}
1552
1553void ConcurrentCopying::CheckEmptyMarkStack() {
1554 Thread* self = Thread::Current();
1555 CHECK(thread_running_gc_ != nullptr);
1556 CHECK_EQ(self, thread_running_gc_);
1557 CHECK(self->GetThreadLocalMarkStack() == nullptr);
1558 MarkStackMode mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1559 if (mark_stack_mode == kMarkStackModeThreadLocal) {
1560 // Thread-local mark stack mode.
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001561 RevokeThreadLocalMarkStacks(false, nullptr);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001562 MutexLock mu(Thread::Current(), mark_stack_lock_);
1563 if (!revoked_mark_stacks_.empty()) {
1564 for (accounting::AtomicStack<mirror::Object>* mark_stack : revoked_mark_stacks_) {
1565 while (!mark_stack->IsEmpty()) {
1566 mirror::Object* obj = mark_stack->PopBack();
1567 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001568 uint32_t rb_state = obj->GetReadBarrierState();
1569 LOG(INFO) << "On mark queue : " << obj << " " << obj->PrettyTypeOf() << " rb_state="
1570 << rb_state << " is_marked=" << IsMarked(obj);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001571 } else {
David Sehr709b0702016-10-13 09:12:37 -07001572 LOG(INFO) << "On mark queue : " << obj << " " << obj->PrettyTypeOf()
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001573 << " is_marked=" << IsMarked(obj);
1574 }
1575 }
1576 }
1577 LOG(FATAL) << "mark stack is not empty";
1578 }
1579 } else {
1580 // Shared, GC-exclusive, or off.
1581 MutexLock mu(Thread::Current(), mark_stack_lock_);
1582 CHECK(gc_mark_stack_->IsEmpty());
1583 CHECK(revoked_mark_stacks_.empty());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001584 }
1585}
1586
1587void ConcurrentCopying::SweepSystemWeaks(Thread* self) {
1588 TimingLogger::ScopedTiming split("SweepSystemWeaks", GetTimings());
1589 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier97509952015-07-13 14:35:43 -07001590 Runtime::Current()->SweepSystemWeaks(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001591}
1592
1593void ConcurrentCopying::Sweep(bool swap_bitmaps) {
1594 {
1595 TimingLogger::ScopedTiming t("MarkStackAsLive", GetTimings());
1596 accounting::ObjectStack* live_stack = heap_->GetLiveStack();
1597 if (kEnableFromSpaceAccountingCheck) {
1598 CHECK_GE(live_stack_freeze_size_, live_stack->Size());
1599 }
1600 heap_->MarkAllocStackAsLive(live_stack);
1601 live_stack->Reset();
1602 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001603 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001604 TimingLogger::ScopedTiming split("Sweep", GetTimings());
1605 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
1606 if (space->IsContinuousMemMapAllocSpace()) {
1607 space::ContinuousMemMapAllocSpace* alloc_space = space->AsContinuousMemMapAllocSpace();
Mathieu Chartier763a31e2015-11-16 16:05:55 -08001608 if (space == region_space_ || immune_spaces_.ContainsSpace(space)) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001609 continue;
1610 }
1611 TimingLogger::ScopedTiming split2(
1612 alloc_space->IsZygoteSpace() ? "SweepZygoteSpace" : "SweepAllocSpace", GetTimings());
1613 RecordFree(alloc_space->Sweep(swap_bitmaps));
1614 }
1615 }
1616 SweepLargeObjects(swap_bitmaps);
1617}
1618
Mathieu Chartier962cd7a2016-08-16 12:15:59 -07001619void ConcurrentCopying::MarkZygoteLargeObjects() {
1620 TimingLogger::ScopedTiming split(__FUNCTION__, GetTimings());
1621 Thread* const self = Thread::Current();
1622 WriterMutexLock rmu(self, *Locks::heap_bitmap_lock_);
1623 space::LargeObjectSpace* const los = heap_->GetLargeObjectsSpace();
Nicolas Geoffray7acddd82017-05-03 15:04:55 +01001624 if (los != nullptr) {
1625 // Pick the current live bitmap (mark bitmap if swapped).
1626 accounting::LargeObjectBitmap* const live_bitmap = los->GetLiveBitmap();
1627 accounting::LargeObjectBitmap* const mark_bitmap = los->GetMarkBitmap();
1628 // Walk through all of the objects and explicitly mark the zygote ones so they don't get swept.
1629 std::pair<uint8_t*, uint8_t*> range = los->GetBeginEndAtomic();
1630 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(range.first),
1631 reinterpret_cast<uintptr_t>(range.second),
1632 [mark_bitmap, los, self](mirror::Object* obj)
1633 REQUIRES(Locks::heap_bitmap_lock_)
1634 REQUIRES_SHARED(Locks::mutator_lock_) {
1635 if (los->IsZygoteLargeObject(self, obj)) {
1636 mark_bitmap->Set(obj);
1637 }
1638 });
1639 }
Mathieu Chartier962cd7a2016-08-16 12:15:59 -07001640}
1641
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001642void ConcurrentCopying::SweepLargeObjects(bool swap_bitmaps) {
1643 TimingLogger::ScopedTiming split("SweepLargeObjects", GetTimings());
Nicolas Geoffray7acddd82017-05-03 15:04:55 +01001644 if (heap_->GetLargeObjectsSpace() != nullptr) {
1645 RecordFreeLOS(heap_->GetLargeObjectsSpace()->Sweep(swap_bitmaps));
1646 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001647}
1648
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001649void ConcurrentCopying::ReclaimPhase() {
1650 TimingLogger::ScopedTiming split("ReclaimPhase", GetTimings());
1651 if (kVerboseMode) {
1652 LOG(INFO) << "GC ReclaimPhase";
1653 }
1654 Thread* self = Thread::Current();
1655
1656 {
1657 // Double-check that the mark stack is empty.
1658 // Note: need to set this after VerifyNoFromSpaceRef().
1659 is_asserting_to_space_invariant_ = false;
1660 QuasiAtomic::ThreadFenceForConstructor();
1661 if (kVerboseMode) {
1662 LOG(INFO) << "Issue an empty check point. ";
1663 }
1664 IssueEmptyCheckpoint();
1665 // Disable the check.
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001666 is_mark_stack_push_disallowed_.StoreSequentiallyConsistent(0);
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001667 if (kUseBakerReadBarrier) {
1668 updated_all_immune_objects_.StoreSequentiallyConsistent(false);
1669 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001670 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001671 }
1672
1673 {
1674 // Record freed objects.
1675 TimingLogger::ScopedTiming split2("RecordFree", GetTimings());
1676 // Don't include thread-locals that are in the to-space.
Mathieu Chartier371b0472017-02-27 16:37:21 -08001677 const uint64_t from_bytes = region_space_->GetBytesAllocatedInFromSpace();
1678 const uint64_t from_objects = region_space_->GetObjectsAllocatedInFromSpace();
1679 const uint64_t unevac_from_bytes = region_space_->GetBytesAllocatedInUnevacFromSpace();
1680 const uint64_t unevac_from_objects = region_space_->GetObjectsAllocatedInUnevacFromSpace();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001681 uint64_t to_bytes = bytes_moved_.LoadSequentiallyConsistent();
Mathieu Chartiercca44a02016-08-17 10:07:29 -07001682 cumulative_bytes_moved_.FetchAndAddRelaxed(to_bytes);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001683 uint64_t to_objects = objects_moved_.LoadSequentiallyConsistent();
Mathieu Chartiercca44a02016-08-17 10:07:29 -07001684 cumulative_objects_moved_.FetchAndAddRelaxed(to_objects);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001685 if (kEnableFromSpaceAccountingCheck) {
1686 CHECK_EQ(from_space_num_objects_at_first_pause_, from_objects + unevac_from_objects);
1687 CHECK_EQ(from_space_num_bytes_at_first_pause_, from_bytes + unevac_from_bytes);
1688 }
1689 CHECK_LE(to_objects, from_objects);
1690 CHECK_LE(to_bytes, from_bytes);
Mathieu Chartier371b0472017-02-27 16:37:21 -08001691 // cleared_bytes and cleared_objects may be greater than the from space equivalents since
1692 // ClearFromSpace may clear empty unevac regions.
1693 uint64_t cleared_bytes;
1694 uint64_t cleared_objects;
1695 {
1696 TimingLogger::ScopedTiming split4("ClearFromSpace", GetTimings());
1697 region_space_->ClearFromSpace(&cleared_bytes, &cleared_objects);
1698 CHECK_GE(cleared_bytes, from_bytes);
1699 CHECK_GE(cleared_objects, from_objects);
1700 }
1701 int64_t freed_bytes = cleared_bytes - to_bytes;
1702 int64_t freed_objects = cleared_objects - to_objects;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001703 if (kVerboseMode) {
1704 LOG(INFO) << "RecordFree:"
1705 << " from_bytes=" << from_bytes << " from_objects=" << from_objects
1706 << " unevac_from_bytes=" << unevac_from_bytes << " unevac_from_objects=" << unevac_from_objects
1707 << " to_bytes=" << to_bytes << " to_objects=" << to_objects
1708 << " freed_bytes=" << freed_bytes << " freed_objects=" << freed_objects
1709 << " from_space size=" << region_space_->FromSpaceSize()
1710 << " unevac_from_space size=" << region_space_->UnevacFromSpaceSize()
1711 << " to_space size=" << region_space_->ToSpaceSize();
1712 LOG(INFO) << "(before) num_bytes_allocated=" << heap_->num_bytes_allocated_.LoadSequentiallyConsistent();
1713 }
1714 RecordFree(ObjectBytePair(freed_objects, freed_bytes));
1715 if (kVerboseMode) {
1716 LOG(INFO) << "(after) num_bytes_allocated=" << heap_->num_bytes_allocated_.LoadSequentiallyConsistent();
1717 }
1718 }
1719
1720 {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001721 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001722 Sweep(false);
1723 SwapBitmaps();
1724 heap_->UnBindBitmaps();
1725
Mathieu Chartier7ec38dc2016-10-07 15:24:46 -07001726 // 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 -07001727 DCHECK(region_space_bitmap_ != nullptr);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001728 region_space_bitmap_ = nullptr;
1729 }
1730
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001731 CheckEmptyMarkStack();
1732
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001733 if (kVerboseMode) {
1734 LOG(INFO) << "GC end of ReclaimPhase";
1735 }
1736}
1737
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001738// Assert the to-space invariant.
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07001739void ConcurrentCopying::AssertToSpaceInvariant(mirror::Object* obj,
1740 MemberOffset offset,
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001741 mirror::Object* ref) {
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07001742 CHECK_EQ(heap_->collector_type_, kCollectorTypeCC);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001743 if (is_asserting_to_space_invariant_) {
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07001744 using RegionType = space::RegionSpace::RegionType;
1745 space::RegionSpace::RegionType type = region_space_->GetRegionType(ref);
1746 if (type == RegionType::kRegionTypeToSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001747 // OK.
1748 return;
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07001749 } else if (type == RegionType::kRegionTypeUnevacFromSpace) {
Mathieu Chartierc381c362016-08-23 13:27:53 -07001750 CHECK(IsMarkedInUnevacFromSpace(ref)) << ref;
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07001751 } else if (UNLIKELY(type == RegionType::kRegionTypeFromSpace)) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001752 // Not OK. Do extra logging.
1753 if (obj != nullptr) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001754 LogFromSpaceRefHolder(obj, offset);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001755 }
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07001756 ref->GetLockWord(false).Dump(LOG_STREAM(FATAL_WITHOUT_ABORT));
David Sehr709b0702016-10-13 09:12:37 -07001757 CHECK(false) << "Found from-space ref " << ref << " " << ref->PrettyTypeOf();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001758 } else {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001759 AssertToSpaceInvariantInNonMovingSpace(obj, ref);
1760 }
1761 }
1762}
1763
1764class RootPrinter {
1765 public:
1766 RootPrinter() { }
1767
1768 template <class MirrorType>
1769 ALWAYS_INLINE void VisitRootIfNonNull(mirror::CompressedReference<MirrorType>* root)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001770 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001771 if (!root->IsNull()) {
1772 VisitRoot(root);
1773 }
1774 }
1775
1776 template <class MirrorType>
1777 void VisitRoot(mirror::Object** root)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001778 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07001779 LOG(FATAL_WITHOUT_ABORT) << "root=" << root << " ref=" << *root;
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001780 }
1781
1782 template <class MirrorType>
1783 void VisitRoot(mirror::CompressedReference<MirrorType>* root)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001784 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07001785 LOG(FATAL_WITHOUT_ABORT) << "root=" << root << " ref=" << root->AsMirrorPtr();
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001786 }
1787};
1788
1789void ConcurrentCopying::AssertToSpaceInvariant(GcRootSource* gc_root_source,
1790 mirror::Object* ref) {
1791 CHECK(heap_->collector_type_ == kCollectorTypeCC) << static_cast<size_t>(heap_->collector_type_);
1792 if (is_asserting_to_space_invariant_) {
1793 if (region_space_->IsInToSpace(ref)) {
1794 // OK.
1795 return;
1796 } else if (region_space_->IsInUnevacFromSpace(ref)) {
Mathieu Chartierc381c362016-08-23 13:27:53 -07001797 CHECK(IsMarkedInUnevacFromSpace(ref)) << ref;
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001798 } else if (region_space_->IsInFromSpace(ref)) {
1799 // Not OK. Do extra logging.
1800 if (gc_root_source == nullptr) {
1801 // No info.
1802 } else if (gc_root_source->HasArtField()) {
1803 ArtField* field = gc_root_source->GetArtField();
David Sehr709b0702016-10-13 09:12:37 -07001804 LOG(FATAL_WITHOUT_ABORT) << "gc root in field " << field << " "
1805 << ArtField::PrettyField(field);
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001806 RootPrinter root_printer;
1807 field->VisitRoots(root_printer);
1808 } else if (gc_root_source->HasArtMethod()) {
1809 ArtMethod* method = gc_root_source->GetArtMethod();
David Sehr709b0702016-10-13 09:12:37 -07001810 LOG(FATAL_WITHOUT_ABORT) << "gc root in method " << method << " "
1811 << ArtMethod::PrettyMethod(method);
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001812 RootPrinter root_printer;
Andreas Gampe542451c2016-07-26 09:02:02 -07001813 method->VisitRoots(root_printer, kRuntimePointerSize);
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001814 }
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07001815 ref->GetLockWord(false).Dump(LOG_STREAM(FATAL_WITHOUT_ABORT));
1816 region_space_->DumpNonFreeRegions(LOG_STREAM(FATAL_WITHOUT_ABORT));
1817 PrintFileToLog("/proc/self/maps", LogSeverity::FATAL_WITHOUT_ABORT);
1818 MemMap::DumpMaps(LOG_STREAM(FATAL_WITHOUT_ABORT), true);
David Sehr709b0702016-10-13 09:12:37 -07001819 CHECK(false) << "Found from-space ref " << ref << " " << ref->PrettyTypeOf();
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001820 } else {
1821 AssertToSpaceInvariantInNonMovingSpace(nullptr, ref);
1822 }
1823 }
1824}
1825
1826void ConcurrentCopying::LogFromSpaceRefHolder(mirror::Object* obj, MemberOffset offset) {
1827 if (kUseBakerReadBarrier) {
David Sehr709b0702016-10-13 09:12:37 -07001828 LOG(INFO) << "holder=" << obj << " " << obj->PrettyTypeOf()
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001829 << " holder rb_state=" << obj->GetReadBarrierState();
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001830 } else {
David Sehr709b0702016-10-13 09:12:37 -07001831 LOG(INFO) << "holder=" << obj << " " << obj->PrettyTypeOf();
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001832 }
1833 if (region_space_->IsInFromSpace(obj)) {
1834 LOG(INFO) << "holder is in the from-space.";
1835 } else if (region_space_->IsInToSpace(obj)) {
1836 LOG(INFO) << "holder is in the to-space.";
1837 } else if (region_space_->IsInUnevacFromSpace(obj)) {
1838 LOG(INFO) << "holder is in the unevac from-space.";
Mathieu Chartierc381c362016-08-23 13:27:53 -07001839 if (IsMarkedInUnevacFromSpace(obj)) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001840 LOG(INFO) << "holder is marked in the region space bitmap.";
1841 } else {
1842 LOG(INFO) << "holder is not marked in the region space bitmap.";
1843 }
1844 } else {
1845 // In a non-moving space.
Mathieu Chartier763a31e2015-11-16 16:05:55 -08001846 if (immune_spaces_.ContainsObject(obj)) {
1847 LOG(INFO) << "holder is in an immune image or the zygote space.";
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001848 } else {
Mathieu Chartier763a31e2015-11-16 16:05:55 -08001849 LOG(INFO) << "holder is in a non-immune, non-moving (or main) space.";
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001850 accounting::ContinuousSpaceBitmap* mark_bitmap =
1851 heap_mark_bitmap_->GetContinuousSpaceBitmap(obj);
1852 accounting::LargeObjectBitmap* los_bitmap =
1853 heap_mark_bitmap_->GetLargeObjectBitmap(obj);
1854 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
1855 bool is_los = mark_bitmap == nullptr;
1856 if (!is_los && mark_bitmap->Test(obj)) {
1857 LOG(INFO) << "holder is marked in the mark bit map.";
1858 } else if (is_los && los_bitmap->Test(obj)) {
1859 LOG(INFO) << "holder is marked in the los bit map.";
1860 } else {
1861 // If ref is on the allocation stack, then it is considered
1862 // mark/alive (but not necessarily on the live stack.)
1863 if (IsOnAllocStack(obj)) {
1864 LOG(INFO) << "holder is on the alloc stack.";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001865 } else {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001866 LOG(INFO) << "holder is not marked or on the alloc stack.";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001867 }
1868 }
1869 }
1870 }
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001871 LOG(INFO) << "offset=" << offset.SizeValue();
1872}
1873
1874void ConcurrentCopying::AssertToSpaceInvariantInNonMovingSpace(mirror::Object* obj,
1875 mirror::Object* ref) {
1876 // In a non-moving spaces. Check that the ref is marked.
Mathieu Chartier763a31e2015-11-16 16:05:55 -08001877 if (immune_spaces_.ContainsObject(ref)) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001878 if (kUseBakerReadBarrier) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001879 // Immune object may not be gray if called from the GC.
1880 if (Thread::Current() == thread_running_gc_ && !gc_grays_immune_objects_) {
1881 return;
1882 }
1883 bool updated_all_immune_objects = updated_all_immune_objects_.LoadSequentiallyConsistent();
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001884 CHECK(updated_all_immune_objects || ref->GetReadBarrierState() == ReadBarrier::GrayState())
1885 << "Unmarked immune space ref. obj=" << obj << " rb_state="
1886 << (obj != nullptr ? obj->GetReadBarrierState() : 0U)
1887 << " ref=" << ref << " ref rb_state=" << ref->GetReadBarrierState()
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001888 << " updated_all_immune_objects=" << updated_all_immune_objects;
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001889 }
1890 } else {
1891 accounting::ContinuousSpaceBitmap* mark_bitmap =
1892 heap_mark_bitmap_->GetContinuousSpaceBitmap(ref);
1893 accounting::LargeObjectBitmap* los_bitmap =
1894 heap_mark_bitmap_->GetLargeObjectBitmap(ref);
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001895 bool is_los = mark_bitmap == nullptr;
1896 if ((!is_los && mark_bitmap->Test(ref)) ||
1897 (is_los && los_bitmap->Test(ref))) {
1898 // OK.
1899 } else {
1900 // If ref is on the allocation stack, then it may not be
1901 // marked live, but considered marked/alive (but not
1902 // necessarily on the live stack).
1903 CHECK(IsOnAllocStack(ref)) << "Unmarked ref that's not on the allocation stack. "
1904 << "obj=" << obj << " ref=" << ref;
1905 }
1906 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001907}
1908
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001909// Used to scan ref fields of an object.
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001910class ConcurrentCopying::RefFieldsVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001911 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001912 explicit RefFieldsVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001913 : collector_(collector) {}
1914
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07001915 void operator()(mirror::Object* obj, MemberOffset offset, bool /* is_static */)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001916 const ALWAYS_INLINE REQUIRES_SHARED(Locks::mutator_lock_)
1917 REQUIRES_SHARED(Locks::heap_bitmap_lock_) {
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07001918 collector_->Process(obj, offset);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001919 }
1920
Mathieu Chartier31e88222016-10-14 18:43:19 -07001921 void operator()(ObjPtr<mirror::Class> klass, ObjPtr<mirror::Reference> ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001922 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001923 CHECK(klass->IsTypeOfReferenceClass());
1924 collector_->DelayReferenceReferent(klass, ref);
1925 }
1926
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001927 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001928 ALWAYS_INLINE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001929 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001930 if (!root->IsNull()) {
1931 VisitRoot(root);
1932 }
1933 }
1934
1935 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001936 ALWAYS_INLINE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001937 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001938 collector_->MarkRoot</*kGrayImmuneObject*/false>(root);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001939 }
1940
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001941 private:
1942 ConcurrentCopying* const collector_;
1943};
1944
1945// Scan ref fields of an object.
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001946inline void ConcurrentCopying::Scan(mirror::Object* to_ref) {
Hiroshi Yamauchi9b60d502017-02-03 15:09:26 -08001947 if (kDisallowReadBarrierDuringScan && !Runtime::Current()->IsActiveTransaction()) {
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07001948 // Avoid all read barriers during visit references to help performance.
Hiroshi Yamauchi9b60d502017-02-03 15:09:26 -08001949 // Don't do this in transaction mode because we may read the old value of an field which may
1950 // trigger read barriers.
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07001951 Thread::Current()->ModifyDebugDisallowReadBarrier(1);
1952 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001953 DCHECK(!region_space_->IsInFromSpace(to_ref));
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001954 DCHECK_EQ(Thread::Current(), thread_running_gc_);
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001955 RefFieldsVisitor visitor(this);
Hiroshi Yamauchi5496f692016-02-17 13:29:59 -08001956 // Disable the read barrier for a performance reason.
1957 to_ref->VisitReferences</*kVisitNativeRoots*/true, kDefaultVerifyFlags, kWithoutReadBarrier>(
1958 visitor, visitor);
Hiroshi Yamauchi9b60d502017-02-03 15:09:26 -08001959 if (kDisallowReadBarrierDuringScan && !Runtime::Current()->IsActiveTransaction()) {
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07001960 Thread::Current()->ModifyDebugDisallowReadBarrier(-1);
1961 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001962}
1963
1964// Process a field.
1965inline void ConcurrentCopying::Process(mirror::Object* obj, MemberOffset offset) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001966 DCHECK_EQ(Thread::Current(), thread_running_gc_);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001967 mirror::Object* ref = obj->GetFieldObject<
1968 mirror::Object, kVerifyNone, kWithoutReadBarrier, false>(offset);
Mathieu Chartierc381c362016-08-23 13:27:53 -07001969 mirror::Object* to_ref = Mark</*kGrayImmuneObject*/false, /*kFromGCThread*/true>(ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001970 if (to_ref == ref) {
1971 return;
1972 }
1973 // This may fail if the mutator writes to the field at the same time. But it's ok.
1974 mirror::Object* expected_ref = ref;
1975 mirror::Object* new_ref = to_ref;
1976 do {
1977 if (expected_ref !=
1978 obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier, false>(offset)) {
1979 // It was updated by the mutator.
1980 break;
1981 }
Hiroshi Yamauchifed3e2f2015-10-20 11:11:56 -07001982 } while (!obj->CasFieldWeakRelaxedObjectWithoutWriteBarrier<
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001983 false, false, kVerifyNone>(offset, expected_ref, new_ref));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001984}
1985
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001986// Process some roots.
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001987inline void ConcurrentCopying::VisitRoots(
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001988 mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED) {
1989 for (size_t i = 0; i < count; ++i) {
1990 mirror::Object** root = roots[i];
1991 mirror::Object* ref = *root;
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001992 mirror::Object* to_ref = Mark(ref);
1993 if (to_ref == ref) {
Mathieu Chartier4809d0a2015-04-07 10:39:04 -07001994 continue;
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001995 }
1996 Atomic<mirror::Object*>* addr = reinterpret_cast<Atomic<mirror::Object*>*>(root);
1997 mirror::Object* expected_ref = ref;
1998 mirror::Object* new_ref = to_ref;
1999 do {
2000 if (expected_ref != addr->LoadRelaxed()) {
2001 // It was updated by the mutator.
2002 break;
2003 }
Hiroshi Yamauchifed3e2f2015-10-20 11:11:56 -07002004 } while (!addr->CompareExchangeWeakRelaxed(expected_ref, new_ref));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002005 }
2006}
2007
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002008template<bool kGrayImmuneObject>
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002009inline void ConcurrentCopying::MarkRoot(mirror::CompressedReference<mirror::Object>* root) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002010 DCHECK(!root->IsNull());
2011 mirror::Object* const ref = root->AsMirrorPtr();
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002012 mirror::Object* to_ref = Mark<kGrayImmuneObject>(ref);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002013 if (to_ref != ref) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002014 auto* addr = reinterpret_cast<Atomic<mirror::CompressedReference<mirror::Object>>*>(root);
2015 auto expected_ref = mirror::CompressedReference<mirror::Object>::FromMirrorPtr(ref);
2016 auto new_ref = mirror::CompressedReference<mirror::Object>::FromMirrorPtr(to_ref);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002017 // If the cas fails, then it was updated by the mutator.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002018 do {
2019 if (ref != addr->LoadRelaxed().AsMirrorPtr()) {
2020 // It was updated by the mutator.
2021 break;
2022 }
Hiroshi Yamauchifed3e2f2015-10-20 11:11:56 -07002023 } while (!addr->CompareExchangeWeakRelaxed(expected_ref, new_ref));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002024 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002025}
2026
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002027inline void ConcurrentCopying::VisitRoots(
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002028 mirror::CompressedReference<mirror::Object>** roots, size_t count,
2029 const RootInfo& info ATTRIBUTE_UNUSED) {
2030 for (size_t i = 0; i < count; ++i) {
2031 mirror::CompressedReference<mirror::Object>* const root = roots[i];
2032 if (!root->IsNull()) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002033 // kGrayImmuneObject is true because this is used for the thread flip.
2034 MarkRoot</*kGrayImmuneObject*/true>(root);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002035 }
2036 }
2037}
2038
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002039// Temporary set gc_grays_immune_objects_ to true in a scope if the current thread is GC.
2040class ConcurrentCopying::ScopedGcGraysImmuneObjects {
2041 public:
2042 explicit ScopedGcGraysImmuneObjects(ConcurrentCopying* collector)
2043 : collector_(collector), enabled_(false) {
2044 if (kUseBakerReadBarrier &&
2045 collector_->thread_running_gc_ == Thread::Current() &&
2046 !collector_->gc_grays_immune_objects_) {
2047 collector_->gc_grays_immune_objects_ = true;
2048 enabled_ = true;
2049 }
2050 }
2051
2052 ~ScopedGcGraysImmuneObjects() {
2053 if (kUseBakerReadBarrier &&
2054 collector_->thread_running_gc_ == Thread::Current() &&
2055 enabled_) {
2056 DCHECK(collector_->gc_grays_immune_objects_);
2057 collector_->gc_grays_immune_objects_ = false;
2058 }
2059 }
2060
2061 private:
2062 ConcurrentCopying* const collector_;
2063 bool enabled_;
2064};
2065
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002066// Fill the given memory block with a dummy object. Used to fill in a
2067// copy of objects that was lost in race.
2068void ConcurrentCopying::FillWithDummyObject(mirror::Object* dummy_obj, size_t byte_size) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002069 // GC doesn't gray immune objects while scanning immune objects. But we need to trigger the read
2070 // barriers here because we need the updated reference to the int array class, etc. Temporary set
2071 // gc_grays_immune_objects_ to true so that we won't cause a DCHECK failure in MarkImmuneSpace().
2072 ScopedGcGraysImmuneObjects scoped_gc_gray_immune_objects(this);
Roland Levillain14d90572015-07-16 10:52:26 +01002073 CHECK_ALIGNED(byte_size, kObjectAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002074 memset(dummy_obj, 0, byte_size);
Mathieu Chartierd6636d32016-07-28 11:02:38 -07002075 // Avoid going through read barrier for since kDisallowReadBarrierDuringScan may be enabled.
2076 // Explicitly mark to make sure to get an object in the to-space.
2077 mirror::Class* int_array_class = down_cast<mirror::Class*>(
2078 Mark(mirror::IntArray::GetArrayClass<kWithoutReadBarrier>()));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002079 CHECK(int_array_class != nullptr);
2080 AssertToSpaceInvariant(nullptr, MemberOffset(0), int_array_class);
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07002081 size_t component_size = int_array_class->GetComponentSize<kWithoutReadBarrier>();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002082 CHECK_EQ(component_size, sizeof(int32_t));
2083 size_t data_offset = mirror::Array::DataOffset(component_size).SizeValue();
2084 if (data_offset > byte_size) {
2085 // An int array is too big. Use java.lang.Object.
Mathieu Chartier9aef9922017-04-23 13:53:50 -07002086 CHECK(java_lang_Object_ != nullptr);
Mathieu Chartier3ed8ec12017-04-20 19:28:54 -07002087 AssertToSpaceInvariant(nullptr, MemberOffset(0), java_lang_Object_);
2088 CHECK_EQ(byte_size, (java_lang_Object_->GetObjectSize<kVerifyNone, kWithoutReadBarrier>()));
2089 dummy_obj->SetClass(java_lang_Object_);
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07002090 CHECK_EQ(byte_size, (dummy_obj->SizeOf<kVerifyNone>()));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002091 } else {
2092 // Use an int array.
2093 dummy_obj->SetClass(int_array_class);
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07002094 CHECK((dummy_obj->IsArrayInstance<kVerifyNone, kWithoutReadBarrier>()));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002095 int32_t length = (byte_size - data_offset) / component_size;
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07002096 mirror::Array* dummy_arr = dummy_obj->AsArray<kVerifyNone, kWithoutReadBarrier>();
2097 dummy_arr->SetLength(length);
2098 CHECK_EQ(dummy_arr->GetLength(), length)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002099 << "byte_size=" << byte_size << " length=" << length
2100 << " component_size=" << component_size << " data_offset=" << data_offset;
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07002101 CHECK_EQ(byte_size, (dummy_obj->SizeOf<kVerifyNone>()))
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002102 << "byte_size=" << byte_size << " length=" << length
2103 << " component_size=" << component_size << " data_offset=" << data_offset;
2104 }
2105}
2106
2107// Reuse the memory blocks that were copy of objects that were lost in race.
2108mirror::Object* ConcurrentCopying::AllocateInSkippedBlock(size_t alloc_size) {
2109 // Try to reuse the blocks that were unused due to CAS failures.
Roland Levillain14d90572015-07-16 10:52:26 +01002110 CHECK_ALIGNED(alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002111 Thread* self = Thread::Current();
2112 size_t min_object_size = RoundUp(sizeof(mirror::Object), space::RegionSpace::kAlignment);
Mathieu Chartierd6636d32016-07-28 11:02:38 -07002113 size_t byte_size;
2114 uint8_t* addr;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002115 {
Mathieu Chartierd6636d32016-07-28 11:02:38 -07002116 MutexLock mu(self, skipped_blocks_lock_);
2117 auto it = skipped_blocks_map_.lower_bound(alloc_size);
2118 if (it == skipped_blocks_map_.end()) {
2119 // Not found.
2120 return nullptr;
2121 }
2122 byte_size = it->first;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002123 CHECK_GE(byte_size, alloc_size);
2124 if (byte_size > alloc_size && byte_size - alloc_size < min_object_size) {
2125 // If remainder would be too small for a dummy object, retry with a larger request size.
2126 it = skipped_blocks_map_.lower_bound(alloc_size + min_object_size);
2127 if (it == skipped_blocks_map_.end()) {
2128 // Not found.
2129 return nullptr;
2130 }
Roland Levillain14d90572015-07-16 10:52:26 +01002131 CHECK_ALIGNED(it->first - alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002132 CHECK_GE(it->first - alloc_size, min_object_size)
2133 << "byte_size=" << byte_size << " it->first=" << it->first << " alloc_size=" << alloc_size;
2134 }
Mathieu Chartierd6636d32016-07-28 11:02:38 -07002135 // Found a block.
2136 CHECK(it != skipped_blocks_map_.end());
2137 byte_size = it->first;
2138 addr = it->second;
2139 CHECK_GE(byte_size, alloc_size);
2140 CHECK(region_space_->IsInToSpace(reinterpret_cast<mirror::Object*>(addr)));
2141 CHECK_ALIGNED(byte_size, space::RegionSpace::kAlignment);
2142 if (kVerboseMode) {
2143 LOG(INFO) << "Reusing skipped bytes : " << reinterpret_cast<void*>(addr) << ", " << byte_size;
2144 }
2145 skipped_blocks_map_.erase(it);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002146 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002147 memset(addr, 0, byte_size);
2148 if (byte_size > alloc_size) {
2149 // Return the remainder to the map.
Roland Levillain14d90572015-07-16 10:52:26 +01002150 CHECK_ALIGNED(byte_size - alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002151 CHECK_GE(byte_size - alloc_size, min_object_size);
Mathieu Chartierd6636d32016-07-28 11:02:38 -07002152 // FillWithDummyObject may mark an object, avoid holding skipped_blocks_lock_ to prevent lock
2153 // violation and possible deadlock. The deadlock case is a recursive case:
2154 // FillWithDummyObject -> IntArray::GetArrayClass -> Mark -> Copy -> AllocateInSkippedBlock.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002155 FillWithDummyObject(reinterpret_cast<mirror::Object*>(addr + alloc_size),
2156 byte_size - alloc_size);
2157 CHECK(region_space_->IsInToSpace(reinterpret_cast<mirror::Object*>(addr + alloc_size)));
Mathieu Chartierd6636d32016-07-28 11:02:38 -07002158 {
2159 MutexLock mu(self, skipped_blocks_lock_);
2160 skipped_blocks_map_.insert(std::make_pair(byte_size - alloc_size, addr + alloc_size));
2161 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002162 }
2163 return reinterpret_cast<mirror::Object*>(addr);
2164}
2165
Mathieu Chartieref496d92017-04-28 18:58:59 -07002166mirror::Object* ConcurrentCopying::Copy(mirror::Object* from_ref,
2167 mirror::Object* holder,
2168 MemberOffset offset) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002169 DCHECK(region_space_->IsInFromSpace(from_ref));
Mathieu Chartieref496d92017-04-28 18:58:59 -07002170 // If the class pointer is null, the object is invalid. This could occur for a dangling pointer
2171 // from a previous GC that is either inside or outside the allocated region.
2172 mirror::Class* klass = from_ref->GetClass<kVerifyNone, kWithoutReadBarrier>();
2173 if (UNLIKELY(klass == nullptr)) {
2174 heap_->GetVerification()->LogHeapCorruption(holder, offset, from_ref, /* fatal */ true);
2175 }
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07002176 // There must not be a read barrier to avoid nested RB that might violate the to-space invariant.
2177 // Note that from_ref is a from space ref so the SizeOf() call will access the from-space meta
2178 // objects, but it's ok and necessary.
2179 size_t obj_size = from_ref->SizeOf<kDefaultVerifyFlags>();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002180 size_t region_space_alloc_size = RoundUp(obj_size, space::RegionSpace::kAlignment);
2181 size_t region_space_bytes_allocated = 0U;
2182 size_t non_moving_space_bytes_allocated = 0U;
2183 size_t bytes_allocated = 0U;
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07002184 size_t dummy;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002185 mirror::Object* to_ref = region_space_->AllocNonvirtual<true>(
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07002186 region_space_alloc_size, &region_space_bytes_allocated, nullptr, &dummy);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002187 bytes_allocated = region_space_bytes_allocated;
2188 if (to_ref != nullptr) {
2189 DCHECK_EQ(region_space_alloc_size, region_space_bytes_allocated);
2190 }
2191 bool fall_back_to_non_moving = false;
2192 if (UNLIKELY(to_ref == nullptr)) {
2193 // Failed to allocate in the region space. Try the skipped blocks.
2194 to_ref = AllocateInSkippedBlock(region_space_alloc_size);
2195 if (to_ref != nullptr) {
2196 // Succeeded to allocate in a skipped block.
2197 if (heap_->use_tlab_) {
2198 // This is necessary for the tlab case as it's not accounted in the space.
2199 region_space_->RecordAlloc(to_ref);
2200 }
2201 bytes_allocated = region_space_alloc_size;
2202 } else {
2203 // Fall back to the non-moving space.
2204 fall_back_to_non_moving = true;
2205 if (kVerboseMode) {
2206 LOG(INFO) << "Out of memory in the to-space. Fall back to non-moving. skipped_bytes="
2207 << to_space_bytes_skipped_.LoadSequentiallyConsistent()
2208 << " skipped_objects=" << to_space_objects_skipped_.LoadSequentiallyConsistent();
2209 }
2210 fall_back_to_non_moving = true;
2211 to_ref = heap_->non_moving_space_->Alloc(Thread::Current(), obj_size,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07002212 &non_moving_space_bytes_allocated, nullptr, &dummy);
Mathieu Chartierb01335c2017-03-22 13:15:01 -07002213 if (UNLIKELY(to_ref == nullptr)) {
2214 LOG(FATAL_WITHOUT_ABORT) << "Fall-back non-moving space allocation failed for a "
2215 << obj_size << " byte object in region type "
2216 << region_space_->GetRegionType(from_ref);
2217 LOG(FATAL) << "Object address=" << from_ref << " type=" << from_ref->PrettyTypeOf();
2218 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002219 bytes_allocated = non_moving_space_bytes_allocated;
2220 // Mark it in the mark bitmap.
2221 accounting::ContinuousSpaceBitmap* mark_bitmap =
2222 heap_mark_bitmap_->GetContinuousSpaceBitmap(to_ref);
2223 CHECK(mark_bitmap != nullptr);
2224 CHECK(!mark_bitmap->AtomicTestAndSet(to_ref));
2225 }
2226 }
2227 DCHECK(to_ref != nullptr);
2228
Mathieu Chartierd818adb2016-09-15 13:12:47 -07002229 // Copy the object excluding the lock word since that is handled in the loop.
Mathieu Chartieref496d92017-04-28 18:58:59 -07002230 to_ref->SetClass(klass);
Mathieu Chartierd818adb2016-09-15 13:12:47 -07002231 const size_t kObjectHeaderSize = sizeof(mirror::Object);
2232 DCHECK_GE(obj_size, kObjectHeaderSize);
2233 static_assert(kObjectHeaderSize == sizeof(mirror::HeapReference<mirror::Class>) +
2234 sizeof(LockWord),
2235 "Object header size does not match");
2236 // Memcpy can tear for words since it may do byte copy. It is only safe to do this since the
2237 // object in the from space is immutable other than the lock word. b/31423258
2238 memcpy(reinterpret_cast<uint8_t*>(to_ref) + kObjectHeaderSize,
2239 reinterpret_cast<const uint8_t*>(from_ref) + kObjectHeaderSize,
2240 obj_size - kObjectHeaderSize);
2241
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002242 // Attempt to install the forward pointer. This is in a loop as the
2243 // lock word atomic write can fail.
2244 while (true) {
Mathieu Chartierd818adb2016-09-15 13:12:47 -07002245 LockWord old_lock_word = from_ref->GetLockWord(false);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002246
2247 if (old_lock_word.GetState() == LockWord::kForwardingAddress) {
2248 // Lost the race. Another thread (either GC or mutator) stored
2249 // the forwarding pointer first. Make the lost copy (to_ref)
2250 // look like a valid but dead (dummy) object and keep it for
2251 // future reuse.
2252 FillWithDummyObject(to_ref, bytes_allocated);
2253 if (!fall_back_to_non_moving) {
2254 DCHECK(region_space_->IsInToSpace(to_ref));
2255 if (bytes_allocated > space::RegionSpace::kRegionSize) {
2256 // Free the large alloc.
2257 region_space_->FreeLarge(to_ref, bytes_allocated);
2258 } else {
2259 // Record the lost copy for later reuse.
2260 heap_->num_bytes_allocated_.FetchAndAddSequentiallyConsistent(bytes_allocated);
2261 to_space_bytes_skipped_.FetchAndAddSequentiallyConsistent(bytes_allocated);
2262 to_space_objects_skipped_.FetchAndAddSequentiallyConsistent(1);
2263 MutexLock mu(Thread::Current(), skipped_blocks_lock_);
2264 skipped_blocks_map_.insert(std::make_pair(bytes_allocated,
2265 reinterpret_cast<uint8_t*>(to_ref)));
2266 }
2267 } else {
2268 DCHECK(heap_->non_moving_space_->HasAddress(to_ref));
2269 DCHECK_EQ(bytes_allocated, non_moving_space_bytes_allocated);
2270 // Free the non-moving-space chunk.
2271 accounting::ContinuousSpaceBitmap* mark_bitmap =
2272 heap_mark_bitmap_->GetContinuousSpaceBitmap(to_ref);
2273 CHECK(mark_bitmap != nullptr);
2274 CHECK(mark_bitmap->Clear(to_ref));
2275 heap_->non_moving_space_->Free(Thread::Current(), to_ref);
2276 }
2277
2278 // Get the winner's forward ptr.
2279 mirror::Object* lost_fwd_ptr = to_ref;
2280 to_ref = reinterpret_cast<mirror::Object*>(old_lock_word.ForwardingAddress());
2281 CHECK(to_ref != nullptr);
2282 CHECK_NE(to_ref, lost_fwd_ptr);
Mathieu Chartierdfcd6f42016-09-13 10:02:48 -07002283 CHECK(region_space_->IsInToSpace(to_ref) || heap_->non_moving_space_->HasAddress(to_ref))
2284 << "to_ref=" << to_ref << " " << heap_->DumpSpaces();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002285 CHECK_NE(to_ref->GetLockWord(false).GetState(), LockWord::kForwardingAddress);
2286 return to_ref;
2287 }
2288
Mathieu Chartierd818adb2016-09-15 13:12:47 -07002289 // Copy the old lock word over since we did not copy it yet.
2290 to_ref->SetLockWord(old_lock_word, false);
Hiroshi Yamauchi60f63f52015-04-23 16:12:40 -07002291 // Set the gray ptr.
2292 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002293 to_ref->SetReadBarrierState(ReadBarrier::GrayState());
Hiroshi Yamauchi60f63f52015-04-23 16:12:40 -07002294 }
2295
Mathieu Chartiera8131262016-11-29 17:55:19 -08002296 // Do a fence to prevent the field CAS in ConcurrentCopying::Process from possibly reordering
2297 // before the object copy.
2298 QuasiAtomic::ThreadFenceRelease();
2299
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002300 LockWord new_lock_word = LockWord::FromForwardingAddress(reinterpret_cast<size_t>(to_ref));
2301
2302 // Try to atomically write the fwd ptr.
Mathieu Chartiera8131262016-11-29 17:55:19 -08002303 bool success = from_ref->CasLockWordWeakRelaxed(old_lock_word, new_lock_word);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002304 if (LIKELY(success)) {
2305 // The CAS succeeded.
Mathieu Chartiera8131262016-11-29 17:55:19 -08002306 objects_moved_.FetchAndAddRelaxed(1);
2307 bytes_moved_.FetchAndAddRelaxed(region_space_alloc_size);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002308 if (LIKELY(!fall_back_to_non_moving)) {
2309 DCHECK(region_space_->IsInToSpace(to_ref));
2310 } else {
2311 DCHECK(heap_->non_moving_space_->HasAddress(to_ref));
2312 DCHECK_EQ(bytes_allocated, non_moving_space_bytes_allocated);
2313 }
2314 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002315 DCHECK(to_ref->GetReadBarrierState() == ReadBarrier::GrayState());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002316 }
2317 DCHECK(GetFwdPtr(from_ref) == to_ref);
2318 CHECK_NE(to_ref->GetLockWord(false).GetState(), LockWord::kForwardingAddress);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002319 PushOntoMarkStack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002320 return to_ref;
2321 } else {
2322 // The CAS failed. It may have lost the race or may have failed
2323 // due to monitor/hashcode ops. Either way, retry.
2324 }
2325 }
2326}
2327
2328mirror::Object* ConcurrentCopying::IsMarked(mirror::Object* from_ref) {
2329 DCHECK(from_ref != nullptr);
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08002330 space::RegionSpace::RegionType rtype = region_space_->GetRegionType(from_ref);
2331 if (rtype == space::RegionSpace::RegionType::kRegionTypeToSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002332 // It's already marked.
2333 return from_ref;
2334 }
2335 mirror::Object* to_ref;
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08002336 if (rtype == space::RegionSpace::RegionType::kRegionTypeFromSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002337 to_ref = GetFwdPtr(from_ref);
2338 DCHECK(to_ref == nullptr || region_space_->IsInToSpace(to_ref) ||
2339 heap_->non_moving_space_->HasAddress(to_ref))
2340 << "from_ref=" << from_ref << " to_ref=" << to_ref;
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08002341 } else if (rtype == space::RegionSpace::RegionType::kRegionTypeUnevacFromSpace) {
Mathieu Chartierc381c362016-08-23 13:27:53 -07002342 if (IsMarkedInUnevacFromSpace(from_ref)) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002343 to_ref = from_ref;
2344 } else {
2345 to_ref = nullptr;
2346 }
2347 } else {
2348 // from_ref is in a non-moving space.
Mathieu Chartier763a31e2015-11-16 16:05:55 -08002349 if (immune_spaces_.ContainsObject(from_ref)) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002350 // An immune object is alive.
2351 to_ref = from_ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002352 } else {
2353 // Non-immune non-moving space. Use the mark bitmap.
2354 accounting::ContinuousSpaceBitmap* mark_bitmap =
2355 heap_mark_bitmap_->GetContinuousSpaceBitmap(from_ref);
2356 accounting::LargeObjectBitmap* los_bitmap =
2357 heap_mark_bitmap_->GetLargeObjectBitmap(from_ref);
2358 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
2359 bool is_los = mark_bitmap == nullptr;
2360 if (!is_los && mark_bitmap->Test(from_ref)) {
2361 // Already marked.
2362 to_ref = from_ref;
2363 } else if (is_los && los_bitmap->Test(from_ref)) {
2364 // Already marked in LOS.
2365 to_ref = from_ref;
2366 } else {
2367 // Not marked.
2368 if (IsOnAllocStack(from_ref)) {
2369 // If on the allocation stack, it's considered marked.
2370 to_ref = from_ref;
2371 } else {
2372 // Not marked.
2373 to_ref = nullptr;
2374 }
2375 }
2376 }
2377 }
2378 return to_ref;
2379}
2380
2381bool ConcurrentCopying::IsOnAllocStack(mirror::Object* ref) {
2382 QuasiAtomic::ThreadFenceAcquire();
2383 accounting::ObjectStack* alloc_stack = GetAllocationStack();
Mathieu Chartiercb535da2015-01-23 13:50:03 -08002384 return alloc_stack->Contains(ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002385}
2386
Mathieu Chartier1ca68902017-04-18 11:26:22 -07002387mirror::Object* ConcurrentCopying::MarkNonMoving(mirror::Object* ref,
2388 mirror::Object* holder,
2389 MemberOffset offset) {
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002390 // ref is in a non-moving space (from_ref == to_ref).
2391 DCHECK(!region_space_->HasAddress(ref)) << ref;
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002392 DCHECK(!immune_spaces_.ContainsObject(ref));
2393 // Use the mark bitmap.
2394 accounting::ContinuousSpaceBitmap* mark_bitmap =
2395 heap_mark_bitmap_->GetContinuousSpaceBitmap(ref);
2396 accounting::LargeObjectBitmap* los_bitmap =
2397 heap_mark_bitmap_->GetLargeObjectBitmap(ref);
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002398 bool is_los = mark_bitmap == nullptr;
2399 if (!is_los && mark_bitmap->Test(ref)) {
2400 // Already marked.
2401 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002402 DCHECK(ref->GetReadBarrierState() == ReadBarrier::GrayState() ||
2403 ref->GetReadBarrierState() == ReadBarrier::WhiteState());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002404 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002405 } else if (is_los && los_bitmap->Test(ref)) {
2406 // Already marked in LOS.
2407 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002408 DCHECK(ref->GetReadBarrierState() == ReadBarrier::GrayState() ||
2409 ref->GetReadBarrierState() == ReadBarrier::WhiteState());
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002410 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002411 } else {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002412 // Not marked.
2413 if (IsOnAllocStack(ref)) {
2414 // If it's on the allocation stack, it's considered marked. Keep it white.
2415 // Objects on the allocation stack need not be marked.
2416 if (!is_los) {
2417 DCHECK(!mark_bitmap->Test(ref));
2418 } else {
2419 DCHECK(!los_bitmap->Test(ref));
Nicolas Geoffrayddeb1722016-06-28 08:25:59 +00002420 }
Nicolas Geoffrayddeb1722016-06-28 08:25:59 +00002421 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002422 DCHECK_EQ(ref->GetReadBarrierState(), ReadBarrier::WhiteState());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002423 }
2424 } else {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002425 // For the baker-style RB, we need to handle 'false-gray' cases. See the
2426 // kRegionTypeUnevacFromSpace-case comment in Mark().
2427 if (kUseBakerReadBarrier) {
2428 // Test the bitmap first to reduce the chance of false gray cases.
2429 if ((!is_los && mark_bitmap->Test(ref)) ||
2430 (is_los && los_bitmap->Test(ref))) {
2431 return ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002432 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002433 }
Mathieu Chartier1ca68902017-04-18 11:26:22 -07002434 if (is_los && !IsAligned<kPageSize>(ref)) {
2435 // Ref is a large object that is not aligned, it must be heap corruption. Dump data before
2436 // AtomicSetReadBarrierState since it will fault if the address is not valid.
Mathieu Chartieref496d92017-04-28 18:58:59 -07002437 heap_->GetVerification()->LogHeapCorruption(holder, offset, ref, /* fatal */ true);
Mathieu Chartier1ca68902017-04-18 11:26:22 -07002438 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002439 // Not marked or on the allocation stack. Try to mark it.
2440 // This may or may not succeed, which is ok.
2441 bool cas_success = false;
2442 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002443 cas_success = ref->AtomicSetReadBarrierState(ReadBarrier::WhiteState(),
2444 ReadBarrier::GrayState());
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002445 }
2446 if (!is_los && mark_bitmap->AtomicTestAndSet(ref)) {
2447 // Already marked.
2448 if (kUseBakerReadBarrier && cas_success &&
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002449 ref->GetReadBarrierState() == ReadBarrier::GrayState()) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002450 PushOntoFalseGrayStack(ref);
2451 }
2452 } else if (is_los && los_bitmap->AtomicTestAndSet(ref)) {
2453 // Already marked in LOS.
2454 if (kUseBakerReadBarrier && cas_success &&
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002455 ref->GetReadBarrierState() == ReadBarrier::GrayState()) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002456 PushOntoFalseGrayStack(ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002457 }
2458 } else {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002459 // Newly marked.
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08002460 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002461 DCHECK_EQ(ref->GetReadBarrierState(), ReadBarrier::GrayState());
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08002462 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002463 PushOntoMarkStack(ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002464 }
2465 }
2466 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002467 return ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002468}
2469
2470void ConcurrentCopying::FinishPhase() {
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -08002471 Thread* const self = Thread::Current();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002472 {
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -08002473 MutexLock mu(self, mark_stack_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002474 CHECK_EQ(pooled_mark_stacks_.size(), kMarkStackPoolSize);
2475 }
Mathieu Chartiera1467d02017-02-22 09:22:50 -08002476 // kVerifyNoMissingCardMarks relies on the region space cards not being cleared to avoid false
2477 // positives.
2478 if (!kVerifyNoMissingCardMarks) {
Mathieu Chartier6e6078a2016-10-24 15:45:41 -07002479 TimingLogger::ScopedTiming split("ClearRegionSpaceCards", GetTimings());
2480 // We do not currently use the region space cards at all, madvise them away to save ram.
2481 heap_->GetCardTable()->ClearCardRange(region_space_->Begin(), region_space_->Limit());
Mathieu Chartier6e6078a2016-10-24 15:45:41 -07002482 }
2483 {
2484 MutexLock mu(self, skipped_blocks_lock_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002485 skipped_blocks_map_.clear();
2486 }
Mathieu Chartier56fe2582016-07-14 13:30:03 -07002487 {
2488 ReaderMutexLock mu(self, *Locks::mutator_lock_);
Mathieu Chartier21328a12016-07-22 10:47:45 -07002489 {
2490 WriterMutexLock mu2(self, *Locks::heap_bitmap_lock_);
2491 heap_->ClearMarkedObjects();
2492 }
2493 if (kUseBakerReadBarrier && kFilterModUnionCards) {
2494 TimingLogger::ScopedTiming split("FilterModUnionCards", GetTimings());
2495 ReaderMutexLock mu2(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier21328a12016-07-22 10:47:45 -07002496 for (space::ContinuousSpace* space : immune_spaces_.GetSpaces()) {
2497 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
Mathieu Chartier6e6078a2016-10-24 15:45:41 -07002498 accounting::ModUnionTable* table = heap_->FindModUnionTableFromSpace(space);
Mathieu Chartier21328a12016-07-22 10:47:45 -07002499 // Filter out cards that don't need to be set.
2500 if (table != nullptr) {
2501 table->FilterCards();
2502 }
2503 }
2504 }
Mathieu Chartier36a270a2016-07-28 18:08:51 -07002505 if (kUseBakerReadBarrier) {
2506 TimingLogger::ScopedTiming split("EmptyRBMarkBitStack", GetTimings());
Mathieu Chartier6e6078a2016-10-24 15:45:41 -07002507 DCHECK(rb_mark_bit_stack_ != nullptr);
Mathieu Chartier36a270a2016-07-28 18:08:51 -07002508 const auto* limit = rb_mark_bit_stack_->End();
2509 for (StackReference<mirror::Object>* it = rb_mark_bit_stack_->Begin(); it != limit; ++it) {
2510 CHECK(it->AsMirrorPtr()->AtomicSetMarkBit(1, 0));
2511 }
2512 rb_mark_bit_stack_->Reset();
2513 }
Mathieu Chartier56fe2582016-07-14 13:30:03 -07002514 }
2515 if (measure_read_barrier_slow_path_) {
2516 MutexLock mu(self, rb_slow_path_histogram_lock_);
2517 rb_slow_path_time_histogram_.AdjustAndAddValue(rb_slow_path_ns_.LoadRelaxed());
2518 rb_slow_path_count_total_ += rb_slow_path_count_.LoadRelaxed();
2519 rb_slow_path_count_gc_total_ += rb_slow_path_count_gc_.LoadRelaxed();
2520 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002521}
2522
Hiroshi Yamauchi65f5f242016-12-19 11:44:47 -08002523bool ConcurrentCopying::IsNullOrMarkedHeapReference(mirror::HeapReference<mirror::Object>* field,
2524 bool do_atomic_update) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002525 mirror::Object* from_ref = field->AsMirrorPtr();
Hiroshi Yamauchi65f5f242016-12-19 11:44:47 -08002526 if (from_ref == nullptr) {
2527 return true;
2528 }
Mathieu Chartier97509952015-07-13 14:35:43 -07002529 mirror::Object* to_ref = IsMarked(from_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002530 if (to_ref == nullptr) {
2531 return false;
2532 }
2533 if (from_ref != to_ref) {
Hiroshi Yamauchi65f5f242016-12-19 11:44:47 -08002534 if (do_atomic_update) {
2535 do {
2536 if (field->AsMirrorPtr() != from_ref) {
2537 // Concurrently overwritten by a mutator.
2538 break;
2539 }
2540 } while (!field->CasWeakRelaxed(from_ref, to_ref));
2541 } else {
2542 QuasiAtomic::ThreadFenceRelease();
2543 field->Assign(to_ref);
2544 QuasiAtomic::ThreadFenceSequentiallyConsistent();
2545 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002546 }
2547 return true;
2548}
2549
Mathieu Chartier97509952015-07-13 14:35:43 -07002550mirror::Object* ConcurrentCopying::MarkObject(mirror::Object* from_ref) {
2551 return Mark(from_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002552}
2553
Mathieu Chartier31e88222016-10-14 18:43:19 -07002554void ConcurrentCopying::DelayReferenceReferent(ObjPtr<mirror::Class> klass,
2555 ObjPtr<mirror::Reference> reference) {
Mathieu Chartier97509952015-07-13 14:35:43 -07002556 heap_->GetReferenceProcessor()->DelayReferenceReferent(klass, reference, this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002557}
2558
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002559void ConcurrentCopying::ProcessReferences(Thread* self) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002560 TimingLogger::ScopedTiming split("ProcessReferences", GetTimings());
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002561 // 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 -08002562 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
2563 GetHeap()->GetReferenceProcessor()->ProcessReferences(
Mathieu Chartier97509952015-07-13 14:35:43 -07002564 true /*concurrent*/, GetTimings(), GetCurrentIteration()->GetClearSoftReferences(), this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002565}
2566
2567void ConcurrentCopying::RevokeAllThreadLocalBuffers() {
2568 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
2569 region_space_->RevokeAllThreadLocalBuffers();
2570}
2571
Mathieu Chartier56fe2582016-07-14 13:30:03 -07002572mirror::Object* ConcurrentCopying::MarkFromReadBarrierWithMeasurements(mirror::Object* from_ref) {
2573 if (Thread::Current() != thread_running_gc_) {
2574 rb_slow_path_count_.FetchAndAddRelaxed(1u);
2575 } else {
2576 rb_slow_path_count_gc_.FetchAndAddRelaxed(1u);
2577 }
2578 ScopedTrace tr(__FUNCTION__);
2579 const uint64_t start_time = measure_read_barrier_slow_path_ ? NanoTime() : 0u;
2580 mirror::Object* ret = Mark(from_ref);
2581 if (measure_read_barrier_slow_path_) {
2582 rb_slow_path_ns_.FetchAndAddRelaxed(NanoTime() - start_time);
2583 }
2584 return ret;
2585}
2586
2587void ConcurrentCopying::DumpPerformanceInfo(std::ostream& os) {
2588 GarbageCollector::DumpPerformanceInfo(os);
2589 MutexLock mu(Thread::Current(), rb_slow_path_histogram_lock_);
2590 if (rb_slow_path_time_histogram_.SampleSize() > 0) {
2591 Histogram<uint64_t>::CumulativeData cumulative_data;
2592 rb_slow_path_time_histogram_.CreateHistogram(&cumulative_data);
2593 rb_slow_path_time_histogram_.PrintConfidenceIntervals(os, 0.99, cumulative_data);
2594 }
2595 if (rb_slow_path_count_total_ > 0) {
2596 os << "Slow path count " << rb_slow_path_count_total_ << "\n";
2597 }
2598 if (rb_slow_path_count_gc_total_ > 0) {
2599 os << "GC slow path count " << rb_slow_path_count_gc_total_ << "\n";
2600 }
Mathieu Chartiercca44a02016-08-17 10:07:29 -07002601 os << "Cumulative bytes moved " << cumulative_bytes_moved_.LoadRelaxed() << "\n";
2602 os << "Cumulative objects moved " << cumulative_objects_moved_.LoadRelaxed() << "\n";
Mathieu Chartier56fe2582016-07-14 13:30:03 -07002603}
2604
Hiroshi Yamauchid5307ec2014-03-27 21:07:51 -07002605} // namespace collector
2606} // namespace gc
2607} // namespace art