blob: ab8942a4b8c1f4b96521681e0d6ecfc2cd560a2c [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"
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080025#include "gc/accounting/heap_bitmap-inl.h"
Mathieu Chartier21328a12016-07-22 10:47:45 -070026#include "gc/accounting/mod_union_table-inl.h"
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080027#include "gc/accounting/space_bitmap-inl.h"
Mathieu Chartier3cf22532015-07-09 15:15:09 -070028#include "gc/reference_processor.h"
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080029#include "gc/space/image_space.h"
Mathieu Chartier073b16c2015-11-10 14:13:23 -080030#include "gc/space/space-inl.h"
Mathieu Chartier4a26f172016-01-26 14:26:18 -080031#include "image-inl.h"
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080032#include "intern_table.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070033#include "mirror/class-inl.h"
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080034#include "mirror/object-inl.h"
35#include "scoped_thread_state_change.h"
36#include "thread-inl.h"
37#include "thread_list.h"
38#include "well_known_classes.h"
39
Hiroshi Yamauchid5307ec2014-03-27 21:07:51 -070040namespace art {
41namespace gc {
42namespace collector {
43
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -070044static constexpr size_t kDefaultGcMarkStackSize = 2 * MB;
Mathieu Chartier21328a12016-07-22 10:47:45 -070045// If kFilterModUnionCards then we attempt to filter cards that don't need to be dirty in the mod
46// union table. Disabled since it does not seem to help the pause much.
47static constexpr bool kFilterModUnionCards = kIsDebugBuild;
Mathieu Chartierd6636d32016-07-28 11:02:38 -070048// If kDisallowReadBarrierDuringScan is true then the GC aborts if there are any that occur during
49// ConcurrentCopying::Scan. May be used to diagnose possibly unnecessary read barriers.
50// Only enabled for kIsDebugBuild to avoid performance hit.
51static constexpr bool kDisallowReadBarrierDuringScan = kIsDebugBuild;
Mathieu Chartier36a270a2016-07-28 18:08:51 -070052// Slow path mark stack size, increase this if the stack is getting full and it is causing
53// performance problems.
54static constexpr size_t kReadBarrierMarkStackSize = 512 * KB;
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -070055
Mathieu Chartier56fe2582016-07-14 13:30:03 -070056ConcurrentCopying::ConcurrentCopying(Heap* heap,
57 const std::string& name_prefix,
58 bool measure_read_barrier_slow_path)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080059 : GarbageCollector(heap,
60 name_prefix + (name_prefix.empty() ? "" : " ") +
61 "concurrent copying + mark sweep"),
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070062 region_space_(nullptr), gc_barrier_(new Barrier(0)),
63 gc_mark_stack_(accounting::ObjectStack::Create("concurrent copying gc mark stack",
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -070064 kDefaultGcMarkStackSize,
65 kDefaultGcMarkStackSize)),
Mathieu Chartier36a270a2016-07-28 18:08:51 -070066 rb_mark_bit_stack_(accounting::ObjectStack::Create("rb copying gc mark stack",
67 kReadBarrierMarkStackSize,
68 kReadBarrierMarkStackSize)),
69 rb_mark_bit_stack_full_(false),
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070070 mark_stack_lock_("concurrent copying mark stack lock", kMarkSweepMarkStackLock),
71 thread_running_gc_(nullptr),
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080072 is_marking_(false), is_active_(false), is_asserting_to_space_invariant_(false),
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -070073 region_space_bitmap_(nullptr),
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070074 heap_mark_bitmap_(nullptr), live_stack_freeze_size_(0), mark_stack_mode_(kMarkStackModeOff),
75 weak_ref_access_enabled_(true),
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080076 skipped_blocks_lock_("concurrent copying bytes blocks lock", kMarkSweepMarkStackLock),
Mathieu Chartier56fe2582016-07-14 13:30:03 -070077 measure_read_barrier_slow_path_(measure_read_barrier_slow_path),
78 rb_slow_path_ns_(0),
79 rb_slow_path_count_(0),
80 rb_slow_path_count_gc_(0),
81 rb_slow_path_histogram_lock_("Read barrier histogram lock"),
82 rb_slow_path_time_histogram_("Mutator time in read barrier slow path", 500, 32),
83 rb_slow_path_count_total_(0),
84 rb_slow_path_count_gc_total_(0),
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080085 rb_table_(heap_->GetReadBarrierTable()),
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -070086 force_evacuate_all_(false),
87 immune_gray_stack_lock_("concurrent copying immune gray stack lock",
88 kMarkSweepMarkStackLock) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080089 static_assert(space::RegionSpace::kRegionSize == accounting::ReadBarrierTable::kRegionSize,
90 "The region space size and the read barrier table region size must match");
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070091 Thread* self = Thread::Current();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080092 {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080093 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
94 // Cache this so that we won't have to lock heap_bitmap_lock_ in
95 // Mark() which could cause a nested lock on heap_bitmap_lock_
96 // when GC causes a RB while doing GC or a lock order violation
97 // (class_linker_lock_ and heap_bitmap_lock_).
98 heap_mark_bitmap_ = heap->GetMarkBitmap();
99 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700100 {
101 MutexLock mu(self, mark_stack_lock_);
102 for (size_t i = 0; i < kMarkStackPoolSize; ++i) {
103 accounting::AtomicStack<mirror::Object>* mark_stack =
104 accounting::AtomicStack<mirror::Object>::Create(
105 "thread local mark stack", kMarkStackSize, kMarkStackSize);
106 pooled_mark_stacks_.push_back(mark_stack);
107 }
108 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800109}
110
Mathieu Chartierb19ccb12015-07-15 10:24:16 -0700111void ConcurrentCopying::MarkHeapReference(mirror::HeapReference<mirror::Object>* from_ref) {
112 // Used for preserving soft references, should be OK to not have a CAS here since there should be
113 // no other threads which can trigger read barriers on the same referent during reference
114 // processing.
115 from_ref->Assign(Mark(from_ref->AsMirrorPtr()));
Mathieu Chartier81187812015-07-15 14:24:07 -0700116 DCHECK(!from_ref->IsNull());
Mathieu Chartier97509952015-07-13 14:35:43 -0700117}
118
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800119ConcurrentCopying::~ConcurrentCopying() {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700120 STLDeleteElements(&pooled_mark_stacks_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800121}
122
123void ConcurrentCopying::RunPhases() {
124 CHECK(kUseBakerReadBarrier || kUseTableLookupReadBarrier);
125 CHECK(!is_active_);
126 is_active_ = true;
127 Thread* self = Thread::Current();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700128 thread_running_gc_ = self;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800129 Locks::mutator_lock_->AssertNotHeld(self);
130 {
131 ReaderMutexLock mu(self, *Locks::mutator_lock_);
132 InitializePhase();
133 }
134 FlipThreadRoots();
135 {
136 ReaderMutexLock mu(self, *Locks::mutator_lock_);
137 MarkingPhase();
138 }
139 // Verify no from space refs. This causes a pause.
140 if (kEnableNoFromSpaceRefsVerification || kIsDebugBuild) {
141 TimingLogger::ScopedTiming split("(Paused)VerifyNoFromSpaceReferences", GetTimings());
142 ScopedPause pause(this);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700143 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800144 if (kVerboseMode) {
145 LOG(INFO) << "Verifying no from-space refs";
146 }
147 VerifyNoFromSpaceReferences();
Mathieu Chartier720e71a2015-04-06 17:10:58 -0700148 if (kVerboseMode) {
149 LOG(INFO) << "Done verifying no from-space refs";
150 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700151 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800152 }
153 {
154 ReaderMutexLock mu(self, *Locks::mutator_lock_);
155 ReclaimPhase();
156 }
157 FinishPhase();
158 CHECK(is_active_);
159 is_active_ = false;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700160 thread_running_gc_ = nullptr;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800161}
162
163void ConcurrentCopying::BindBitmaps() {
164 Thread* self = Thread::Current();
165 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
166 // Mark all of the spaces we never collect as immune.
167 for (const auto& space : heap_->GetContinuousSpaces()) {
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800168 if (space->GetGcRetentionPolicy() == space::kGcRetentionPolicyNeverCollect ||
169 space->GetGcRetentionPolicy() == space::kGcRetentionPolicyFullCollect) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800170 CHECK(space->IsZygoteSpace() || space->IsImageSpace());
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800171 immune_spaces_.AddSpace(space);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800172 } else if (space == region_space_) {
173 accounting::ContinuousSpaceBitmap* bitmap =
174 accounting::ContinuousSpaceBitmap::Create("cc region space bitmap",
175 space->Begin(), space->Capacity());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800176 region_space_bitmap_ = bitmap;
177 }
178 }
179}
180
181void ConcurrentCopying::InitializePhase() {
182 TimingLogger::ScopedTiming split("InitializePhase", GetTimings());
183 if (kVerboseMode) {
184 LOG(INFO) << "GC InitializePhase";
185 LOG(INFO) << "Region-space : " << reinterpret_cast<void*>(region_space_->Begin()) << "-"
186 << reinterpret_cast<void*>(region_space_->Limit());
187 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700188 CheckEmptyMarkStack();
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800189 if (kIsDebugBuild) {
190 MutexLock mu(Thread::Current(), mark_stack_lock_);
191 CHECK(false_gray_stack_.empty());
192 }
Mathieu Chartier56fe2582016-07-14 13:30:03 -0700193
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700194 rb_mark_bit_stack_full_ = false;
Mathieu Chartier56fe2582016-07-14 13:30:03 -0700195 mark_from_read_barrier_measurements_ = measure_read_barrier_slow_path_;
196 if (measure_read_barrier_slow_path_) {
197 rb_slow_path_ns_.StoreRelaxed(0);
198 rb_slow_path_count_.StoreRelaxed(0);
199 rb_slow_path_count_gc_.StoreRelaxed(0);
200 }
201
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800202 immune_spaces_.Reset();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800203 bytes_moved_.StoreRelaxed(0);
204 objects_moved_.StoreRelaxed(0);
Hiroshi Yamauchi60985b72016-08-24 13:53:12 -0700205 GcCause gc_cause = GetCurrentIteration()->GetGcCause();
206 if (gc_cause == kGcCauseExplicit ||
207 gc_cause == kGcCauseForNativeAlloc ||
208 gc_cause == kGcCauseCollectorTransition ||
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800209 GetCurrentIteration()->GetClearSoftReferences()) {
210 force_evacuate_all_ = true;
211 } else {
212 force_evacuate_all_ = false;
213 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700214 if (kUseBakerReadBarrier) {
215 updated_all_immune_objects_.StoreRelaxed(false);
216 // GC may gray immune objects in the thread flip.
217 gc_grays_immune_objects_ = true;
218 if (kIsDebugBuild) {
219 MutexLock mu(Thread::Current(), immune_gray_stack_lock_);
220 DCHECK(immune_gray_stack_.empty());
221 }
222 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800223 BindBitmaps();
224 if (kVerboseMode) {
225 LOG(INFO) << "force_evacuate_all=" << force_evacuate_all_;
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800226 LOG(INFO) << "Largest immune region: " << immune_spaces_.GetLargestImmuneRegion().Begin()
227 << "-" << immune_spaces_.GetLargestImmuneRegion().End();
228 for (space::ContinuousSpace* space : immune_spaces_.GetSpaces()) {
229 LOG(INFO) << "Immune space: " << *space;
230 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800231 LOG(INFO) << "GC end of InitializePhase";
232 }
Mathieu Chartier962cd7a2016-08-16 12:15:59 -0700233 // Mark all of the zygote large objects without graying them.
234 MarkZygoteLargeObjects();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800235}
236
237// Used to switch the thread roots of a thread from from-space refs to to-space refs.
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700238class ConcurrentCopying::ThreadFlipVisitor : public Closure, public RootVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800239 public:
Roland Levillain3887c462015-08-12 18:15:42 +0100240 ThreadFlipVisitor(ConcurrentCopying* concurrent_copying, bool use_tlab)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800241 : concurrent_copying_(concurrent_copying), use_tlab_(use_tlab) {
242 }
243
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700244 virtual void Run(Thread* thread) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800245 // Note: self is not necessarily equal to thread since thread may be suspended.
246 Thread* self = Thread::Current();
247 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
248 << thread->GetState() << " thread " << thread << " self " << self;
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700249 thread->SetIsGcMarking(true);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800250 if (use_tlab_ && thread->HasTlab()) {
251 if (ConcurrentCopying::kEnableFromSpaceAccountingCheck) {
252 // This must come before the revoke.
253 size_t thread_local_objects = thread->GetThreadLocalObjectsAllocated();
254 concurrent_copying_->region_space_->RevokeThreadLocalBuffers(thread);
255 reinterpret_cast<Atomic<size_t>*>(&concurrent_copying_->from_space_num_objects_at_first_pause_)->
256 FetchAndAddSequentiallyConsistent(thread_local_objects);
257 } else {
258 concurrent_copying_->region_space_->RevokeThreadLocalBuffers(thread);
259 }
260 }
261 if (kUseThreadLocalAllocationStack) {
262 thread->RevokeThreadLocalAllocationStack();
263 }
264 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700265 // We can use the non-CAS VisitRoots functions below because we update thread-local GC roots
266 // only.
267 thread->VisitRoots(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800268 concurrent_copying_->GetBarrier().Pass(self);
269 }
270
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700271 void VisitRoots(mirror::Object*** roots,
272 size_t count,
273 const RootInfo& info ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700274 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700275 for (size_t i = 0; i < count; ++i) {
276 mirror::Object** root = roots[i];
277 mirror::Object* ref = *root;
278 if (ref != nullptr) {
279 mirror::Object* to_ref = concurrent_copying_->Mark(ref);
280 if (to_ref != ref) {
281 *root = to_ref;
282 }
283 }
284 }
285 }
286
287 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots,
288 size_t count,
289 const RootInfo& info ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700290 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700291 for (size_t i = 0; i < count; ++i) {
292 mirror::CompressedReference<mirror::Object>* const root = roots[i];
293 if (!root->IsNull()) {
294 mirror::Object* ref = root->AsMirrorPtr();
295 mirror::Object* to_ref = concurrent_copying_->Mark(ref);
296 if (to_ref != ref) {
297 root->Assign(to_ref);
298 }
299 }
300 }
301 }
302
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800303 private:
304 ConcurrentCopying* const concurrent_copying_;
305 const bool use_tlab_;
306};
307
308// Called back from Runtime::FlipThreadRoots() during a pause.
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700309class ConcurrentCopying::FlipCallback : public Closure {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800310 public:
311 explicit FlipCallback(ConcurrentCopying* concurrent_copying)
312 : concurrent_copying_(concurrent_copying) {
313 }
314
Mathieu Chartier90443472015-07-16 20:32:27 -0700315 virtual void Run(Thread* thread) OVERRIDE REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800316 ConcurrentCopying* cc = concurrent_copying_;
317 TimingLogger::ScopedTiming split("(Paused)FlipCallback", cc->GetTimings());
318 // Note: self is not necessarily equal to thread since thread may be suspended.
319 Thread* self = Thread::Current();
320 CHECK(thread == self);
321 Locks::mutator_lock_->AssertExclusiveHeld(self);
322 cc->region_space_->SetFromSpace(cc->rb_table_, cc->force_evacuate_all_);
Mathieu Chartiera4f6af92015-08-11 17:35:25 -0700323 cc->SwapStacks();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800324 if (ConcurrentCopying::kEnableFromSpaceAccountingCheck) {
325 cc->RecordLiveStackFreezeSize(self);
326 cc->from_space_num_objects_at_first_pause_ = cc->region_space_->GetObjectsAllocated();
327 cc->from_space_num_bytes_at_first_pause_ = cc->region_space_->GetBytesAllocated();
328 }
329 cc->is_marking_ = true;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700330 cc->mark_stack_mode_.StoreRelaxed(ConcurrentCopying::kMarkStackModeThreadLocal);
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800331 if (kIsDebugBuild) {
332 cc->region_space_->AssertAllRegionLiveBytesZeroOrCleared();
333 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800334 if (UNLIKELY(Runtime::Current()->IsActiveTransaction())) {
Mathieu Chartier184c9dc2015-03-05 13:20:54 -0800335 CHECK(Runtime::Current()->IsAotCompiler());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800336 TimingLogger::ScopedTiming split2("(Paused)VisitTransactionRoots", cc->GetTimings());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700337 Runtime::Current()->VisitTransactionRoots(cc);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800338 }
Mathieu Chartier21328a12016-07-22 10:47:45 -0700339 if (kUseBakerReadBarrier && kGrayDirtyImmuneObjects) {
340 cc->GrayAllDirtyImmuneObjects();
341 if (kIsDebugBuild) {
342 // Check that all non-gray immune objects only refernce immune objects.
343 cc->VerifyGrayImmuneObjects();
344 }
345 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800346 }
347
348 private:
349 ConcurrentCopying* const concurrent_copying_;
350};
351
Mathieu Chartier21328a12016-07-22 10:47:45 -0700352class ConcurrentCopying::VerifyGrayImmuneObjectsVisitor {
353 public:
354 explicit VerifyGrayImmuneObjectsVisitor(ConcurrentCopying* collector)
355 : collector_(collector) {}
356
357 void operator()(mirror::Object* obj, MemberOffset offset, bool /* is_static */)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700358 const ALWAYS_INLINE REQUIRES_SHARED(Locks::mutator_lock_)
359 REQUIRES_SHARED(Locks::heap_bitmap_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700360 CheckReference(obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(offset),
361 obj, offset);
362 }
363
364 void operator()(mirror::Class* klass, mirror::Reference* ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700365 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700366 CHECK(klass->IsTypeOfReferenceClass());
367 CheckReference(ref->GetReferent<kWithoutReadBarrier>(),
368 ref,
369 mirror::Reference::ReferentOffset());
370 }
371
372 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
373 ALWAYS_INLINE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700374 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700375 if (!root->IsNull()) {
376 VisitRoot(root);
377 }
378 }
379
380 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
381 ALWAYS_INLINE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700382 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700383 CheckReference(root->AsMirrorPtr(), nullptr, MemberOffset(0));
384 }
385
386 private:
387 ConcurrentCopying* const collector_;
388
389 void CheckReference(mirror::Object* ref, mirror::Object* holder, MemberOffset offset) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700390 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700391 if (ref != nullptr) {
Mathieu Chartier962cd7a2016-08-16 12:15:59 -0700392 if (!collector_->immune_spaces_.ContainsObject(ref)) {
393 // Not immune, must be a zygote large object.
394 CHECK(Runtime::Current()->GetHeap()->GetLargeObjectsSpace()->IsZygoteLargeObject(
395 Thread::Current(), ref))
396 << "Non gray object references non immune, non zygote large object "<< ref << " "
397 << PrettyTypeOf(ref) << " in holder " << holder << " " << PrettyTypeOf(holder)
398 << " offset=" << offset.Uint32Value();
399 } else {
400 // Make sure the large object class is immune since we will never scan the large object.
401 CHECK(collector_->immune_spaces_.ContainsObject(
402 ref->GetClass<kVerifyNone, kWithoutReadBarrier>()));
403 }
Mathieu Chartier21328a12016-07-22 10:47:45 -0700404 }
405 }
406};
407
408void ConcurrentCopying::VerifyGrayImmuneObjects() {
409 TimingLogger::ScopedTiming split(__FUNCTION__, GetTimings());
410 for (auto& space : immune_spaces_.GetSpaces()) {
411 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
412 accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
413 VerifyGrayImmuneObjectsVisitor visitor(this);
414 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()),
415 reinterpret_cast<uintptr_t>(space->Limit()),
416 [&visitor](mirror::Object* obj)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700417 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700418 // If an object is not gray, it should only have references to things in the immune spaces.
419 if (obj->GetReadBarrierPointer() != ReadBarrier::GrayPtr()) {
420 obj->VisitReferences</*kVisitNativeRoots*/true,
421 kDefaultVerifyFlags,
422 kWithoutReadBarrier>(visitor, visitor);
423 }
424 });
425 }
426}
427
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800428// Switch threads that from from-space to to-space refs. Forward/mark the thread roots.
429void ConcurrentCopying::FlipThreadRoots() {
430 TimingLogger::ScopedTiming split("FlipThreadRoots", GetTimings());
431 if (kVerboseMode) {
432 LOG(INFO) << "time=" << region_space_->Time();
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700433 region_space_->DumpNonFreeRegions(LOG_STREAM(INFO));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800434 }
435 Thread* self = Thread::Current();
436 Locks::mutator_lock_->AssertNotHeld(self);
437 gc_barrier_->Init(self, 0);
438 ThreadFlipVisitor thread_flip_visitor(this, heap_->use_tlab_);
439 FlipCallback flip_callback(this);
440 size_t barrier_count = Runtime::Current()->FlipThreadRoots(
441 &thread_flip_visitor, &flip_callback, this);
442 {
443 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
444 gc_barrier_->Increment(self, barrier_count);
445 }
446 is_asserting_to_space_invariant_ = true;
447 QuasiAtomic::ThreadFenceForConstructor();
448 if (kVerboseMode) {
449 LOG(INFO) << "time=" << region_space_->Time();
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700450 region_space_->DumpNonFreeRegions(LOG_STREAM(INFO));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800451 LOG(INFO) << "GC end of FlipThreadRoots";
452 }
453}
454
Mathieu Chartier21328a12016-07-22 10:47:45 -0700455class ConcurrentCopying::GrayImmuneObjectVisitor {
456 public:
457 explicit GrayImmuneObjectVisitor() {}
458
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700459 ALWAYS_INLINE void operator()(mirror::Object* obj) const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700460 if (kUseBakerReadBarrier) {
461 if (kIsDebugBuild) {
462 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
463 }
464 obj->SetReadBarrierPointer(ReadBarrier::GrayPtr());
465 }
466 }
467
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700468 static void Callback(mirror::Object* obj, void* arg) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700469 reinterpret_cast<GrayImmuneObjectVisitor*>(arg)->operator()(obj);
470 }
471};
472
473void ConcurrentCopying::GrayAllDirtyImmuneObjects() {
474 TimingLogger::ScopedTiming split(__FUNCTION__, GetTimings());
475 gc::Heap* const heap = Runtime::Current()->GetHeap();
476 accounting::CardTable* const card_table = heap->GetCardTable();
477 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
478 for (space::ContinuousSpace* space : immune_spaces_.GetSpaces()) {
479 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
480 GrayImmuneObjectVisitor visitor;
481 accounting::ModUnionTable* table = heap->FindModUnionTableFromSpace(space);
482 // Mark all the objects on dirty cards since these may point to objects in other space.
483 // Once these are marked, the GC will eventually clear them later.
484 // Table is non null for boot image and zygote spaces. It is only null for application image
485 // spaces.
486 if (table != nullptr) {
487 // TODO: Add preclean outside the pause.
488 table->ClearCards();
489 table->VisitObjects(GrayImmuneObjectVisitor::Callback, &visitor);
490 } else {
491 // TODO: Consider having a mark bitmap for app image spaces and avoid scanning during the
492 // pause because app image spaces are all dirty pages anyways.
493 card_table->Scan<false>(space->GetMarkBitmap(), space->Begin(), space->End(), visitor);
494 }
495 }
496 // Since all of the objects that may point to other spaces are marked, we can avoid all the read
497 // barriers in the immune spaces.
498 updated_all_immune_objects_.StoreRelaxed(true);
499}
500
Mathieu Chartiera4f6af92015-08-11 17:35:25 -0700501void ConcurrentCopying::SwapStacks() {
502 heap_->SwapStacks();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800503}
504
505void ConcurrentCopying::RecordLiveStackFreezeSize(Thread* self) {
506 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
507 live_stack_freeze_size_ = heap_->GetLiveStack()->Size();
508}
509
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800510class EmptyCheckpoint : public Closure {
511 public:
512 explicit EmptyCheckpoint(ConcurrentCopying* concurrent_copying)
513 : concurrent_copying_(concurrent_copying) {
514 }
515
516 virtual void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
517 // Note: self is not necessarily equal to thread since thread may be suspended.
518 Thread* self = Thread::Current();
519 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
520 << thread->GetState() << " thread " << thread << " self " << self;
Lei Lidd9943d2015-02-02 14:24:44 +0800521 // If thread is a running mutator, then act on behalf of the garbage collector.
522 // See the code in ThreadList::RunCheckpoint.
Mathieu Chartier10d25082015-10-28 18:36:09 -0700523 concurrent_copying_->GetBarrier().Pass(self);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800524 }
525
526 private:
527 ConcurrentCopying* const concurrent_copying_;
528};
529
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700530// Used to visit objects in the immune spaces.
531inline void ConcurrentCopying::ScanImmuneObject(mirror::Object* obj) {
532 DCHECK(obj != nullptr);
533 DCHECK(immune_spaces_.ContainsObject(obj));
534 // Update the fields without graying it or pushing it onto the mark stack.
535 Scan(obj);
536}
537
538class ConcurrentCopying::ImmuneSpaceScanObjVisitor {
539 public:
540 explicit ImmuneSpaceScanObjVisitor(ConcurrentCopying* cc)
541 : collector_(cc) {}
542
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700543 ALWAYS_INLINE void operator()(mirror::Object* obj) const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700544 if (kUseBakerReadBarrier && kGrayDirtyImmuneObjects) {
545 if (obj->GetReadBarrierPointer() == ReadBarrier::GrayPtr()) {
546 collector_->ScanImmuneObject(obj);
547 // Done scanning the object, go back to white.
548 bool success = obj->AtomicSetReadBarrierPointer(ReadBarrier::GrayPtr(),
549 ReadBarrier::WhitePtr());
550 CHECK(success);
551 }
552 } else {
553 collector_->ScanImmuneObject(obj);
554 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700555 }
556
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700557 static void Callback(mirror::Object* obj, void* arg) REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi5408f232016-07-29 15:07:05 -0700558 reinterpret_cast<ImmuneSpaceScanObjVisitor*>(arg)->operator()(obj);
559 }
560
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700561 private:
562 ConcurrentCopying* const collector_;
563};
564
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800565// Concurrently mark roots that are guarded by read barriers and process the mark stack.
566void ConcurrentCopying::MarkingPhase() {
567 TimingLogger::ScopedTiming split("MarkingPhase", GetTimings());
568 if (kVerboseMode) {
569 LOG(INFO) << "GC MarkingPhase";
570 }
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -0700571 Thread* self = Thread::Current();
572 if (kIsDebugBuild) {
573 MutexLock mu(self, *Locks::thread_list_lock_);
574 CHECK(weak_ref_access_enabled_);
575 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700576
577 // Scan immune spaces.
578 // Update all the fields in the immune spaces first without graying the objects so that we
579 // minimize dirty pages in the immune spaces. Note mutators can concurrently access and gray some
580 // of the objects.
581 if (kUseBakerReadBarrier) {
582 gc_grays_immune_objects_ = false;
Hiroshi Yamauchi16292fc2016-06-20 20:23:34 -0700583 }
Mathieu Chartier21328a12016-07-22 10:47:45 -0700584 {
585 TimingLogger::ScopedTiming split2("ScanImmuneSpaces", GetTimings());
586 for (auto& space : immune_spaces_.GetSpaces()) {
587 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
588 accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
Hiroshi Yamauchi5408f232016-07-29 15:07:05 -0700589 accounting::ModUnionTable* table = heap_->FindModUnionTableFromSpace(space);
Mathieu Chartier21328a12016-07-22 10:47:45 -0700590 ImmuneSpaceScanObjVisitor visitor(this);
Hiroshi Yamauchi5408f232016-07-29 15:07:05 -0700591 if (kUseBakerReadBarrier && kGrayDirtyImmuneObjects && table != nullptr) {
592 table->VisitObjects(ImmuneSpaceScanObjVisitor::Callback, &visitor);
593 } else {
594 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()),
595 reinterpret_cast<uintptr_t>(space->Limit()),
596 visitor);
597 }
Mathieu Chartier21328a12016-07-22 10:47:45 -0700598 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700599 }
600 if (kUseBakerReadBarrier) {
601 // This release fence makes the field updates in the above loop visible before allowing mutator
602 // getting access to immune objects without graying it first.
603 updated_all_immune_objects_.StoreRelease(true);
604 // Now whiten immune objects concurrently accessed and grayed by mutators. We can't do this in
605 // the above loop because we would incorrectly disable the read barrier by whitening an object
606 // which may point to an unscanned, white object, breaking the to-space invariant.
607 //
608 // Make sure no mutators are in the middle of marking an immune object before whitening immune
609 // objects.
610 IssueEmptyCheckpoint();
611 MutexLock mu(Thread::Current(), immune_gray_stack_lock_);
612 if (kVerboseMode) {
613 LOG(INFO) << "immune gray stack size=" << immune_gray_stack_.size();
614 }
615 for (mirror::Object* obj : immune_gray_stack_) {
616 DCHECK(obj->GetReadBarrierPointer() == ReadBarrier::GrayPtr());
617 bool success = obj->AtomicSetReadBarrierPointer(ReadBarrier::GrayPtr(),
618 ReadBarrier::WhitePtr());
619 DCHECK(success);
620 }
621 immune_gray_stack_.clear();
622 }
623
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800624 {
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -0700625 TimingLogger::ScopedTiming split2("VisitConcurrentRoots", GetTimings());
626 Runtime::Current()->VisitConcurrentRoots(this, kVisitRootFlagAllRoots);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800627 }
628 {
629 // TODO: don't visit the transaction roots if it's not active.
630 TimingLogger::ScopedTiming split5("VisitNonThreadRoots", GetTimings());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700631 Runtime::Current()->VisitNonThreadRoots(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800632 }
633
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800634 {
Mathieu Chartiera6b1ead2015-10-06 10:32:38 -0700635 TimingLogger::ScopedTiming split7("ProcessMarkStack", GetTimings());
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700636 // We transition through three mark stack modes (thread-local, shared, GC-exclusive). The
637 // primary reasons are the fact that we need to use a checkpoint to process thread-local mark
638 // stacks, but after we disable weak refs accesses, we can't use a checkpoint due to a deadlock
639 // issue because running threads potentially blocking at WaitHoldingLocks, and that once we
640 // reach the point where we process weak references, we can avoid using a lock when accessing
641 // the GC mark stack, which makes mark stack processing more efficient.
642
643 // Process the mark stack once in the thread local stack mode. This marks most of the live
644 // objects, aside from weak ref accesses with read barriers (Reference::GetReferent() and system
645 // weaks) that may happen concurrently while we processing the mark stack and newly mark/gray
646 // objects and push refs on the mark stack.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800647 ProcessMarkStack();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700648 // Switch to the shared mark stack mode. That is, revoke and process thread-local mark stacks
649 // for the last time before transitioning to the shared mark stack mode, which would process new
650 // refs that may have been concurrently pushed onto the mark stack during the ProcessMarkStack()
651 // call above. At the same time, disable weak ref accesses using a per-thread flag. It's
652 // important to do these together in a single checkpoint so that we can ensure that mutators
653 // won't newly gray objects and push new refs onto the mark stack due to weak ref accesses and
654 // mutators safely transition to the shared mark stack mode (without leaving unprocessed refs on
655 // the thread-local mark stacks), without a race. This is why we use a thread-local weak ref
656 // access flag Thread::tls32_.weak_ref_access_enabled_ instead of the global ones.
657 SwitchToSharedMarkStackMode();
658 CHECK(!self->GetWeakRefAccessEnabled());
659 // Now that weak refs accesses are disabled, once we exhaust the shared mark stack again here
660 // (which may be non-empty if there were refs found on thread-local mark stacks during the above
661 // SwitchToSharedMarkStackMode() call), we won't have new refs to process, that is, mutators
662 // (via read barriers) have no way to produce any more refs to process. Marking converges once
663 // before we process weak refs below.
664 ProcessMarkStack();
665 CheckEmptyMarkStack();
666 // Switch to the GC exclusive mark stack mode so that we can process the mark stack without a
667 // lock from this point on.
668 SwitchToGcExclusiveMarkStackMode();
669 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800670 if (kVerboseMode) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800671 LOG(INFO) << "ProcessReferences";
672 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700673 // Process weak references. This may produce new refs to process and have them processed via
Mathieu Chartier97509952015-07-13 14:35:43 -0700674 // ProcessMarkStack (in the GC exclusive mark stack mode).
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700675 ProcessReferences(self);
676 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800677 if (kVerboseMode) {
678 LOG(INFO) << "SweepSystemWeaks";
679 }
680 SweepSystemWeaks(self);
681 if (kVerboseMode) {
682 LOG(INFO) << "SweepSystemWeaks done";
683 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700684 // Process the mark stack here one last time because the above SweepSystemWeaks() call may have
685 // marked some objects (strings alive) as hash_set::Erase() can call the hash function for
686 // arbitrary elements in the weak intern table in InternTable::Table::SweepWeaks().
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800687 ProcessMarkStack();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700688 CheckEmptyMarkStack();
689 // Re-enable weak ref accesses.
690 ReenableWeakRefAccess(self);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -0700691 // Free data for class loaders that we unloaded.
692 Runtime::Current()->GetClassLinker()->CleanupClassLoaders();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700693 // Marking is done. Disable marking.
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700694 DisableMarking();
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800695 if (kUseBakerReadBarrier) {
696 ProcessFalseGrayStack();
697 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700698 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800699 }
700
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -0700701 if (kIsDebugBuild) {
702 MutexLock mu(self, *Locks::thread_list_lock_);
703 CHECK(weak_ref_access_enabled_);
704 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800705 if (kVerboseMode) {
706 LOG(INFO) << "GC end of MarkingPhase";
707 }
708}
709
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700710void ConcurrentCopying::ReenableWeakRefAccess(Thread* self) {
711 if (kVerboseMode) {
712 LOG(INFO) << "ReenableWeakRefAccess";
713 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700714 // Iterate all threads (don't need to or can't use a checkpoint) and re-enable weak ref access.
715 {
716 MutexLock mu(self, *Locks::thread_list_lock_);
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -0700717 weak_ref_access_enabled_ = true; // This is for new threads.
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700718 std::list<Thread*> thread_list = Runtime::Current()->GetThreadList()->GetList();
719 for (Thread* thread : thread_list) {
720 thread->SetWeakRefAccessEnabled(true);
721 }
722 }
723 // Unblock blocking threads.
724 GetHeap()->GetReferenceProcessor()->BroadcastForSlowPath(self);
725 Runtime::Current()->BroadcastForNewSystemWeaks();
726}
727
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700728class ConcurrentCopying::DisableMarkingCheckpoint : public Closure {
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700729 public:
730 explicit DisableMarkingCheckpoint(ConcurrentCopying* concurrent_copying)
731 : concurrent_copying_(concurrent_copying) {
732 }
733
734 void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
735 // Note: self is not necessarily equal to thread since thread may be suspended.
736 Thread* self = Thread::Current();
737 DCHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
738 << thread->GetState() << " thread " << thread << " self " << self;
739 // Disable the thread-local is_gc_marking flag.
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -0700740 // Note a thread that has just started right before this checkpoint may have already this flag
741 // set to false, which is ok.
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700742 thread->SetIsGcMarking(false);
743 // If thread is a running mutator, then act on behalf of the garbage collector.
744 // See the code in ThreadList::RunCheckpoint.
Mathieu Chartier10d25082015-10-28 18:36:09 -0700745 concurrent_copying_->GetBarrier().Pass(self);
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700746 }
747
748 private:
749 ConcurrentCopying* const concurrent_copying_;
750};
751
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -0700752class ConcurrentCopying::DisableMarkingCallback : public Closure {
753 public:
754 explicit DisableMarkingCallback(ConcurrentCopying* concurrent_copying)
755 : concurrent_copying_(concurrent_copying) {
756 }
757
758 void Run(Thread* self ATTRIBUTE_UNUSED) OVERRIDE REQUIRES(Locks::thread_list_lock_) {
759 // This needs to run under the thread_list_lock_ critical section in ThreadList::RunCheckpoint()
760 // to avoid a race with ThreadList::Register().
761 CHECK(concurrent_copying_->is_marking_);
762 concurrent_copying_->is_marking_ = false;
763 }
764
765 private:
766 ConcurrentCopying* const concurrent_copying_;
767};
768
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700769void ConcurrentCopying::IssueDisableMarkingCheckpoint() {
770 Thread* self = Thread::Current();
771 DisableMarkingCheckpoint check_point(this);
772 ThreadList* thread_list = Runtime::Current()->GetThreadList();
773 gc_barrier_->Init(self, 0);
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -0700774 DisableMarkingCallback dmc(this);
775 size_t barrier_count = thread_list->RunCheckpoint(&check_point, &dmc);
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700776 // If there are no threads to wait which implies that all the checkpoint functions are finished,
777 // then no need to release the mutator lock.
778 if (barrier_count == 0) {
779 return;
780 }
781 // Release locks then wait for all mutator threads to pass the barrier.
782 Locks::mutator_lock_->SharedUnlock(self);
783 {
784 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
785 gc_barrier_->Increment(self, barrier_count);
786 }
787 Locks::mutator_lock_->SharedLock(self);
788}
789
790void ConcurrentCopying::DisableMarking() {
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -0700791 // Use a checkpoint to turn off the global is_marking and the thread-local is_gc_marking flags and
792 // to ensure no threads are still in the middle of a read barrier which may have a from-space ref
793 // cached in a local variable.
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700794 IssueDisableMarkingCheckpoint();
795 if (kUseTableLookupReadBarrier) {
796 heap_->rb_table_->ClearAll();
797 DCHECK(heap_->rb_table_->IsAllCleared());
798 }
799 is_mark_stack_push_disallowed_.StoreSequentiallyConsistent(1);
800 mark_stack_mode_.StoreSequentiallyConsistent(kMarkStackModeOff);
801}
802
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800803void ConcurrentCopying::PushOntoFalseGrayStack(mirror::Object* ref) {
804 CHECK(kUseBakerReadBarrier);
805 DCHECK(ref != nullptr);
806 MutexLock mu(Thread::Current(), mark_stack_lock_);
807 false_gray_stack_.push_back(ref);
808}
809
810void ConcurrentCopying::ProcessFalseGrayStack() {
811 CHECK(kUseBakerReadBarrier);
812 // Change the objects on the false gray stack from gray to white.
813 MutexLock mu(Thread::Current(), mark_stack_lock_);
814 for (mirror::Object* obj : false_gray_stack_) {
815 DCHECK(IsMarked(obj));
816 // The object could be white here if a thread got preempted after a success at the
817 // AtomicSetReadBarrierPointer in Mark(), GC started marking through it (but not finished so
818 // still gray), and the thread ran to register it onto the false gray stack.
819 if (obj->GetReadBarrierPointer() == ReadBarrier::GrayPtr()) {
820 bool success = obj->AtomicSetReadBarrierPointer(ReadBarrier::GrayPtr(),
821 ReadBarrier::WhitePtr());
822 DCHECK(success);
823 }
824 }
825 false_gray_stack_.clear();
826}
827
828
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800829void ConcurrentCopying::IssueEmptyCheckpoint() {
830 Thread* self = Thread::Current();
831 EmptyCheckpoint check_point(this);
832 ThreadList* thread_list = Runtime::Current()->GetThreadList();
833 gc_barrier_->Init(self, 0);
834 size_t barrier_count = thread_list->RunCheckpoint(&check_point);
Lei Lidd9943d2015-02-02 14:24:44 +0800835 // If there are no threads to wait which implys that all the checkpoint functions are finished,
836 // then no need to release the mutator lock.
837 if (barrier_count == 0) {
838 return;
839 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800840 // Release locks then wait for all mutator threads to pass the barrier.
841 Locks::mutator_lock_->SharedUnlock(self);
842 {
843 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
844 gc_barrier_->Increment(self, barrier_count);
845 }
846 Locks::mutator_lock_->SharedLock(self);
847}
848
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -0700849void ConcurrentCopying::ExpandGcMarkStack() {
850 DCHECK(gc_mark_stack_->IsFull());
851 const size_t new_size = gc_mark_stack_->Capacity() * 2;
852 std::vector<StackReference<mirror::Object>> temp(gc_mark_stack_->Begin(),
853 gc_mark_stack_->End());
854 gc_mark_stack_->Resize(new_size);
855 for (auto& ref : temp) {
856 gc_mark_stack_->PushBack(ref.AsMirrorPtr());
857 }
858 DCHECK(!gc_mark_stack_->IsFull());
859}
860
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800861void ConcurrentCopying::PushOntoMarkStack(mirror::Object* to_ref) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700862 CHECK_EQ(is_mark_stack_push_disallowed_.LoadRelaxed(), 0)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800863 << " " << to_ref << " " << PrettyTypeOf(to_ref);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700864 Thread* self = Thread::Current(); // TODO: pass self as an argument from call sites?
865 CHECK(thread_running_gc_ != nullptr);
866 MarkStackMode mark_stack_mode = mark_stack_mode_.LoadRelaxed();
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -0700867 if (LIKELY(mark_stack_mode == kMarkStackModeThreadLocal)) {
868 if (LIKELY(self == thread_running_gc_)) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700869 // If GC-running thread, use the GC mark stack instead of a thread-local mark stack.
870 CHECK(self->GetThreadLocalMarkStack() == nullptr);
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -0700871 if (UNLIKELY(gc_mark_stack_->IsFull())) {
872 ExpandGcMarkStack();
873 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700874 gc_mark_stack_->PushBack(to_ref);
875 } else {
876 // Otherwise, use a thread-local mark stack.
877 accounting::AtomicStack<mirror::Object>* tl_mark_stack = self->GetThreadLocalMarkStack();
878 if (UNLIKELY(tl_mark_stack == nullptr || tl_mark_stack->IsFull())) {
879 MutexLock mu(self, mark_stack_lock_);
880 // Get a new thread local mark stack.
881 accounting::AtomicStack<mirror::Object>* new_tl_mark_stack;
882 if (!pooled_mark_stacks_.empty()) {
883 // Use a pooled mark stack.
884 new_tl_mark_stack = pooled_mark_stacks_.back();
885 pooled_mark_stacks_.pop_back();
886 } else {
887 // None pooled. Create a new one.
888 new_tl_mark_stack =
889 accounting::AtomicStack<mirror::Object>::Create(
890 "thread local mark stack", 4 * KB, 4 * KB);
891 }
892 DCHECK(new_tl_mark_stack != nullptr);
893 DCHECK(new_tl_mark_stack->IsEmpty());
894 new_tl_mark_stack->PushBack(to_ref);
895 self->SetThreadLocalMarkStack(new_tl_mark_stack);
896 if (tl_mark_stack != nullptr) {
897 // Store the old full stack into a vector.
898 revoked_mark_stacks_.push_back(tl_mark_stack);
899 }
900 } else {
901 tl_mark_stack->PushBack(to_ref);
902 }
903 }
904 } else if (mark_stack_mode == kMarkStackModeShared) {
905 // Access the shared GC mark stack with a lock.
906 MutexLock mu(self, mark_stack_lock_);
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -0700907 if (UNLIKELY(gc_mark_stack_->IsFull())) {
908 ExpandGcMarkStack();
909 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700910 gc_mark_stack_->PushBack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800911 } else {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700912 CHECK_EQ(static_cast<uint32_t>(mark_stack_mode),
Hiroshi Yamauchifa755182015-09-30 20:12:11 -0700913 static_cast<uint32_t>(kMarkStackModeGcExclusive))
914 << "ref=" << to_ref
915 << " self->gc_marking=" << self->GetIsGcMarking()
916 << " cc->is_marking=" << is_marking_;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700917 CHECK(self == thread_running_gc_)
918 << "Only GC-running thread should access the mark stack "
919 << "in the GC exclusive mark stack mode";
920 // Access the GC mark stack without a lock.
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -0700921 if (UNLIKELY(gc_mark_stack_->IsFull())) {
922 ExpandGcMarkStack();
923 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700924 gc_mark_stack_->PushBack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800925 }
926}
927
928accounting::ObjectStack* ConcurrentCopying::GetAllocationStack() {
929 return heap_->allocation_stack_.get();
930}
931
932accounting::ObjectStack* ConcurrentCopying::GetLiveStack() {
933 return heap_->live_stack_.get();
934}
935
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800936// The following visitors are used to verify that there's no references to the from-space left after
937// marking.
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700938class ConcurrentCopying::VerifyNoFromSpaceRefsVisitor : public SingleRootVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800939 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700940 explicit VerifyNoFromSpaceRefsVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800941 : collector_(collector) {}
942
943 void operator()(mirror::Object* ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700944 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800945 if (ref == nullptr) {
946 // OK.
947 return;
948 }
949 collector_->AssertToSpaceInvariant(nullptr, MemberOffset(0), ref);
950 if (kUseBakerReadBarrier) {
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700951 CHECK_EQ(ref->GetReadBarrierPointer(), ReadBarrier::WhitePtr())
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800952 << "Ref " << ref << " " << PrettyTypeOf(ref)
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700953 << " has non-white rb_ptr ";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800954 }
955 }
956
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700957 void VisitRoot(mirror::Object* root, const RootInfo& info ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700958 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800959 DCHECK(root != nullptr);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700960 operator()(root);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800961 }
962
963 private:
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700964 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800965};
966
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700967class ConcurrentCopying::VerifyNoFromSpaceRefsFieldVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800968 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700969 explicit VerifyNoFromSpaceRefsFieldVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800970 : collector_(collector) {}
971
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700972 void operator()(mirror::Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700973 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800974 mirror::Object* ref =
975 obj->GetFieldObject<mirror::Object, kDefaultVerifyFlags, kWithoutReadBarrier>(offset);
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700976 VerifyNoFromSpaceRefsVisitor visitor(collector_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800977 visitor(ref);
978 }
979 void operator()(mirror::Class* klass, mirror::Reference* ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700980 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800981 CHECK(klass->IsTypeOfReferenceClass());
982 this->operator()(ref, mirror::Reference::ReferentOffset(), false);
983 }
984
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700985 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700986 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700987 if (!root->IsNull()) {
988 VisitRoot(root);
989 }
990 }
991
992 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700993 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700994 VerifyNoFromSpaceRefsVisitor visitor(collector_);
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700995 visitor(root->AsMirrorPtr());
996 }
997
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800998 private:
Mathieu Chartier97509952015-07-13 14:35:43 -0700999 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001000};
1001
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001002class ConcurrentCopying::VerifyNoFromSpaceRefsObjectVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001003 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001004 explicit VerifyNoFromSpaceRefsObjectVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001005 : collector_(collector) {}
1006 void operator()(mirror::Object* obj) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001007 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001008 ObjectCallback(obj, collector_);
1009 }
1010 static void ObjectCallback(mirror::Object* obj, void *arg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001011 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001012 CHECK(obj != nullptr);
1013 ConcurrentCopying* collector = reinterpret_cast<ConcurrentCopying*>(arg);
1014 space::RegionSpace* region_space = collector->RegionSpace();
1015 CHECK(!region_space->IsInFromSpace(obj)) << "Scanning object " << obj << " in from space";
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001016 VerifyNoFromSpaceRefsFieldVisitor visitor(collector);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07001017 obj->VisitReferences(visitor, visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001018 if (kUseBakerReadBarrier) {
Mathieu Chartier36a270a2016-07-28 18:08:51 -07001019 CHECK_EQ(obj->GetReadBarrierPointer(), ReadBarrier::WhitePtr())
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001020 << "obj=" << obj << " non-white rb_ptr " << obj->GetReadBarrierPointer();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001021 }
1022 }
1023
1024 private:
1025 ConcurrentCopying* const collector_;
1026};
1027
1028// Verify there's no from-space references left after the marking phase.
1029void ConcurrentCopying::VerifyNoFromSpaceReferences() {
1030 Thread* self = Thread::Current();
1031 DCHECK(Locks::mutator_lock_->IsExclusiveHeld(self));
Hiroshi Yamauchi00370822015-08-18 14:47:25 -07001032 // Verify all threads have is_gc_marking to be false
1033 {
1034 MutexLock mu(self, *Locks::thread_list_lock_);
1035 std::list<Thread*> thread_list = Runtime::Current()->GetThreadList()->GetList();
1036 for (Thread* thread : thread_list) {
1037 CHECK(!thread->GetIsGcMarking());
1038 }
1039 }
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001040 VerifyNoFromSpaceRefsObjectVisitor visitor(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001041 // Roots.
1042 {
1043 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001044 VerifyNoFromSpaceRefsVisitor ref_visitor(this);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001045 Runtime::Current()->VisitRoots(&ref_visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001046 }
1047 // The to-space.
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001048 region_space_->WalkToSpace(VerifyNoFromSpaceRefsObjectVisitor::ObjectCallback, this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001049 // Non-moving spaces.
1050 {
1051 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1052 heap_->GetMarkBitmap()->Visit(visitor);
1053 }
1054 // The alloc stack.
1055 {
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001056 VerifyNoFromSpaceRefsVisitor ref_visitor(this);
Mathieu Chartiercb535da2015-01-23 13:50:03 -08001057 for (auto* it = heap_->allocation_stack_->Begin(), *end = heap_->allocation_stack_->End();
1058 it < end; ++it) {
1059 mirror::Object* const obj = it->AsMirrorPtr();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001060 if (obj != nullptr && obj->GetClass() != nullptr) {
1061 // TODO: need to call this only if obj is alive?
1062 ref_visitor(obj);
1063 visitor(obj);
1064 }
1065 }
1066 }
1067 // TODO: LOS. But only refs in LOS are classes.
1068}
1069
1070// The following visitors are used to assert the to-space invariant.
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001071class ConcurrentCopying::AssertToSpaceInvariantRefsVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001072 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001073 explicit AssertToSpaceInvariantRefsVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001074 : collector_(collector) {}
1075
1076 void operator()(mirror::Object* ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001077 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001078 if (ref == nullptr) {
1079 // OK.
1080 return;
1081 }
1082 collector_->AssertToSpaceInvariant(nullptr, MemberOffset(0), ref);
1083 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001084
1085 private:
Mathieu Chartier97509952015-07-13 14:35:43 -07001086 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001087};
1088
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001089class ConcurrentCopying::AssertToSpaceInvariantFieldVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001090 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001091 explicit AssertToSpaceInvariantFieldVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001092 : collector_(collector) {}
1093
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001094 void operator()(mirror::Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001095 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001096 mirror::Object* ref =
1097 obj->GetFieldObject<mirror::Object, kDefaultVerifyFlags, kWithoutReadBarrier>(offset);
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001098 AssertToSpaceInvariantRefsVisitor visitor(collector_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001099 visitor(ref);
1100 }
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001101 void operator()(mirror::Class* klass, mirror::Reference* ref ATTRIBUTE_UNUSED) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001102 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001103 CHECK(klass->IsTypeOfReferenceClass());
1104 }
1105
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001106 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001107 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001108 if (!root->IsNull()) {
1109 VisitRoot(root);
1110 }
1111 }
1112
1113 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001114 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001115 AssertToSpaceInvariantRefsVisitor visitor(collector_);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001116 visitor(root->AsMirrorPtr());
1117 }
1118
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001119 private:
Mathieu Chartier97509952015-07-13 14:35:43 -07001120 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001121};
1122
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001123class ConcurrentCopying::AssertToSpaceInvariantObjectVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001124 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001125 explicit AssertToSpaceInvariantObjectVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001126 : collector_(collector) {}
1127 void operator()(mirror::Object* obj) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001128 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001129 ObjectCallback(obj, collector_);
1130 }
1131 static void ObjectCallback(mirror::Object* obj, void *arg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001132 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001133 CHECK(obj != nullptr);
1134 ConcurrentCopying* collector = reinterpret_cast<ConcurrentCopying*>(arg);
1135 space::RegionSpace* region_space = collector->RegionSpace();
1136 CHECK(!region_space->IsInFromSpace(obj)) << "Scanning object " << obj << " in from space";
1137 collector->AssertToSpaceInvariant(nullptr, MemberOffset(0), obj);
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001138 AssertToSpaceInvariantFieldVisitor visitor(collector);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07001139 obj->VisitReferences(visitor, visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001140 }
1141
1142 private:
Mathieu Chartier97509952015-07-13 14:35:43 -07001143 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001144};
1145
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001146class ConcurrentCopying::RevokeThreadLocalMarkStackCheckpoint : public Closure {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001147 public:
Roland Levillain3887c462015-08-12 18:15:42 +01001148 RevokeThreadLocalMarkStackCheckpoint(ConcurrentCopying* concurrent_copying,
1149 bool disable_weak_ref_access)
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001150 : concurrent_copying_(concurrent_copying),
1151 disable_weak_ref_access_(disable_weak_ref_access) {
1152 }
1153
1154 virtual void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
1155 // Note: self is not necessarily equal to thread since thread may be suspended.
1156 Thread* self = Thread::Current();
1157 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
1158 << thread->GetState() << " thread " << thread << " self " << self;
1159 // Revoke thread local mark stacks.
1160 accounting::AtomicStack<mirror::Object>* tl_mark_stack = thread->GetThreadLocalMarkStack();
1161 if (tl_mark_stack != nullptr) {
1162 MutexLock mu(self, concurrent_copying_->mark_stack_lock_);
1163 concurrent_copying_->revoked_mark_stacks_.push_back(tl_mark_stack);
1164 thread->SetThreadLocalMarkStack(nullptr);
1165 }
1166 // Disable weak ref access.
1167 if (disable_weak_ref_access_) {
1168 thread->SetWeakRefAccessEnabled(false);
1169 }
1170 // If thread is a running mutator, then act on behalf of the garbage collector.
1171 // See the code in ThreadList::RunCheckpoint.
Mathieu Chartier10d25082015-10-28 18:36:09 -07001172 concurrent_copying_->GetBarrier().Pass(self);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001173 }
1174
1175 private:
1176 ConcurrentCopying* const concurrent_copying_;
1177 const bool disable_weak_ref_access_;
1178};
1179
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001180void ConcurrentCopying::RevokeThreadLocalMarkStacks(bool disable_weak_ref_access,
1181 Closure* checkpoint_callback) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001182 Thread* self = Thread::Current();
1183 RevokeThreadLocalMarkStackCheckpoint check_point(this, disable_weak_ref_access);
1184 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1185 gc_barrier_->Init(self, 0);
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001186 size_t barrier_count = thread_list->RunCheckpoint(&check_point, checkpoint_callback);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001187 // If there are no threads to wait which implys that all the checkpoint functions are finished,
1188 // then no need to release the mutator lock.
1189 if (barrier_count == 0) {
1190 return;
1191 }
1192 Locks::mutator_lock_->SharedUnlock(self);
1193 {
1194 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
1195 gc_barrier_->Increment(self, barrier_count);
1196 }
1197 Locks::mutator_lock_->SharedLock(self);
1198}
1199
1200void ConcurrentCopying::RevokeThreadLocalMarkStack(Thread* thread) {
1201 Thread* self = Thread::Current();
1202 CHECK_EQ(self, thread);
1203 accounting::AtomicStack<mirror::Object>* tl_mark_stack = thread->GetThreadLocalMarkStack();
1204 if (tl_mark_stack != nullptr) {
1205 CHECK(is_marking_);
1206 MutexLock mu(self, mark_stack_lock_);
1207 revoked_mark_stacks_.push_back(tl_mark_stack);
1208 thread->SetThreadLocalMarkStack(nullptr);
1209 }
1210}
1211
1212void ConcurrentCopying::ProcessMarkStack() {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001213 if (kVerboseMode) {
1214 LOG(INFO) << "ProcessMarkStack. ";
1215 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001216 bool empty_prev = false;
1217 while (true) {
1218 bool empty = ProcessMarkStackOnce();
1219 if (empty_prev && empty) {
1220 // Saw empty mark stack for a second time, done.
1221 break;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001222 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001223 empty_prev = empty;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001224 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001225}
1226
1227bool ConcurrentCopying::ProcessMarkStackOnce() {
1228 Thread* self = Thread::Current();
1229 CHECK(thread_running_gc_ != nullptr);
1230 CHECK(self == thread_running_gc_);
1231 CHECK(self->GetThreadLocalMarkStack() == nullptr);
1232 size_t count = 0;
1233 MarkStackMode mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1234 if (mark_stack_mode == kMarkStackModeThreadLocal) {
1235 // Process the thread-local mark stacks and the GC mark stack.
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001236 count += ProcessThreadLocalMarkStacks(false, nullptr);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001237 while (!gc_mark_stack_->IsEmpty()) {
1238 mirror::Object* to_ref = gc_mark_stack_->PopBack();
1239 ProcessMarkStackRef(to_ref);
1240 ++count;
1241 }
1242 gc_mark_stack_->Reset();
1243 } else if (mark_stack_mode == kMarkStackModeShared) {
1244 // Process the shared GC mark stack with a lock.
1245 {
1246 MutexLock mu(self, mark_stack_lock_);
1247 CHECK(revoked_mark_stacks_.empty());
1248 }
1249 while (true) {
1250 std::vector<mirror::Object*> refs;
1251 {
1252 // Copy refs with lock. Note the number of refs should be small.
1253 MutexLock mu(self, mark_stack_lock_);
1254 if (gc_mark_stack_->IsEmpty()) {
1255 break;
1256 }
1257 for (StackReference<mirror::Object>* p = gc_mark_stack_->Begin();
1258 p != gc_mark_stack_->End(); ++p) {
1259 refs.push_back(p->AsMirrorPtr());
1260 }
1261 gc_mark_stack_->Reset();
1262 }
1263 for (mirror::Object* ref : refs) {
1264 ProcessMarkStackRef(ref);
1265 ++count;
1266 }
1267 }
1268 } else {
1269 CHECK_EQ(static_cast<uint32_t>(mark_stack_mode),
1270 static_cast<uint32_t>(kMarkStackModeGcExclusive));
1271 {
1272 MutexLock mu(self, mark_stack_lock_);
1273 CHECK(revoked_mark_stacks_.empty());
1274 }
1275 // Process the GC mark stack in the exclusive mode. No need to take the lock.
1276 while (!gc_mark_stack_->IsEmpty()) {
1277 mirror::Object* to_ref = gc_mark_stack_->PopBack();
1278 ProcessMarkStackRef(to_ref);
1279 ++count;
1280 }
1281 gc_mark_stack_->Reset();
1282 }
1283
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001284 // Return true if the stack was empty.
1285 return count == 0;
1286}
1287
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001288size_t ConcurrentCopying::ProcessThreadLocalMarkStacks(bool disable_weak_ref_access,
1289 Closure* checkpoint_callback) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001290 // Run a checkpoint to collect all thread local mark stacks and iterate over them all.
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001291 RevokeThreadLocalMarkStacks(disable_weak_ref_access, checkpoint_callback);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001292 size_t count = 0;
1293 std::vector<accounting::AtomicStack<mirror::Object>*> mark_stacks;
1294 {
1295 MutexLock mu(Thread::Current(), mark_stack_lock_);
1296 // Make a copy of the mark stack vector.
1297 mark_stacks = revoked_mark_stacks_;
1298 revoked_mark_stacks_.clear();
1299 }
1300 for (accounting::AtomicStack<mirror::Object>* mark_stack : mark_stacks) {
1301 for (StackReference<mirror::Object>* p = mark_stack->Begin(); p != mark_stack->End(); ++p) {
1302 mirror::Object* to_ref = p->AsMirrorPtr();
1303 ProcessMarkStackRef(to_ref);
1304 ++count;
1305 }
1306 {
1307 MutexLock mu(Thread::Current(), mark_stack_lock_);
1308 if (pooled_mark_stacks_.size() >= kMarkStackPoolSize) {
1309 // The pool has enough. Delete it.
1310 delete mark_stack;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001311 } else {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001312 // Otherwise, put it into the pool for later reuse.
1313 mark_stack->Reset();
1314 pooled_mark_stacks_.push_back(mark_stack);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001315 }
1316 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001317 }
1318 return count;
1319}
1320
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001321inline void ConcurrentCopying::ProcessMarkStackRef(mirror::Object* to_ref) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001322 DCHECK(!region_space_->IsInFromSpace(to_ref));
1323 if (kUseBakerReadBarrier) {
1324 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr())
1325 << " " << to_ref << " " << to_ref->GetReadBarrierPointer()
1326 << " is_marked=" << IsMarked(to_ref);
1327 }
Mathieu Chartierc381c362016-08-23 13:27:53 -07001328 bool add_to_live_bytes = false;
1329 if (region_space_->IsInUnevacFromSpace(to_ref)) {
1330 // Mark the bitmap only in the GC thread here so that we don't need a CAS.
1331 if (!kUseBakerReadBarrier || !region_space_bitmap_->Set(to_ref)) {
1332 // It may be already marked if we accidentally pushed the same object twice due to the racy
1333 // bitmap read in MarkUnevacFromSpaceRegion.
1334 Scan(to_ref);
1335 // Only add to the live bytes if the object was not already marked.
1336 add_to_live_bytes = true;
1337 }
1338 } else {
1339 Scan(to_ref);
1340 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001341 if (kUseBakerReadBarrier) {
1342 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr())
1343 << " " << to_ref << " " << to_ref->GetReadBarrierPointer()
1344 << " is_marked=" << IsMarked(to_ref);
1345 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001346#ifdef USE_BAKER_OR_BROOKS_READ_BARRIER
1347 if (UNLIKELY((to_ref->GetClass<kVerifyNone, kWithoutReadBarrier>()->IsTypeOfReferenceClass() &&
1348 to_ref->AsReference()->GetReferent<kWithoutReadBarrier>() != nullptr &&
1349 !IsInToSpace(to_ref->AsReference()->GetReferent<kWithoutReadBarrier>())))) {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001350 // Leave this reference gray in the queue so that GetReferent() will trigger a read barrier. We
1351 // will change it to white later in ReferenceQueue::DequeuePendingReference().
Richard Uhlere3627402016-02-02 13:36:55 -08001352 DCHECK(to_ref->AsReference()->GetPendingNext() != nullptr) << "Left unenqueued ref gray " << to_ref;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001353 } else {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001354 // We may occasionally leave a reference white in the queue if its referent happens to be
1355 // concurrently marked after the Scan() call above has enqueued the Reference, in which case the
1356 // above IsInToSpace() evaluates to true and we change the color from gray to white here in this
1357 // else block.
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001358 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001359 bool success = to_ref->AtomicSetReadBarrierPointer</*kCasRelease*/true>(
1360 ReadBarrier::GrayPtr(),
1361 ReadBarrier::WhitePtr());
1362 DCHECK(success) << "Must succeed as we won the race.";
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001363 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001364 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001365#else
1366 DCHECK(!kUseBakerReadBarrier);
1367#endif
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001368
Mathieu Chartierc381c362016-08-23 13:27:53 -07001369 if (add_to_live_bytes) {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001370 // Add to the live bytes per unevacuated from space. Note this code is always run by the
1371 // GC-running thread (no synchronization required).
1372 DCHECK(region_space_bitmap_->Test(to_ref));
1373 // Disable the read barrier in SizeOf for performance, which is safe.
1374 size_t obj_size = to_ref->SizeOf<kDefaultVerifyFlags, kWithoutReadBarrier>();
1375 size_t alloc_size = RoundUp(obj_size, space::RegionSpace::kAlignment);
1376 region_space_->AddLiveBytes(to_ref, alloc_size);
1377 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001378 if (ReadBarrier::kEnableToSpaceInvariantChecks || kIsDebugBuild) {
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001379 AssertToSpaceInvariantObjectVisitor visitor(this);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001380 visitor(to_ref);
1381 }
1382}
1383
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001384class ConcurrentCopying::DisableWeakRefAccessCallback : public Closure {
1385 public:
1386 explicit DisableWeakRefAccessCallback(ConcurrentCopying* concurrent_copying)
1387 : concurrent_copying_(concurrent_copying) {
1388 }
1389
1390 void Run(Thread* self ATTRIBUTE_UNUSED) OVERRIDE REQUIRES(Locks::thread_list_lock_) {
1391 // This needs to run under the thread_list_lock_ critical section in ThreadList::RunCheckpoint()
1392 // to avoid a deadlock b/31500969.
1393 CHECK(concurrent_copying_->weak_ref_access_enabled_);
1394 concurrent_copying_->weak_ref_access_enabled_ = false;
1395 }
1396
1397 private:
1398 ConcurrentCopying* const concurrent_copying_;
1399};
1400
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001401void ConcurrentCopying::SwitchToSharedMarkStackMode() {
1402 Thread* self = Thread::Current();
1403 CHECK(thread_running_gc_ != nullptr);
1404 CHECK_EQ(self, thread_running_gc_);
1405 CHECK(self->GetThreadLocalMarkStack() == nullptr);
1406 MarkStackMode before_mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1407 CHECK_EQ(static_cast<uint32_t>(before_mark_stack_mode),
1408 static_cast<uint32_t>(kMarkStackModeThreadLocal));
1409 mark_stack_mode_.StoreRelaxed(kMarkStackModeShared);
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001410 DisableWeakRefAccessCallback dwrac(this);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001411 // Process the thread local mark stacks one last time after switching to the shared mark stack
1412 // mode and disable weak ref accesses.
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001413 ProcessThreadLocalMarkStacks(true, &dwrac);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001414 if (kVerboseMode) {
1415 LOG(INFO) << "Switched to shared mark stack mode and disabled weak ref access";
1416 }
1417}
1418
1419void ConcurrentCopying::SwitchToGcExclusiveMarkStackMode() {
1420 Thread* self = Thread::Current();
1421 CHECK(thread_running_gc_ != nullptr);
1422 CHECK_EQ(self, thread_running_gc_);
1423 CHECK(self->GetThreadLocalMarkStack() == nullptr);
1424 MarkStackMode before_mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1425 CHECK_EQ(static_cast<uint32_t>(before_mark_stack_mode),
1426 static_cast<uint32_t>(kMarkStackModeShared));
1427 mark_stack_mode_.StoreRelaxed(kMarkStackModeGcExclusive);
1428 QuasiAtomic::ThreadFenceForConstructor();
1429 if (kVerboseMode) {
1430 LOG(INFO) << "Switched to GC exclusive mark stack mode";
1431 }
1432}
1433
1434void ConcurrentCopying::CheckEmptyMarkStack() {
1435 Thread* self = Thread::Current();
1436 CHECK(thread_running_gc_ != nullptr);
1437 CHECK_EQ(self, thread_running_gc_);
1438 CHECK(self->GetThreadLocalMarkStack() == nullptr);
1439 MarkStackMode mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1440 if (mark_stack_mode == kMarkStackModeThreadLocal) {
1441 // Thread-local mark stack mode.
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001442 RevokeThreadLocalMarkStacks(false, nullptr);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001443 MutexLock mu(Thread::Current(), mark_stack_lock_);
1444 if (!revoked_mark_stacks_.empty()) {
1445 for (accounting::AtomicStack<mirror::Object>* mark_stack : revoked_mark_stacks_) {
1446 while (!mark_stack->IsEmpty()) {
1447 mirror::Object* obj = mark_stack->PopBack();
1448 if (kUseBakerReadBarrier) {
1449 mirror::Object* rb_ptr = obj->GetReadBarrierPointer();
1450 LOG(INFO) << "On mark queue : " << obj << " " << PrettyTypeOf(obj) << " rb_ptr=" << rb_ptr
1451 << " is_marked=" << IsMarked(obj);
1452 } else {
1453 LOG(INFO) << "On mark queue : " << obj << " " << PrettyTypeOf(obj)
1454 << " is_marked=" << IsMarked(obj);
1455 }
1456 }
1457 }
1458 LOG(FATAL) << "mark stack is not empty";
1459 }
1460 } else {
1461 // Shared, GC-exclusive, or off.
1462 MutexLock mu(Thread::Current(), mark_stack_lock_);
1463 CHECK(gc_mark_stack_->IsEmpty());
1464 CHECK(revoked_mark_stacks_.empty());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001465 }
1466}
1467
1468void ConcurrentCopying::SweepSystemWeaks(Thread* self) {
1469 TimingLogger::ScopedTiming split("SweepSystemWeaks", GetTimings());
1470 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier97509952015-07-13 14:35:43 -07001471 Runtime::Current()->SweepSystemWeaks(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001472}
1473
1474void ConcurrentCopying::Sweep(bool swap_bitmaps) {
1475 {
1476 TimingLogger::ScopedTiming t("MarkStackAsLive", GetTimings());
1477 accounting::ObjectStack* live_stack = heap_->GetLiveStack();
1478 if (kEnableFromSpaceAccountingCheck) {
1479 CHECK_GE(live_stack_freeze_size_, live_stack->Size());
1480 }
1481 heap_->MarkAllocStackAsLive(live_stack);
1482 live_stack->Reset();
1483 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001484 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001485 TimingLogger::ScopedTiming split("Sweep", GetTimings());
1486 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
1487 if (space->IsContinuousMemMapAllocSpace()) {
1488 space::ContinuousMemMapAllocSpace* alloc_space = space->AsContinuousMemMapAllocSpace();
Mathieu Chartier763a31e2015-11-16 16:05:55 -08001489 if (space == region_space_ || immune_spaces_.ContainsSpace(space)) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001490 continue;
1491 }
1492 TimingLogger::ScopedTiming split2(
1493 alloc_space->IsZygoteSpace() ? "SweepZygoteSpace" : "SweepAllocSpace", GetTimings());
1494 RecordFree(alloc_space->Sweep(swap_bitmaps));
1495 }
1496 }
1497 SweepLargeObjects(swap_bitmaps);
1498}
1499
Mathieu Chartier962cd7a2016-08-16 12:15:59 -07001500void ConcurrentCopying::MarkZygoteLargeObjects() {
1501 TimingLogger::ScopedTiming split(__FUNCTION__, GetTimings());
1502 Thread* const self = Thread::Current();
1503 WriterMutexLock rmu(self, *Locks::heap_bitmap_lock_);
1504 space::LargeObjectSpace* const los = heap_->GetLargeObjectsSpace();
1505 // Pick the current live bitmap (mark bitmap if swapped).
1506 accounting::LargeObjectBitmap* const live_bitmap = los->GetLiveBitmap();
1507 accounting::LargeObjectBitmap* const mark_bitmap = los->GetMarkBitmap();
1508 // Walk through all of the objects and explicitly mark the zygote ones so they don't get swept.
1509 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(los->Begin()),
1510 reinterpret_cast<uintptr_t>(los->End()),
1511 [mark_bitmap, los, self](mirror::Object* obj)
1512 REQUIRES(Locks::heap_bitmap_lock_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001513 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier962cd7a2016-08-16 12:15:59 -07001514 if (los->IsZygoteLargeObject(self, obj)) {
1515 mark_bitmap->Set(obj);
1516 }
1517 });
1518}
1519
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001520void ConcurrentCopying::SweepLargeObjects(bool swap_bitmaps) {
1521 TimingLogger::ScopedTiming split("SweepLargeObjects", GetTimings());
1522 RecordFreeLOS(heap_->GetLargeObjectsSpace()->Sweep(swap_bitmaps));
1523}
1524
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001525void ConcurrentCopying::ReclaimPhase() {
1526 TimingLogger::ScopedTiming split("ReclaimPhase", GetTimings());
1527 if (kVerboseMode) {
1528 LOG(INFO) << "GC ReclaimPhase";
1529 }
1530 Thread* self = Thread::Current();
1531
1532 {
1533 // Double-check that the mark stack is empty.
1534 // Note: need to set this after VerifyNoFromSpaceRef().
1535 is_asserting_to_space_invariant_ = false;
1536 QuasiAtomic::ThreadFenceForConstructor();
1537 if (kVerboseMode) {
1538 LOG(INFO) << "Issue an empty check point. ";
1539 }
1540 IssueEmptyCheckpoint();
1541 // Disable the check.
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001542 is_mark_stack_push_disallowed_.StoreSequentiallyConsistent(0);
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001543 if (kUseBakerReadBarrier) {
1544 updated_all_immune_objects_.StoreSequentiallyConsistent(false);
1545 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001546 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001547 }
1548
1549 {
1550 // Record freed objects.
1551 TimingLogger::ScopedTiming split2("RecordFree", GetTimings());
1552 // Don't include thread-locals that are in the to-space.
1553 uint64_t from_bytes = region_space_->GetBytesAllocatedInFromSpace();
1554 uint64_t from_objects = region_space_->GetObjectsAllocatedInFromSpace();
1555 uint64_t unevac_from_bytes = region_space_->GetBytesAllocatedInUnevacFromSpace();
1556 uint64_t unevac_from_objects = region_space_->GetObjectsAllocatedInUnevacFromSpace();
1557 uint64_t to_bytes = bytes_moved_.LoadSequentiallyConsistent();
Mathieu Chartiercca44a02016-08-17 10:07:29 -07001558 cumulative_bytes_moved_.FetchAndAddRelaxed(to_bytes);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001559 uint64_t to_objects = objects_moved_.LoadSequentiallyConsistent();
Mathieu Chartiercca44a02016-08-17 10:07:29 -07001560 cumulative_objects_moved_.FetchAndAddRelaxed(to_objects);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001561 if (kEnableFromSpaceAccountingCheck) {
1562 CHECK_EQ(from_space_num_objects_at_first_pause_, from_objects + unevac_from_objects);
1563 CHECK_EQ(from_space_num_bytes_at_first_pause_, from_bytes + unevac_from_bytes);
1564 }
1565 CHECK_LE(to_objects, from_objects);
1566 CHECK_LE(to_bytes, from_bytes);
1567 int64_t freed_bytes = from_bytes - to_bytes;
1568 int64_t freed_objects = from_objects - to_objects;
1569 if (kVerboseMode) {
1570 LOG(INFO) << "RecordFree:"
1571 << " from_bytes=" << from_bytes << " from_objects=" << from_objects
1572 << " unevac_from_bytes=" << unevac_from_bytes << " unevac_from_objects=" << unevac_from_objects
1573 << " to_bytes=" << to_bytes << " to_objects=" << to_objects
1574 << " freed_bytes=" << freed_bytes << " freed_objects=" << freed_objects
1575 << " from_space size=" << region_space_->FromSpaceSize()
1576 << " unevac_from_space size=" << region_space_->UnevacFromSpaceSize()
1577 << " to_space size=" << region_space_->ToSpaceSize();
1578 LOG(INFO) << "(before) num_bytes_allocated=" << heap_->num_bytes_allocated_.LoadSequentiallyConsistent();
1579 }
1580 RecordFree(ObjectBytePair(freed_objects, freed_bytes));
1581 if (kVerboseMode) {
1582 LOG(INFO) << "(after) num_bytes_allocated=" << heap_->num_bytes_allocated_.LoadSequentiallyConsistent();
1583 }
1584 }
1585
1586 {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001587 TimingLogger::ScopedTiming split4("ClearFromSpace", GetTimings());
1588 region_space_->ClearFromSpace();
1589 }
1590
1591 {
1592 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001593 Sweep(false);
1594 SwapBitmaps();
1595 heap_->UnBindBitmaps();
1596
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001597 // Delete the region bitmap.
1598 DCHECK(region_space_bitmap_ != nullptr);
1599 delete region_space_bitmap_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001600 region_space_bitmap_ = nullptr;
1601 }
1602
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001603 CheckEmptyMarkStack();
1604
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001605 if (kVerboseMode) {
1606 LOG(INFO) << "GC end of ReclaimPhase";
1607 }
1608}
1609
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001610// Assert the to-space invariant.
1611void ConcurrentCopying::AssertToSpaceInvariant(mirror::Object* obj, MemberOffset offset,
1612 mirror::Object* ref) {
1613 CHECK(heap_->collector_type_ == kCollectorTypeCC) << static_cast<size_t>(heap_->collector_type_);
1614 if (is_asserting_to_space_invariant_) {
1615 if (region_space_->IsInToSpace(ref)) {
1616 // OK.
1617 return;
1618 } else if (region_space_->IsInUnevacFromSpace(ref)) {
Mathieu Chartierc381c362016-08-23 13:27:53 -07001619 CHECK(IsMarkedInUnevacFromSpace(ref)) << ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001620 } else if (region_space_->IsInFromSpace(ref)) {
1621 // Not OK. Do extra logging.
1622 if (obj != nullptr) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001623 LogFromSpaceRefHolder(obj, offset);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001624 }
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07001625 ref->GetLockWord(false).Dump(LOG_STREAM(FATAL_WITHOUT_ABORT));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001626 CHECK(false) << "Found from-space ref " << ref << " " << PrettyTypeOf(ref);
1627 } else {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001628 AssertToSpaceInvariantInNonMovingSpace(obj, ref);
1629 }
1630 }
1631}
1632
1633class RootPrinter {
1634 public:
1635 RootPrinter() { }
1636
1637 template <class MirrorType>
1638 ALWAYS_INLINE void VisitRootIfNonNull(mirror::CompressedReference<MirrorType>* root)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001639 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001640 if (!root->IsNull()) {
1641 VisitRoot(root);
1642 }
1643 }
1644
1645 template <class MirrorType>
1646 void VisitRoot(mirror::Object** root)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001647 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07001648 LOG(FATAL_WITHOUT_ABORT) << "root=" << root << " ref=" << *root;
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001649 }
1650
1651 template <class MirrorType>
1652 void VisitRoot(mirror::CompressedReference<MirrorType>* root)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001653 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07001654 LOG(FATAL_WITHOUT_ABORT) << "root=" << root << " ref=" << root->AsMirrorPtr();
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001655 }
1656};
1657
1658void ConcurrentCopying::AssertToSpaceInvariant(GcRootSource* gc_root_source,
1659 mirror::Object* ref) {
1660 CHECK(heap_->collector_type_ == kCollectorTypeCC) << static_cast<size_t>(heap_->collector_type_);
1661 if (is_asserting_to_space_invariant_) {
1662 if (region_space_->IsInToSpace(ref)) {
1663 // OK.
1664 return;
1665 } else if (region_space_->IsInUnevacFromSpace(ref)) {
Mathieu Chartierc381c362016-08-23 13:27:53 -07001666 CHECK(IsMarkedInUnevacFromSpace(ref)) << ref;
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001667 } else if (region_space_->IsInFromSpace(ref)) {
1668 // Not OK. Do extra logging.
1669 if (gc_root_source == nullptr) {
1670 // No info.
1671 } else if (gc_root_source->HasArtField()) {
1672 ArtField* field = gc_root_source->GetArtField();
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07001673 LOG(FATAL_WITHOUT_ABORT) << "gc root in field " << field << " " << PrettyField(field);
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001674 RootPrinter root_printer;
1675 field->VisitRoots(root_printer);
1676 } else if (gc_root_source->HasArtMethod()) {
1677 ArtMethod* method = gc_root_source->GetArtMethod();
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07001678 LOG(FATAL_WITHOUT_ABORT) << "gc root in method " << method << " " << PrettyMethod(method);
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001679 RootPrinter root_printer;
Andreas Gampe542451c2016-07-26 09:02:02 -07001680 method->VisitRoots(root_printer, kRuntimePointerSize);
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001681 }
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07001682 ref->GetLockWord(false).Dump(LOG_STREAM(FATAL_WITHOUT_ABORT));
1683 region_space_->DumpNonFreeRegions(LOG_STREAM(FATAL_WITHOUT_ABORT));
1684 PrintFileToLog("/proc/self/maps", LogSeverity::FATAL_WITHOUT_ABORT);
1685 MemMap::DumpMaps(LOG_STREAM(FATAL_WITHOUT_ABORT), true);
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001686 CHECK(false) << "Found from-space ref " << ref << " " << PrettyTypeOf(ref);
1687 } else {
1688 AssertToSpaceInvariantInNonMovingSpace(nullptr, ref);
1689 }
1690 }
1691}
1692
1693void ConcurrentCopying::LogFromSpaceRefHolder(mirror::Object* obj, MemberOffset offset) {
1694 if (kUseBakerReadBarrier) {
1695 LOG(INFO) << "holder=" << obj << " " << PrettyTypeOf(obj)
1696 << " holder rb_ptr=" << obj->GetReadBarrierPointer();
1697 } else {
1698 LOG(INFO) << "holder=" << obj << " " << PrettyTypeOf(obj);
1699 }
1700 if (region_space_->IsInFromSpace(obj)) {
1701 LOG(INFO) << "holder is in the from-space.";
1702 } else if (region_space_->IsInToSpace(obj)) {
1703 LOG(INFO) << "holder is in the to-space.";
1704 } else if (region_space_->IsInUnevacFromSpace(obj)) {
1705 LOG(INFO) << "holder is in the unevac from-space.";
Mathieu Chartierc381c362016-08-23 13:27:53 -07001706 if (IsMarkedInUnevacFromSpace(obj)) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001707 LOG(INFO) << "holder is marked in the region space bitmap.";
1708 } else {
1709 LOG(INFO) << "holder is not marked in the region space bitmap.";
1710 }
1711 } else {
1712 // In a non-moving space.
Mathieu Chartier763a31e2015-11-16 16:05:55 -08001713 if (immune_spaces_.ContainsObject(obj)) {
1714 LOG(INFO) << "holder is in an immune image or the zygote space.";
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001715 } else {
Mathieu Chartier763a31e2015-11-16 16:05:55 -08001716 LOG(INFO) << "holder is in a non-immune, non-moving (or main) space.";
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001717 accounting::ContinuousSpaceBitmap* mark_bitmap =
1718 heap_mark_bitmap_->GetContinuousSpaceBitmap(obj);
1719 accounting::LargeObjectBitmap* los_bitmap =
1720 heap_mark_bitmap_->GetLargeObjectBitmap(obj);
1721 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
1722 bool is_los = mark_bitmap == nullptr;
1723 if (!is_los && mark_bitmap->Test(obj)) {
1724 LOG(INFO) << "holder is marked in the mark bit map.";
1725 } else if (is_los && los_bitmap->Test(obj)) {
1726 LOG(INFO) << "holder is marked in the los bit map.";
1727 } else {
1728 // If ref is on the allocation stack, then it is considered
1729 // mark/alive (but not necessarily on the live stack.)
1730 if (IsOnAllocStack(obj)) {
1731 LOG(INFO) << "holder is on the alloc stack.";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001732 } else {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001733 LOG(INFO) << "holder is not marked or on the alloc stack.";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001734 }
1735 }
1736 }
1737 }
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001738 LOG(INFO) << "offset=" << offset.SizeValue();
1739}
1740
1741void ConcurrentCopying::AssertToSpaceInvariantInNonMovingSpace(mirror::Object* obj,
1742 mirror::Object* ref) {
1743 // In a non-moving spaces. Check that the ref is marked.
Mathieu Chartier763a31e2015-11-16 16:05:55 -08001744 if (immune_spaces_.ContainsObject(ref)) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001745 if (kUseBakerReadBarrier) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001746 // Immune object may not be gray if called from the GC.
1747 if (Thread::Current() == thread_running_gc_ && !gc_grays_immune_objects_) {
1748 return;
1749 }
1750 bool updated_all_immune_objects = updated_all_immune_objects_.LoadSequentiallyConsistent();
1751 CHECK(updated_all_immune_objects || ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr())
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001752 << "Unmarked immune space ref. obj=" << obj << " rb_ptr="
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001753 << (obj != nullptr ? obj->GetReadBarrierPointer() : nullptr)
1754 << " ref=" << ref << " ref rb_ptr=" << ref->GetReadBarrierPointer()
1755 << " updated_all_immune_objects=" << updated_all_immune_objects;
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001756 }
1757 } else {
1758 accounting::ContinuousSpaceBitmap* mark_bitmap =
1759 heap_mark_bitmap_->GetContinuousSpaceBitmap(ref);
1760 accounting::LargeObjectBitmap* los_bitmap =
1761 heap_mark_bitmap_->GetLargeObjectBitmap(ref);
1762 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
1763 bool is_los = mark_bitmap == nullptr;
1764 if ((!is_los && mark_bitmap->Test(ref)) ||
1765 (is_los && los_bitmap->Test(ref))) {
1766 // OK.
1767 } else {
1768 // If ref is on the allocation stack, then it may not be
1769 // marked live, but considered marked/alive (but not
1770 // necessarily on the live stack).
1771 CHECK(IsOnAllocStack(ref)) << "Unmarked ref that's not on the allocation stack. "
1772 << "obj=" << obj << " ref=" << ref;
1773 }
1774 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001775}
1776
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001777// Used to scan ref fields of an object.
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001778class ConcurrentCopying::RefFieldsVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001779 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001780 explicit RefFieldsVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001781 : collector_(collector) {}
1782
1783 void operator()(mirror::Object* obj, MemberOffset offset, bool /* is_static */)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001784 const ALWAYS_INLINE REQUIRES_SHARED(Locks::mutator_lock_)
1785 REQUIRES_SHARED(Locks::heap_bitmap_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001786 collector_->Process(obj, offset);
1787 }
1788
1789 void operator()(mirror::Class* klass, mirror::Reference* ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001790 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001791 CHECK(klass->IsTypeOfReferenceClass());
1792 collector_->DelayReferenceReferent(klass, ref);
1793 }
1794
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001795 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001796 ALWAYS_INLINE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001797 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001798 if (!root->IsNull()) {
1799 VisitRoot(root);
1800 }
1801 }
1802
1803 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001804 ALWAYS_INLINE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001805 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001806 collector_->MarkRoot</*kGrayImmuneObject*/false>(root);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001807 }
1808
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001809 private:
1810 ConcurrentCopying* const collector_;
1811};
1812
1813// Scan ref fields of an object.
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001814inline void ConcurrentCopying::Scan(mirror::Object* to_ref) {
Mathieu Chartierd6636d32016-07-28 11:02:38 -07001815 if (kDisallowReadBarrierDuringScan) {
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07001816 // Avoid all read barriers during visit references to help performance.
1817 Thread::Current()->ModifyDebugDisallowReadBarrier(1);
1818 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001819 DCHECK(!region_space_->IsInFromSpace(to_ref));
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001820 DCHECK_EQ(Thread::Current(), thread_running_gc_);
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001821 RefFieldsVisitor visitor(this);
Hiroshi Yamauchi5496f692016-02-17 13:29:59 -08001822 // Disable the read barrier for a performance reason.
1823 to_ref->VisitReferences</*kVisitNativeRoots*/true, kDefaultVerifyFlags, kWithoutReadBarrier>(
1824 visitor, visitor);
Mathieu Chartierd6636d32016-07-28 11:02:38 -07001825 if (kDisallowReadBarrierDuringScan) {
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07001826 Thread::Current()->ModifyDebugDisallowReadBarrier(-1);
1827 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001828}
1829
1830// Process a field.
1831inline void ConcurrentCopying::Process(mirror::Object* obj, MemberOffset offset) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001832 DCHECK_EQ(Thread::Current(), thread_running_gc_);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001833 mirror::Object* ref = obj->GetFieldObject<
1834 mirror::Object, kVerifyNone, kWithoutReadBarrier, false>(offset);
Mathieu Chartierc381c362016-08-23 13:27:53 -07001835 mirror::Object* to_ref = Mark</*kGrayImmuneObject*/false, /*kFromGCThread*/true>(ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001836 if (to_ref == ref) {
1837 return;
1838 }
1839 // This may fail if the mutator writes to the field at the same time. But it's ok.
1840 mirror::Object* expected_ref = ref;
1841 mirror::Object* new_ref = to_ref;
1842 do {
1843 if (expected_ref !=
1844 obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier, false>(offset)) {
1845 // It was updated by the mutator.
1846 break;
1847 }
Hiroshi Yamauchifed3e2f2015-10-20 11:11:56 -07001848 } while (!obj->CasFieldWeakRelaxedObjectWithoutWriteBarrier<
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001849 false, false, kVerifyNone>(offset, expected_ref, new_ref));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001850}
1851
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001852// Process some roots.
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001853inline void ConcurrentCopying::VisitRoots(
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001854 mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED) {
1855 for (size_t i = 0; i < count; ++i) {
1856 mirror::Object** root = roots[i];
1857 mirror::Object* ref = *root;
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001858 mirror::Object* to_ref = Mark(ref);
1859 if (to_ref == ref) {
Mathieu Chartier4809d0a2015-04-07 10:39:04 -07001860 continue;
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001861 }
1862 Atomic<mirror::Object*>* addr = reinterpret_cast<Atomic<mirror::Object*>*>(root);
1863 mirror::Object* expected_ref = ref;
1864 mirror::Object* new_ref = to_ref;
1865 do {
1866 if (expected_ref != addr->LoadRelaxed()) {
1867 // It was updated by the mutator.
1868 break;
1869 }
Hiroshi Yamauchifed3e2f2015-10-20 11:11:56 -07001870 } while (!addr->CompareExchangeWeakRelaxed(expected_ref, new_ref));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001871 }
1872}
1873
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001874template<bool kGrayImmuneObject>
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001875inline void ConcurrentCopying::MarkRoot(mirror::CompressedReference<mirror::Object>* root) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001876 DCHECK(!root->IsNull());
1877 mirror::Object* const ref = root->AsMirrorPtr();
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001878 mirror::Object* to_ref = Mark<kGrayImmuneObject>(ref);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001879 if (to_ref != ref) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001880 auto* addr = reinterpret_cast<Atomic<mirror::CompressedReference<mirror::Object>>*>(root);
1881 auto expected_ref = mirror::CompressedReference<mirror::Object>::FromMirrorPtr(ref);
1882 auto new_ref = mirror::CompressedReference<mirror::Object>::FromMirrorPtr(to_ref);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001883 // If the cas fails, then it was updated by the mutator.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001884 do {
1885 if (ref != addr->LoadRelaxed().AsMirrorPtr()) {
1886 // It was updated by the mutator.
1887 break;
1888 }
Hiroshi Yamauchifed3e2f2015-10-20 11:11:56 -07001889 } while (!addr->CompareExchangeWeakRelaxed(expected_ref, new_ref));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001890 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001891}
1892
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001893inline void ConcurrentCopying::VisitRoots(
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001894 mirror::CompressedReference<mirror::Object>** roots, size_t count,
1895 const RootInfo& info ATTRIBUTE_UNUSED) {
1896 for (size_t i = 0; i < count; ++i) {
1897 mirror::CompressedReference<mirror::Object>* const root = roots[i];
1898 if (!root->IsNull()) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001899 // kGrayImmuneObject is true because this is used for the thread flip.
1900 MarkRoot</*kGrayImmuneObject*/true>(root);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001901 }
1902 }
1903}
1904
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001905// Temporary set gc_grays_immune_objects_ to true in a scope if the current thread is GC.
1906class ConcurrentCopying::ScopedGcGraysImmuneObjects {
1907 public:
1908 explicit ScopedGcGraysImmuneObjects(ConcurrentCopying* collector)
1909 : collector_(collector), enabled_(false) {
1910 if (kUseBakerReadBarrier &&
1911 collector_->thread_running_gc_ == Thread::Current() &&
1912 !collector_->gc_grays_immune_objects_) {
1913 collector_->gc_grays_immune_objects_ = true;
1914 enabled_ = true;
1915 }
1916 }
1917
1918 ~ScopedGcGraysImmuneObjects() {
1919 if (kUseBakerReadBarrier &&
1920 collector_->thread_running_gc_ == Thread::Current() &&
1921 enabled_) {
1922 DCHECK(collector_->gc_grays_immune_objects_);
1923 collector_->gc_grays_immune_objects_ = false;
1924 }
1925 }
1926
1927 private:
1928 ConcurrentCopying* const collector_;
1929 bool enabled_;
1930};
1931
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001932// Fill the given memory block with a dummy object. Used to fill in a
1933// copy of objects that was lost in race.
1934void ConcurrentCopying::FillWithDummyObject(mirror::Object* dummy_obj, size_t byte_size) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001935 // GC doesn't gray immune objects while scanning immune objects. But we need to trigger the read
1936 // barriers here because we need the updated reference to the int array class, etc. Temporary set
1937 // gc_grays_immune_objects_ to true so that we won't cause a DCHECK failure in MarkImmuneSpace().
1938 ScopedGcGraysImmuneObjects scoped_gc_gray_immune_objects(this);
Roland Levillain14d90572015-07-16 10:52:26 +01001939 CHECK_ALIGNED(byte_size, kObjectAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001940 memset(dummy_obj, 0, byte_size);
Mathieu Chartierd6636d32016-07-28 11:02:38 -07001941 // Avoid going through read barrier for since kDisallowReadBarrierDuringScan may be enabled.
1942 // Explicitly mark to make sure to get an object in the to-space.
1943 mirror::Class* int_array_class = down_cast<mirror::Class*>(
1944 Mark(mirror::IntArray::GetArrayClass<kWithoutReadBarrier>()));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001945 CHECK(int_array_class != nullptr);
1946 AssertToSpaceInvariant(nullptr, MemberOffset(0), int_array_class);
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07001947 size_t component_size = int_array_class->GetComponentSize<kWithoutReadBarrier>();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001948 CHECK_EQ(component_size, sizeof(int32_t));
1949 size_t data_offset = mirror::Array::DataOffset(component_size).SizeValue();
1950 if (data_offset > byte_size) {
1951 // An int array is too big. Use java.lang.Object.
1952 mirror::Class* java_lang_Object = WellKnownClasses::ToClass(WellKnownClasses::java_lang_Object);
1953 AssertToSpaceInvariant(nullptr, MemberOffset(0), java_lang_Object);
Mathieu Chartierd6636d32016-07-28 11:02:38 -07001954 CHECK_EQ(byte_size, (java_lang_Object->GetObjectSize<kVerifyNone, kWithoutReadBarrier>()));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001955 dummy_obj->SetClass(java_lang_Object);
Mathieu Chartierd6636d32016-07-28 11:02:38 -07001956 CHECK_EQ(byte_size, (dummy_obj->SizeOf<kVerifyNone, kWithoutReadBarrier>()));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001957 } else {
1958 // Use an int array.
1959 dummy_obj->SetClass(int_array_class);
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07001960 CHECK((dummy_obj->IsArrayInstance<kVerifyNone, kWithoutReadBarrier>()));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001961 int32_t length = (byte_size - data_offset) / component_size;
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07001962 mirror::Array* dummy_arr = dummy_obj->AsArray<kVerifyNone, kWithoutReadBarrier>();
1963 dummy_arr->SetLength(length);
1964 CHECK_EQ(dummy_arr->GetLength(), length)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001965 << "byte_size=" << byte_size << " length=" << length
1966 << " component_size=" << component_size << " data_offset=" << data_offset;
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07001967 CHECK_EQ(byte_size, (dummy_obj->SizeOf<kVerifyNone, kWithoutReadBarrier>()))
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001968 << "byte_size=" << byte_size << " length=" << length
1969 << " component_size=" << component_size << " data_offset=" << data_offset;
1970 }
1971}
1972
1973// Reuse the memory blocks that were copy of objects that were lost in race.
1974mirror::Object* ConcurrentCopying::AllocateInSkippedBlock(size_t alloc_size) {
1975 // Try to reuse the blocks that were unused due to CAS failures.
Roland Levillain14d90572015-07-16 10:52:26 +01001976 CHECK_ALIGNED(alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001977 Thread* self = Thread::Current();
1978 size_t min_object_size = RoundUp(sizeof(mirror::Object), space::RegionSpace::kAlignment);
Mathieu Chartierd6636d32016-07-28 11:02:38 -07001979 size_t byte_size;
1980 uint8_t* addr;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001981 {
Mathieu Chartierd6636d32016-07-28 11:02:38 -07001982 MutexLock mu(self, skipped_blocks_lock_);
1983 auto it = skipped_blocks_map_.lower_bound(alloc_size);
1984 if (it == skipped_blocks_map_.end()) {
1985 // Not found.
1986 return nullptr;
1987 }
1988 byte_size = it->first;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001989 CHECK_GE(byte_size, alloc_size);
1990 if (byte_size > alloc_size && byte_size - alloc_size < min_object_size) {
1991 // If remainder would be too small for a dummy object, retry with a larger request size.
1992 it = skipped_blocks_map_.lower_bound(alloc_size + min_object_size);
1993 if (it == skipped_blocks_map_.end()) {
1994 // Not found.
1995 return nullptr;
1996 }
Roland Levillain14d90572015-07-16 10:52:26 +01001997 CHECK_ALIGNED(it->first - alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001998 CHECK_GE(it->first - alloc_size, min_object_size)
1999 << "byte_size=" << byte_size << " it->first=" << it->first << " alloc_size=" << alloc_size;
2000 }
Mathieu Chartierd6636d32016-07-28 11:02:38 -07002001 // Found a block.
2002 CHECK(it != skipped_blocks_map_.end());
2003 byte_size = it->first;
2004 addr = it->second;
2005 CHECK_GE(byte_size, alloc_size);
2006 CHECK(region_space_->IsInToSpace(reinterpret_cast<mirror::Object*>(addr)));
2007 CHECK_ALIGNED(byte_size, space::RegionSpace::kAlignment);
2008 if (kVerboseMode) {
2009 LOG(INFO) << "Reusing skipped bytes : " << reinterpret_cast<void*>(addr) << ", " << byte_size;
2010 }
2011 skipped_blocks_map_.erase(it);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002012 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002013 memset(addr, 0, byte_size);
2014 if (byte_size > alloc_size) {
2015 // Return the remainder to the map.
Roland Levillain14d90572015-07-16 10:52:26 +01002016 CHECK_ALIGNED(byte_size - alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002017 CHECK_GE(byte_size - alloc_size, min_object_size);
Mathieu Chartierd6636d32016-07-28 11:02:38 -07002018 // FillWithDummyObject may mark an object, avoid holding skipped_blocks_lock_ to prevent lock
2019 // violation and possible deadlock. The deadlock case is a recursive case:
2020 // FillWithDummyObject -> IntArray::GetArrayClass -> Mark -> Copy -> AllocateInSkippedBlock.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002021 FillWithDummyObject(reinterpret_cast<mirror::Object*>(addr + alloc_size),
2022 byte_size - alloc_size);
2023 CHECK(region_space_->IsInToSpace(reinterpret_cast<mirror::Object*>(addr + alloc_size)));
Mathieu Chartierd6636d32016-07-28 11:02:38 -07002024 {
2025 MutexLock mu(self, skipped_blocks_lock_);
2026 skipped_blocks_map_.insert(std::make_pair(byte_size - alloc_size, addr + alloc_size));
2027 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002028 }
2029 return reinterpret_cast<mirror::Object*>(addr);
2030}
2031
2032mirror::Object* ConcurrentCopying::Copy(mirror::Object* from_ref) {
2033 DCHECK(region_space_->IsInFromSpace(from_ref));
2034 // No read barrier to avoid nested RB that might violate the to-space
2035 // invariant. Note that from_ref is a from space ref so the SizeOf()
2036 // call will access the from-space meta objects, but it's ok and necessary.
2037 size_t obj_size = from_ref->SizeOf<kDefaultVerifyFlags, kWithoutReadBarrier>();
2038 size_t region_space_alloc_size = RoundUp(obj_size, space::RegionSpace::kAlignment);
2039 size_t region_space_bytes_allocated = 0U;
2040 size_t non_moving_space_bytes_allocated = 0U;
2041 size_t bytes_allocated = 0U;
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07002042 size_t dummy;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002043 mirror::Object* to_ref = region_space_->AllocNonvirtual<true>(
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07002044 region_space_alloc_size, &region_space_bytes_allocated, nullptr, &dummy);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002045 bytes_allocated = region_space_bytes_allocated;
2046 if (to_ref != nullptr) {
2047 DCHECK_EQ(region_space_alloc_size, region_space_bytes_allocated);
2048 }
2049 bool fall_back_to_non_moving = false;
2050 if (UNLIKELY(to_ref == nullptr)) {
2051 // Failed to allocate in the region space. Try the skipped blocks.
2052 to_ref = AllocateInSkippedBlock(region_space_alloc_size);
2053 if (to_ref != nullptr) {
2054 // Succeeded to allocate in a skipped block.
2055 if (heap_->use_tlab_) {
2056 // This is necessary for the tlab case as it's not accounted in the space.
2057 region_space_->RecordAlloc(to_ref);
2058 }
2059 bytes_allocated = region_space_alloc_size;
2060 } else {
2061 // Fall back to the non-moving space.
2062 fall_back_to_non_moving = true;
2063 if (kVerboseMode) {
2064 LOG(INFO) << "Out of memory in the to-space. Fall back to non-moving. skipped_bytes="
2065 << to_space_bytes_skipped_.LoadSequentiallyConsistent()
2066 << " skipped_objects=" << to_space_objects_skipped_.LoadSequentiallyConsistent();
2067 }
2068 fall_back_to_non_moving = true;
2069 to_ref = heap_->non_moving_space_->Alloc(Thread::Current(), obj_size,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07002070 &non_moving_space_bytes_allocated, nullptr, &dummy);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002071 CHECK(to_ref != nullptr) << "Fall-back non-moving space allocation failed";
2072 bytes_allocated = non_moving_space_bytes_allocated;
2073 // Mark it in the mark bitmap.
2074 accounting::ContinuousSpaceBitmap* mark_bitmap =
2075 heap_mark_bitmap_->GetContinuousSpaceBitmap(to_ref);
2076 CHECK(mark_bitmap != nullptr);
2077 CHECK(!mark_bitmap->AtomicTestAndSet(to_ref));
2078 }
2079 }
2080 DCHECK(to_ref != nullptr);
2081
Mathieu Chartierd818adb2016-09-15 13:12:47 -07002082 // Copy the object excluding the lock word since that is handled in the loop.
2083 to_ref->SetClass(from_ref->GetClass<kVerifyNone, kWithoutReadBarrier>());
2084 const size_t kObjectHeaderSize = sizeof(mirror::Object);
2085 DCHECK_GE(obj_size, kObjectHeaderSize);
2086 static_assert(kObjectHeaderSize == sizeof(mirror::HeapReference<mirror::Class>) +
2087 sizeof(LockWord),
2088 "Object header size does not match");
2089 // Memcpy can tear for words since it may do byte copy. It is only safe to do this since the
2090 // object in the from space is immutable other than the lock word. b/31423258
2091 memcpy(reinterpret_cast<uint8_t*>(to_ref) + kObjectHeaderSize,
2092 reinterpret_cast<const uint8_t*>(from_ref) + kObjectHeaderSize,
2093 obj_size - kObjectHeaderSize);
2094
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002095 // Attempt to install the forward pointer. This is in a loop as the
2096 // lock word atomic write can fail.
2097 while (true) {
Mathieu Chartierd818adb2016-09-15 13:12:47 -07002098 LockWord old_lock_word = from_ref->GetLockWord(false);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002099
2100 if (old_lock_word.GetState() == LockWord::kForwardingAddress) {
2101 // Lost the race. Another thread (either GC or mutator) stored
2102 // the forwarding pointer first. Make the lost copy (to_ref)
2103 // look like a valid but dead (dummy) object and keep it for
2104 // future reuse.
2105 FillWithDummyObject(to_ref, bytes_allocated);
2106 if (!fall_back_to_non_moving) {
2107 DCHECK(region_space_->IsInToSpace(to_ref));
2108 if (bytes_allocated > space::RegionSpace::kRegionSize) {
2109 // Free the large alloc.
2110 region_space_->FreeLarge(to_ref, bytes_allocated);
2111 } else {
2112 // Record the lost copy for later reuse.
2113 heap_->num_bytes_allocated_.FetchAndAddSequentiallyConsistent(bytes_allocated);
2114 to_space_bytes_skipped_.FetchAndAddSequentiallyConsistent(bytes_allocated);
2115 to_space_objects_skipped_.FetchAndAddSequentiallyConsistent(1);
2116 MutexLock mu(Thread::Current(), skipped_blocks_lock_);
2117 skipped_blocks_map_.insert(std::make_pair(bytes_allocated,
2118 reinterpret_cast<uint8_t*>(to_ref)));
2119 }
2120 } else {
2121 DCHECK(heap_->non_moving_space_->HasAddress(to_ref));
2122 DCHECK_EQ(bytes_allocated, non_moving_space_bytes_allocated);
2123 // Free the non-moving-space chunk.
2124 accounting::ContinuousSpaceBitmap* mark_bitmap =
2125 heap_mark_bitmap_->GetContinuousSpaceBitmap(to_ref);
2126 CHECK(mark_bitmap != nullptr);
2127 CHECK(mark_bitmap->Clear(to_ref));
2128 heap_->non_moving_space_->Free(Thread::Current(), to_ref);
2129 }
2130
2131 // Get the winner's forward ptr.
2132 mirror::Object* lost_fwd_ptr = to_ref;
2133 to_ref = reinterpret_cast<mirror::Object*>(old_lock_word.ForwardingAddress());
2134 CHECK(to_ref != nullptr);
2135 CHECK_NE(to_ref, lost_fwd_ptr);
Mathieu Chartierdfcd6f42016-09-13 10:02:48 -07002136 CHECK(region_space_->IsInToSpace(to_ref) || heap_->non_moving_space_->HasAddress(to_ref))
2137 << "to_ref=" << to_ref << " " << heap_->DumpSpaces();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002138 CHECK_NE(to_ref->GetLockWord(false).GetState(), LockWord::kForwardingAddress);
2139 return to_ref;
2140 }
2141
Mathieu Chartierd818adb2016-09-15 13:12:47 -07002142 // Copy the old lock word over since we did not copy it yet.
2143 to_ref->SetLockWord(old_lock_word, false);
Hiroshi Yamauchi60f63f52015-04-23 16:12:40 -07002144 // Set the gray ptr.
2145 if (kUseBakerReadBarrier) {
2146 to_ref->SetReadBarrierPointer(ReadBarrier::GrayPtr());
2147 }
2148
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002149 LockWord new_lock_word = LockWord::FromForwardingAddress(reinterpret_cast<size_t>(to_ref));
2150
2151 // Try to atomically write the fwd ptr.
2152 bool success = from_ref->CasLockWordWeakSequentiallyConsistent(old_lock_word, new_lock_word);
2153 if (LIKELY(success)) {
2154 // The CAS succeeded.
2155 objects_moved_.FetchAndAddSequentiallyConsistent(1);
2156 bytes_moved_.FetchAndAddSequentiallyConsistent(region_space_alloc_size);
2157 if (LIKELY(!fall_back_to_non_moving)) {
2158 DCHECK(region_space_->IsInToSpace(to_ref));
2159 } else {
2160 DCHECK(heap_->non_moving_space_->HasAddress(to_ref));
2161 DCHECK_EQ(bytes_allocated, non_moving_space_bytes_allocated);
2162 }
2163 if (kUseBakerReadBarrier) {
2164 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr());
2165 }
2166 DCHECK(GetFwdPtr(from_ref) == to_ref);
2167 CHECK_NE(to_ref->GetLockWord(false).GetState(), LockWord::kForwardingAddress);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002168 PushOntoMarkStack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002169 return to_ref;
2170 } else {
2171 // The CAS failed. It may have lost the race or may have failed
2172 // due to monitor/hashcode ops. Either way, retry.
2173 }
2174 }
2175}
2176
2177mirror::Object* ConcurrentCopying::IsMarked(mirror::Object* from_ref) {
2178 DCHECK(from_ref != nullptr);
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08002179 space::RegionSpace::RegionType rtype = region_space_->GetRegionType(from_ref);
2180 if (rtype == space::RegionSpace::RegionType::kRegionTypeToSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002181 // It's already marked.
2182 return from_ref;
2183 }
2184 mirror::Object* to_ref;
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08002185 if (rtype == space::RegionSpace::RegionType::kRegionTypeFromSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002186 to_ref = GetFwdPtr(from_ref);
2187 DCHECK(to_ref == nullptr || region_space_->IsInToSpace(to_ref) ||
2188 heap_->non_moving_space_->HasAddress(to_ref))
2189 << "from_ref=" << from_ref << " to_ref=" << to_ref;
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08002190 } else if (rtype == space::RegionSpace::RegionType::kRegionTypeUnevacFromSpace) {
Mathieu Chartierc381c362016-08-23 13:27:53 -07002191 if (IsMarkedInUnevacFromSpace(from_ref)) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002192 to_ref = from_ref;
2193 } else {
2194 to_ref = nullptr;
2195 }
2196 } else {
2197 // from_ref is in a non-moving space.
Mathieu Chartier763a31e2015-11-16 16:05:55 -08002198 if (immune_spaces_.ContainsObject(from_ref)) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002199 // An immune object is alive.
2200 to_ref = from_ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002201 } else {
2202 // Non-immune non-moving space. Use the mark bitmap.
2203 accounting::ContinuousSpaceBitmap* mark_bitmap =
2204 heap_mark_bitmap_->GetContinuousSpaceBitmap(from_ref);
2205 accounting::LargeObjectBitmap* los_bitmap =
2206 heap_mark_bitmap_->GetLargeObjectBitmap(from_ref);
2207 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
2208 bool is_los = mark_bitmap == nullptr;
2209 if (!is_los && mark_bitmap->Test(from_ref)) {
2210 // Already marked.
2211 to_ref = from_ref;
2212 } else if (is_los && los_bitmap->Test(from_ref)) {
2213 // Already marked in LOS.
2214 to_ref = from_ref;
2215 } else {
2216 // Not marked.
2217 if (IsOnAllocStack(from_ref)) {
2218 // If on the allocation stack, it's considered marked.
2219 to_ref = from_ref;
2220 } else {
2221 // Not marked.
2222 to_ref = nullptr;
2223 }
2224 }
2225 }
2226 }
2227 return to_ref;
2228}
2229
2230bool ConcurrentCopying::IsOnAllocStack(mirror::Object* ref) {
2231 QuasiAtomic::ThreadFenceAcquire();
2232 accounting::ObjectStack* alloc_stack = GetAllocationStack();
Mathieu Chartiercb535da2015-01-23 13:50:03 -08002233 return alloc_stack->Contains(ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002234}
2235
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002236mirror::Object* ConcurrentCopying::MarkNonMoving(mirror::Object* ref) {
2237 // ref is in a non-moving space (from_ref == to_ref).
2238 DCHECK(!region_space_->HasAddress(ref)) << ref;
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002239 DCHECK(!immune_spaces_.ContainsObject(ref));
2240 // Use the mark bitmap.
2241 accounting::ContinuousSpaceBitmap* mark_bitmap =
2242 heap_mark_bitmap_->GetContinuousSpaceBitmap(ref);
2243 accounting::LargeObjectBitmap* los_bitmap =
2244 heap_mark_bitmap_->GetLargeObjectBitmap(ref);
2245 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
2246 bool is_los = mark_bitmap == nullptr;
2247 if (!is_los && mark_bitmap->Test(ref)) {
2248 // Already marked.
2249 if (kUseBakerReadBarrier) {
2250 DCHECK(ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr() ||
2251 ref->GetReadBarrierPointer() == ReadBarrier::WhitePtr());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002252 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002253 } else if (is_los && los_bitmap->Test(ref)) {
2254 // Already marked in LOS.
2255 if (kUseBakerReadBarrier) {
2256 DCHECK(ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr() ||
2257 ref->GetReadBarrierPointer() == ReadBarrier::WhitePtr());
2258 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002259 } else {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002260 // Not marked.
2261 if (IsOnAllocStack(ref)) {
2262 // If it's on the allocation stack, it's considered marked. Keep it white.
2263 // Objects on the allocation stack need not be marked.
2264 if (!is_los) {
2265 DCHECK(!mark_bitmap->Test(ref));
2266 } else {
2267 DCHECK(!los_bitmap->Test(ref));
Nicolas Geoffrayddeb1722016-06-28 08:25:59 +00002268 }
Nicolas Geoffrayddeb1722016-06-28 08:25:59 +00002269 if (kUseBakerReadBarrier) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002270 DCHECK_EQ(ref->GetReadBarrierPointer(), ReadBarrier::WhitePtr());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002271 }
2272 } else {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002273 // For the baker-style RB, we need to handle 'false-gray' cases. See the
2274 // kRegionTypeUnevacFromSpace-case comment in Mark().
2275 if (kUseBakerReadBarrier) {
2276 // Test the bitmap first to reduce the chance of false gray cases.
2277 if ((!is_los && mark_bitmap->Test(ref)) ||
2278 (is_los && los_bitmap->Test(ref))) {
2279 return ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002280 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002281 }
2282 // Not marked or on the allocation stack. Try to mark it.
2283 // This may or may not succeed, which is ok.
2284 bool cas_success = false;
2285 if (kUseBakerReadBarrier) {
2286 cas_success = ref->AtomicSetReadBarrierPointer(ReadBarrier::WhitePtr(),
2287 ReadBarrier::GrayPtr());
2288 }
2289 if (!is_los && mark_bitmap->AtomicTestAndSet(ref)) {
2290 // Already marked.
2291 if (kUseBakerReadBarrier && cas_success &&
2292 ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr()) {
2293 PushOntoFalseGrayStack(ref);
2294 }
2295 } else if (is_los && los_bitmap->AtomicTestAndSet(ref)) {
2296 // Already marked in LOS.
2297 if (kUseBakerReadBarrier && cas_success &&
2298 ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr()) {
2299 PushOntoFalseGrayStack(ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002300 }
2301 } else {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002302 // Newly marked.
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08002303 if (kUseBakerReadBarrier) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002304 DCHECK_EQ(ref->GetReadBarrierPointer(), ReadBarrier::GrayPtr());
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08002305 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002306 PushOntoMarkStack(ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002307 }
2308 }
2309 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002310 return ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002311}
2312
2313void ConcurrentCopying::FinishPhase() {
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -08002314 Thread* const self = Thread::Current();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002315 {
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -08002316 MutexLock mu(self, mark_stack_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002317 CHECK_EQ(pooled_mark_stacks_.size(), kMarkStackPoolSize);
2318 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002319 region_space_ = nullptr;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002320 {
2321 MutexLock mu(Thread::Current(), skipped_blocks_lock_);
2322 skipped_blocks_map_.clear();
2323 }
Mathieu Chartier56fe2582016-07-14 13:30:03 -07002324 {
2325 ReaderMutexLock mu(self, *Locks::mutator_lock_);
Mathieu Chartier21328a12016-07-22 10:47:45 -07002326 {
2327 WriterMutexLock mu2(self, *Locks::heap_bitmap_lock_);
2328 heap_->ClearMarkedObjects();
2329 }
2330 if (kUseBakerReadBarrier && kFilterModUnionCards) {
2331 TimingLogger::ScopedTiming split("FilterModUnionCards", GetTimings());
2332 ReaderMutexLock mu2(self, *Locks::heap_bitmap_lock_);
2333 gc::Heap* const heap = Runtime::Current()->GetHeap();
2334 for (space::ContinuousSpace* space : immune_spaces_.GetSpaces()) {
2335 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
2336 accounting::ModUnionTable* table = heap->FindModUnionTableFromSpace(space);
2337 // Filter out cards that don't need to be set.
2338 if (table != nullptr) {
2339 table->FilterCards();
2340 }
2341 }
2342 }
Mathieu Chartier36a270a2016-07-28 18:08:51 -07002343 if (kUseBakerReadBarrier) {
2344 TimingLogger::ScopedTiming split("EmptyRBMarkBitStack", GetTimings());
2345 DCHECK(rb_mark_bit_stack_.get() != nullptr);
2346 const auto* limit = rb_mark_bit_stack_->End();
2347 for (StackReference<mirror::Object>* it = rb_mark_bit_stack_->Begin(); it != limit; ++it) {
2348 CHECK(it->AsMirrorPtr()->AtomicSetMarkBit(1, 0));
2349 }
2350 rb_mark_bit_stack_->Reset();
2351 }
Mathieu Chartier56fe2582016-07-14 13:30:03 -07002352 }
2353 if (measure_read_barrier_slow_path_) {
2354 MutexLock mu(self, rb_slow_path_histogram_lock_);
2355 rb_slow_path_time_histogram_.AdjustAndAddValue(rb_slow_path_ns_.LoadRelaxed());
2356 rb_slow_path_count_total_ += rb_slow_path_count_.LoadRelaxed();
2357 rb_slow_path_count_gc_total_ += rb_slow_path_count_gc_.LoadRelaxed();
2358 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002359}
2360
Mathieu Chartier97509952015-07-13 14:35:43 -07002361bool ConcurrentCopying::IsMarkedHeapReference(mirror::HeapReference<mirror::Object>* field) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002362 mirror::Object* from_ref = field->AsMirrorPtr();
Mathieu Chartier97509952015-07-13 14:35:43 -07002363 mirror::Object* to_ref = IsMarked(from_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002364 if (to_ref == nullptr) {
2365 return false;
2366 }
2367 if (from_ref != to_ref) {
2368 QuasiAtomic::ThreadFenceRelease();
2369 field->Assign(to_ref);
2370 QuasiAtomic::ThreadFenceSequentiallyConsistent();
2371 }
2372 return true;
2373}
2374
Mathieu Chartier97509952015-07-13 14:35:43 -07002375mirror::Object* ConcurrentCopying::MarkObject(mirror::Object* from_ref) {
2376 return Mark(from_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002377}
2378
2379void ConcurrentCopying::DelayReferenceReferent(mirror::Class* klass, mirror::Reference* reference) {
Mathieu Chartier97509952015-07-13 14:35:43 -07002380 heap_->GetReferenceProcessor()->DelayReferenceReferent(klass, reference, this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002381}
2382
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002383void ConcurrentCopying::ProcessReferences(Thread* self) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002384 TimingLogger::ScopedTiming split("ProcessReferences", GetTimings());
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002385 // 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 -08002386 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
2387 GetHeap()->GetReferenceProcessor()->ProcessReferences(
Mathieu Chartier97509952015-07-13 14:35:43 -07002388 true /*concurrent*/, GetTimings(), GetCurrentIteration()->GetClearSoftReferences(), this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002389}
2390
2391void ConcurrentCopying::RevokeAllThreadLocalBuffers() {
2392 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
2393 region_space_->RevokeAllThreadLocalBuffers();
2394}
2395
Mathieu Chartier56fe2582016-07-14 13:30:03 -07002396mirror::Object* ConcurrentCopying::MarkFromReadBarrierWithMeasurements(mirror::Object* from_ref) {
2397 if (Thread::Current() != thread_running_gc_) {
2398 rb_slow_path_count_.FetchAndAddRelaxed(1u);
2399 } else {
2400 rb_slow_path_count_gc_.FetchAndAddRelaxed(1u);
2401 }
2402 ScopedTrace tr(__FUNCTION__);
2403 const uint64_t start_time = measure_read_barrier_slow_path_ ? NanoTime() : 0u;
2404 mirror::Object* ret = Mark(from_ref);
2405 if (measure_read_barrier_slow_path_) {
2406 rb_slow_path_ns_.FetchAndAddRelaxed(NanoTime() - start_time);
2407 }
2408 return ret;
2409}
2410
2411void ConcurrentCopying::DumpPerformanceInfo(std::ostream& os) {
2412 GarbageCollector::DumpPerformanceInfo(os);
2413 MutexLock mu(Thread::Current(), rb_slow_path_histogram_lock_);
2414 if (rb_slow_path_time_histogram_.SampleSize() > 0) {
2415 Histogram<uint64_t>::CumulativeData cumulative_data;
2416 rb_slow_path_time_histogram_.CreateHistogram(&cumulative_data);
2417 rb_slow_path_time_histogram_.PrintConfidenceIntervals(os, 0.99, cumulative_data);
2418 }
2419 if (rb_slow_path_count_total_ > 0) {
2420 os << "Slow path count " << rb_slow_path_count_total_ << "\n";
2421 }
2422 if (rb_slow_path_count_gc_total_ > 0) {
2423 os << "GC slow path count " << rb_slow_path_count_gc_total_ << "\n";
2424 }
Mathieu Chartiercca44a02016-08-17 10:07:29 -07002425 os << "Cumulative bytes moved " << cumulative_bytes_moved_.LoadRelaxed() << "\n";
2426 os << "Cumulative objects moved " << cumulative_objects_moved_.LoadRelaxed() << "\n";
Mathieu Chartier56fe2582016-07-14 13:30:03 -07002427}
2428
Hiroshi Yamauchid5307ec2014-03-27 21:07:51 -07002429} // namespace collector
2430} // namespace gc
2431} // namespace art