blob: 975ac364d0308606f36543ed31e4f64cd4e0f832 [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();
433 region_space_->DumpNonFreeRegions(LOG(INFO));
434 }
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();
450 region_space_->DumpNonFreeRegions(LOG(INFO));
451 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 Yamauchi0b713572015-06-16 18:29:23 -0700571 CHECK(weak_ref_access_enabled_);
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700572
573 // Scan immune spaces.
574 // Update all the fields in the immune spaces first without graying the objects so that we
575 // minimize dirty pages in the immune spaces. Note mutators can concurrently access and gray some
576 // of the objects.
577 if (kUseBakerReadBarrier) {
578 gc_grays_immune_objects_ = false;
Hiroshi Yamauchi16292fc2016-06-20 20:23:34 -0700579 }
Mathieu Chartier21328a12016-07-22 10:47:45 -0700580 {
581 TimingLogger::ScopedTiming split2("ScanImmuneSpaces", GetTimings());
582 for (auto& space : immune_spaces_.GetSpaces()) {
583 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
584 accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
Hiroshi Yamauchi5408f232016-07-29 15:07:05 -0700585 accounting::ModUnionTable* table = heap_->FindModUnionTableFromSpace(space);
Mathieu Chartier21328a12016-07-22 10:47:45 -0700586 ImmuneSpaceScanObjVisitor visitor(this);
Hiroshi Yamauchi5408f232016-07-29 15:07:05 -0700587 if (kUseBakerReadBarrier && kGrayDirtyImmuneObjects && table != nullptr) {
588 table->VisitObjects(ImmuneSpaceScanObjVisitor::Callback, &visitor);
589 } else {
590 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()),
591 reinterpret_cast<uintptr_t>(space->Limit()),
592 visitor);
593 }
Mathieu Chartier21328a12016-07-22 10:47:45 -0700594 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700595 }
596 if (kUseBakerReadBarrier) {
597 // This release fence makes the field updates in the above loop visible before allowing mutator
598 // getting access to immune objects without graying it first.
599 updated_all_immune_objects_.StoreRelease(true);
600 // Now whiten immune objects concurrently accessed and grayed by mutators. We can't do this in
601 // the above loop because we would incorrectly disable the read barrier by whitening an object
602 // which may point to an unscanned, white object, breaking the to-space invariant.
603 //
604 // Make sure no mutators are in the middle of marking an immune object before whitening immune
605 // objects.
606 IssueEmptyCheckpoint();
607 MutexLock mu(Thread::Current(), immune_gray_stack_lock_);
608 if (kVerboseMode) {
609 LOG(INFO) << "immune gray stack size=" << immune_gray_stack_.size();
610 }
611 for (mirror::Object* obj : immune_gray_stack_) {
612 DCHECK(obj->GetReadBarrierPointer() == ReadBarrier::GrayPtr());
613 bool success = obj->AtomicSetReadBarrierPointer(ReadBarrier::GrayPtr(),
614 ReadBarrier::WhitePtr());
615 DCHECK(success);
616 }
617 immune_gray_stack_.clear();
618 }
619
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800620 {
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -0700621 TimingLogger::ScopedTiming split2("VisitConcurrentRoots", GetTimings());
622 Runtime::Current()->VisitConcurrentRoots(this, kVisitRootFlagAllRoots);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800623 }
624 {
625 // TODO: don't visit the transaction roots if it's not active.
626 TimingLogger::ScopedTiming split5("VisitNonThreadRoots", GetTimings());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700627 Runtime::Current()->VisitNonThreadRoots(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800628 }
629
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800630 Thread* self = Thread::Current();
631 {
Mathieu Chartiera6b1ead2015-10-06 10:32:38 -0700632 TimingLogger::ScopedTiming split7("ProcessMarkStack", GetTimings());
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700633 // We transition through three mark stack modes (thread-local, shared, GC-exclusive). The
634 // primary reasons are the fact that we need to use a checkpoint to process thread-local mark
635 // stacks, but after we disable weak refs accesses, we can't use a checkpoint due to a deadlock
636 // issue because running threads potentially blocking at WaitHoldingLocks, and that once we
637 // reach the point where we process weak references, we can avoid using a lock when accessing
638 // the GC mark stack, which makes mark stack processing more efficient.
639
640 // Process the mark stack once in the thread local stack mode. This marks most of the live
641 // objects, aside from weak ref accesses with read barriers (Reference::GetReferent() and system
642 // weaks) that may happen concurrently while we processing the mark stack and newly mark/gray
643 // objects and push refs on the mark stack.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800644 ProcessMarkStack();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700645 // Switch to the shared mark stack mode. That is, revoke and process thread-local mark stacks
646 // for the last time before transitioning to the shared mark stack mode, which would process new
647 // refs that may have been concurrently pushed onto the mark stack during the ProcessMarkStack()
648 // call above. At the same time, disable weak ref accesses using a per-thread flag. It's
649 // important to do these together in a single checkpoint so that we can ensure that mutators
650 // won't newly gray objects and push new refs onto the mark stack due to weak ref accesses and
651 // mutators safely transition to the shared mark stack mode (without leaving unprocessed refs on
652 // the thread-local mark stacks), without a race. This is why we use a thread-local weak ref
653 // access flag Thread::tls32_.weak_ref_access_enabled_ instead of the global ones.
654 SwitchToSharedMarkStackMode();
655 CHECK(!self->GetWeakRefAccessEnabled());
656 // Now that weak refs accesses are disabled, once we exhaust the shared mark stack again here
657 // (which may be non-empty if there were refs found on thread-local mark stacks during the above
658 // SwitchToSharedMarkStackMode() call), we won't have new refs to process, that is, mutators
659 // (via read barriers) have no way to produce any more refs to process. Marking converges once
660 // before we process weak refs below.
661 ProcessMarkStack();
662 CheckEmptyMarkStack();
663 // Switch to the GC exclusive mark stack mode so that we can process the mark stack without a
664 // lock from this point on.
665 SwitchToGcExclusiveMarkStackMode();
666 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800667 if (kVerboseMode) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800668 LOG(INFO) << "ProcessReferences";
669 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700670 // Process weak references. This may produce new refs to process and have them processed via
Mathieu Chartier97509952015-07-13 14:35:43 -0700671 // ProcessMarkStack (in the GC exclusive mark stack mode).
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700672 ProcessReferences(self);
673 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800674 if (kVerboseMode) {
675 LOG(INFO) << "SweepSystemWeaks";
676 }
677 SweepSystemWeaks(self);
678 if (kVerboseMode) {
679 LOG(INFO) << "SweepSystemWeaks done";
680 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700681 // Process the mark stack here one last time because the above SweepSystemWeaks() call may have
682 // marked some objects (strings alive) as hash_set::Erase() can call the hash function for
683 // arbitrary elements in the weak intern table in InternTable::Table::SweepWeaks().
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800684 ProcessMarkStack();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700685 CheckEmptyMarkStack();
686 // Re-enable weak ref accesses.
687 ReenableWeakRefAccess(self);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -0700688 // Free data for class loaders that we unloaded.
689 Runtime::Current()->GetClassLinker()->CleanupClassLoaders();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700690 // Marking is done. Disable marking.
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700691 DisableMarking();
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800692 if (kUseBakerReadBarrier) {
693 ProcessFalseGrayStack();
694 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700695 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800696 }
697
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700698 CHECK(weak_ref_access_enabled_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800699 if (kVerboseMode) {
700 LOG(INFO) << "GC end of MarkingPhase";
701 }
702}
703
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700704void ConcurrentCopying::ReenableWeakRefAccess(Thread* self) {
705 if (kVerboseMode) {
706 LOG(INFO) << "ReenableWeakRefAccess";
707 }
708 weak_ref_access_enabled_.StoreRelaxed(true); // This is for new threads.
709 QuasiAtomic::ThreadFenceForConstructor();
710 // Iterate all threads (don't need to or can't use a checkpoint) and re-enable weak ref access.
711 {
712 MutexLock mu(self, *Locks::thread_list_lock_);
713 std::list<Thread*> thread_list = Runtime::Current()->GetThreadList()->GetList();
714 for (Thread* thread : thread_list) {
715 thread->SetWeakRefAccessEnabled(true);
716 }
717 }
718 // Unblock blocking threads.
719 GetHeap()->GetReferenceProcessor()->BroadcastForSlowPath(self);
720 Runtime::Current()->BroadcastForNewSystemWeaks();
721}
722
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700723class ConcurrentCopying::DisableMarkingCheckpoint : public Closure {
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700724 public:
725 explicit DisableMarkingCheckpoint(ConcurrentCopying* concurrent_copying)
726 : concurrent_copying_(concurrent_copying) {
727 }
728
729 void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
730 // Note: self is not necessarily equal to thread since thread may be suspended.
731 Thread* self = Thread::Current();
732 DCHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
733 << thread->GetState() << " thread " << thread << " self " << self;
734 // Disable the thread-local is_gc_marking flag.
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -0700735 // Note a thread that has just started right before this checkpoint may have already this flag
736 // set to false, which is ok.
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700737 thread->SetIsGcMarking(false);
738 // If thread is a running mutator, then act on behalf of the garbage collector.
739 // See the code in ThreadList::RunCheckpoint.
Mathieu Chartier10d25082015-10-28 18:36:09 -0700740 concurrent_copying_->GetBarrier().Pass(self);
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700741 }
742
743 private:
744 ConcurrentCopying* const concurrent_copying_;
745};
746
747void ConcurrentCopying::IssueDisableMarkingCheckpoint() {
748 Thread* self = Thread::Current();
749 DisableMarkingCheckpoint check_point(this);
750 ThreadList* thread_list = Runtime::Current()->GetThreadList();
751 gc_barrier_->Init(self, 0);
752 size_t barrier_count = thread_list->RunCheckpoint(&check_point);
753 // If there are no threads to wait which implies that all the checkpoint functions are finished,
754 // then no need to release the mutator lock.
755 if (barrier_count == 0) {
756 return;
757 }
758 // Release locks then wait for all mutator threads to pass the barrier.
759 Locks::mutator_lock_->SharedUnlock(self);
760 {
761 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
762 gc_barrier_->Increment(self, barrier_count);
763 }
764 Locks::mutator_lock_->SharedLock(self);
765}
766
767void ConcurrentCopying::DisableMarking() {
768 // Change the global is_marking flag to false. Do a fence before doing a checkpoint to update the
769 // thread-local flags so that a new thread starting up will get the correct is_marking flag.
770 is_marking_ = false;
771 QuasiAtomic::ThreadFenceForConstructor();
772 // Use a checkpoint to turn off the thread-local is_gc_marking flags and to ensure no threads are
773 // still in the middle of a read barrier which may have a from-space ref cached in a local
774 // variable.
775 IssueDisableMarkingCheckpoint();
776 if (kUseTableLookupReadBarrier) {
777 heap_->rb_table_->ClearAll();
778 DCHECK(heap_->rb_table_->IsAllCleared());
779 }
780 is_mark_stack_push_disallowed_.StoreSequentiallyConsistent(1);
781 mark_stack_mode_.StoreSequentiallyConsistent(kMarkStackModeOff);
782}
783
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800784void ConcurrentCopying::PushOntoFalseGrayStack(mirror::Object* ref) {
785 CHECK(kUseBakerReadBarrier);
786 DCHECK(ref != nullptr);
787 MutexLock mu(Thread::Current(), mark_stack_lock_);
788 false_gray_stack_.push_back(ref);
789}
790
791void ConcurrentCopying::ProcessFalseGrayStack() {
792 CHECK(kUseBakerReadBarrier);
793 // Change the objects on the false gray stack from gray to white.
794 MutexLock mu(Thread::Current(), mark_stack_lock_);
795 for (mirror::Object* obj : false_gray_stack_) {
796 DCHECK(IsMarked(obj));
797 // The object could be white here if a thread got preempted after a success at the
798 // AtomicSetReadBarrierPointer in Mark(), GC started marking through it (but not finished so
799 // still gray), and the thread ran to register it onto the false gray stack.
800 if (obj->GetReadBarrierPointer() == ReadBarrier::GrayPtr()) {
801 bool success = obj->AtomicSetReadBarrierPointer(ReadBarrier::GrayPtr(),
802 ReadBarrier::WhitePtr());
803 DCHECK(success);
804 }
805 }
806 false_gray_stack_.clear();
807}
808
809
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800810void ConcurrentCopying::IssueEmptyCheckpoint() {
811 Thread* self = Thread::Current();
812 EmptyCheckpoint check_point(this);
813 ThreadList* thread_list = Runtime::Current()->GetThreadList();
814 gc_barrier_->Init(self, 0);
815 size_t barrier_count = thread_list->RunCheckpoint(&check_point);
Lei Lidd9943d2015-02-02 14:24:44 +0800816 // If there are no threads to wait which implys that all the checkpoint functions are finished,
817 // then no need to release the mutator lock.
818 if (barrier_count == 0) {
819 return;
820 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800821 // Release locks then wait for all mutator threads to pass the barrier.
822 Locks::mutator_lock_->SharedUnlock(self);
823 {
824 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
825 gc_barrier_->Increment(self, barrier_count);
826 }
827 Locks::mutator_lock_->SharedLock(self);
828}
829
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -0700830void ConcurrentCopying::ExpandGcMarkStack() {
831 DCHECK(gc_mark_stack_->IsFull());
832 const size_t new_size = gc_mark_stack_->Capacity() * 2;
833 std::vector<StackReference<mirror::Object>> temp(gc_mark_stack_->Begin(),
834 gc_mark_stack_->End());
835 gc_mark_stack_->Resize(new_size);
836 for (auto& ref : temp) {
837 gc_mark_stack_->PushBack(ref.AsMirrorPtr());
838 }
839 DCHECK(!gc_mark_stack_->IsFull());
840}
841
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800842void ConcurrentCopying::PushOntoMarkStack(mirror::Object* to_ref) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700843 CHECK_EQ(is_mark_stack_push_disallowed_.LoadRelaxed(), 0)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800844 << " " << to_ref << " " << PrettyTypeOf(to_ref);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700845 Thread* self = Thread::Current(); // TODO: pass self as an argument from call sites?
846 CHECK(thread_running_gc_ != nullptr);
847 MarkStackMode mark_stack_mode = mark_stack_mode_.LoadRelaxed();
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -0700848 if (LIKELY(mark_stack_mode == kMarkStackModeThreadLocal)) {
849 if (LIKELY(self == thread_running_gc_)) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700850 // If GC-running thread, use the GC mark stack instead of a thread-local mark stack.
851 CHECK(self->GetThreadLocalMarkStack() == nullptr);
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -0700852 if (UNLIKELY(gc_mark_stack_->IsFull())) {
853 ExpandGcMarkStack();
854 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700855 gc_mark_stack_->PushBack(to_ref);
856 } else {
857 // Otherwise, use a thread-local mark stack.
858 accounting::AtomicStack<mirror::Object>* tl_mark_stack = self->GetThreadLocalMarkStack();
859 if (UNLIKELY(tl_mark_stack == nullptr || tl_mark_stack->IsFull())) {
860 MutexLock mu(self, mark_stack_lock_);
861 // Get a new thread local mark stack.
862 accounting::AtomicStack<mirror::Object>* new_tl_mark_stack;
863 if (!pooled_mark_stacks_.empty()) {
864 // Use a pooled mark stack.
865 new_tl_mark_stack = pooled_mark_stacks_.back();
866 pooled_mark_stacks_.pop_back();
867 } else {
868 // None pooled. Create a new one.
869 new_tl_mark_stack =
870 accounting::AtomicStack<mirror::Object>::Create(
871 "thread local mark stack", 4 * KB, 4 * KB);
872 }
873 DCHECK(new_tl_mark_stack != nullptr);
874 DCHECK(new_tl_mark_stack->IsEmpty());
875 new_tl_mark_stack->PushBack(to_ref);
876 self->SetThreadLocalMarkStack(new_tl_mark_stack);
877 if (tl_mark_stack != nullptr) {
878 // Store the old full stack into a vector.
879 revoked_mark_stacks_.push_back(tl_mark_stack);
880 }
881 } else {
882 tl_mark_stack->PushBack(to_ref);
883 }
884 }
885 } else if (mark_stack_mode == kMarkStackModeShared) {
886 // Access the shared GC mark stack with a lock.
887 MutexLock mu(self, mark_stack_lock_);
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -0700888 if (UNLIKELY(gc_mark_stack_->IsFull())) {
889 ExpandGcMarkStack();
890 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700891 gc_mark_stack_->PushBack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800892 } else {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700893 CHECK_EQ(static_cast<uint32_t>(mark_stack_mode),
Hiroshi Yamauchifa755182015-09-30 20:12:11 -0700894 static_cast<uint32_t>(kMarkStackModeGcExclusive))
895 << "ref=" << to_ref
896 << " self->gc_marking=" << self->GetIsGcMarking()
897 << " cc->is_marking=" << is_marking_;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700898 CHECK(self == thread_running_gc_)
899 << "Only GC-running thread should access the mark stack "
900 << "in the GC exclusive mark stack mode";
901 // Access the GC mark stack without a lock.
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -0700902 if (UNLIKELY(gc_mark_stack_->IsFull())) {
903 ExpandGcMarkStack();
904 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700905 gc_mark_stack_->PushBack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800906 }
907}
908
909accounting::ObjectStack* ConcurrentCopying::GetAllocationStack() {
910 return heap_->allocation_stack_.get();
911}
912
913accounting::ObjectStack* ConcurrentCopying::GetLiveStack() {
914 return heap_->live_stack_.get();
915}
916
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800917// The following visitors are used to verify that there's no references to the from-space left after
918// marking.
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700919class ConcurrentCopying::VerifyNoFromSpaceRefsVisitor : public SingleRootVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800920 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700921 explicit VerifyNoFromSpaceRefsVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800922 : collector_(collector) {}
923
924 void operator()(mirror::Object* ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700925 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800926 if (ref == nullptr) {
927 // OK.
928 return;
929 }
930 collector_->AssertToSpaceInvariant(nullptr, MemberOffset(0), ref);
931 if (kUseBakerReadBarrier) {
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700932 CHECK_EQ(ref->GetReadBarrierPointer(), ReadBarrier::WhitePtr())
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800933 << "Ref " << ref << " " << PrettyTypeOf(ref)
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700934 << " has non-white rb_ptr ";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800935 }
936 }
937
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700938 void VisitRoot(mirror::Object* root, const RootInfo& info ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700939 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800940 DCHECK(root != nullptr);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700941 operator()(root);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800942 }
943
944 private:
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700945 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800946};
947
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700948class ConcurrentCopying::VerifyNoFromSpaceRefsFieldVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800949 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700950 explicit VerifyNoFromSpaceRefsFieldVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800951 : collector_(collector) {}
952
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700953 void operator()(mirror::Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700954 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800955 mirror::Object* ref =
956 obj->GetFieldObject<mirror::Object, kDefaultVerifyFlags, kWithoutReadBarrier>(offset);
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700957 VerifyNoFromSpaceRefsVisitor visitor(collector_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800958 visitor(ref);
959 }
960 void operator()(mirror::Class* klass, mirror::Reference* ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700961 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800962 CHECK(klass->IsTypeOfReferenceClass());
963 this->operator()(ref, mirror::Reference::ReferentOffset(), false);
964 }
965
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700966 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700967 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700968 if (!root->IsNull()) {
969 VisitRoot(root);
970 }
971 }
972
973 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700974 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700975 VerifyNoFromSpaceRefsVisitor visitor(collector_);
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700976 visitor(root->AsMirrorPtr());
977 }
978
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800979 private:
Mathieu Chartier97509952015-07-13 14:35:43 -0700980 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800981};
982
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700983class ConcurrentCopying::VerifyNoFromSpaceRefsObjectVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800984 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700985 explicit VerifyNoFromSpaceRefsObjectVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800986 : collector_(collector) {}
987 void operator()(mirror::Object* obj) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700988 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800989 ObjectCallback(obj, collector_);
990 }
991 static void ObjectCallback(mirror::Object* obj, void *arg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700992 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800993 CHECK(obj != nullptr);
994 ConcurrentCopying* collector = reinterpret_cast<ConcurrentCopying*>(arg);
995 space::RegionSpace* region_space = collector->RegionSpace();
996 CHECK(!region_space->IsInFromSpace(obj)) << "Scanning object " << obj << " in from space";
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700997 VerifyNoFromSpaceRefsFieldVisitor visitor(collector);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -0700998 obj->VisitReferences(visitor, visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800999 if (kUseBakerReadBarrier) {
Mathieu Chartier36a270a2016-07-28 18:08:51 -07001000 CHECK_EQ(obj->GetReadBarrierPointer(), ReadBarrier::WhitePtr())
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001001 << "obj=" << obj << " non-white rb_ptr " << obj->GetReadBarrierPointer();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001002 }
1003 }
1004
1005 private:
1006 ConcurrentCopying* const collector_;
1007};
1008
1009// Verify there's no from-space references left after the marking phase.
1010void ConcurrentCopying::VerifyNoFromSpaceReferences() {
1011 Thread* self = Thread::Current();
1012 DCHECK(Locks::mutator_lock_->IsExclusiveHeld(self));
Hiroshi Yamauchi00370822015-08-18 14:47:25 -07001013 // Verify all threads have is_gc_marking to be false
1014 {
1015 MutexLock mu(self, *Locks::thread_list_lock_);
1016 std::list<Thread*> thread_list = Runtime::Current()->GetThreadList()->GetList();
1017 for (Thread* thread : thread_list) {
1018 CHECK(!thread->GetIsGcMarking());
1019 }
1020 }
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001021 VerifyNoFromSpaceRefsObjectVisitor visitor(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001022 // Roots.
1023 {
1024 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001025 VerifyNoFromSpaceRefsVisitor ref_visitor(this);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001026 Runtime::Current()->VisitRoots(&ref_visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001027 }
1028 // The to-space.
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001029 region_space_->WalkToSpace(VerifyNoFromSpaceRefsObjectVisitor::ObjectCallback, this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001030 // Non-moving spaces.
1031 {
1032 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1033 heap_->GetMarkBitmap()->Visit(visitor);
1034 }
1035 // The alloc stack.
1036 {
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001037 VerifyNoFromSpaceRefsVisitor ref_visitor(this);
Mathieu Chartiercb535da2015-01-23 13:50:03 -08001038 for (auto* it = heap_->allocation_stack_->Begin(), *end = heap_->allocation_stack_->End();
1039 it < end; ++it) {
1040 mirror::Object* const obj = it->AsMirrorPtr();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001041 if (obj != nullptr && obj->GetClass() != nullptr) {
1042 // TODO: need to call this only if obj is alive?
1043 ref_visitor(obj);
1044 visitor(obj);
1045 }
1046 }
1047 }
1048 // TODO: LOS. But only refs in LOS are classes.
1049}
1050
1051// The following visitors are used to assert the to-space invariant.
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001052class ConcurrentCopying::AssertToSpaceInvariantRefsVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001053 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001054 explicit AssertToSpaceInvariantRefsVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001055 : collector_(collector) {}
1056
1057 void operator()(mirror::Object* ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001058 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001059 if (ref == nullptr) {
1060 // OK.
1061 return;
1062 }
1063 collector_->AssertToSpaceInvariant(nullptr, MemberOffset(0), ref);
1064 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001065
1066 private:
Mathieu Chartier97509952015-07-13 14:35:43 -07001067 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001068};
1069
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001070class ConcurrentCopying::AssertToSpaceInvariantFieldVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001071 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001072 explicit AssertToSpaceInvariantFieldVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001073 : collector_(collector) {}
1074
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001075 void operator()(mirror::Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001076 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001077 mirror::Object* ref =
1078 obj->GetFieldObject<mirror::Object, kDefaultVerifyFlags, kWithoutReadBarrier>(offset);
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001079 AssertToSpaceInvariantRefsVisitor visitor(collector_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001080 visitor(ref);
1081 }
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001082 void operator()(mirror::Class* klass, mirror::Reference* ref ATTRIBUTE_UNUSED) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001083 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001084 CHECK(klass->IsTypeOfReferenceClass());
1085 }
1086
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001087 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001088 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001089 if (!root->IsNull()) {
1090 VisitRoot(root);
1091 }
1092 }
1093
1094 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001095 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001096 AssertToSpaceInvariantRefsVisitor visitor(collector_);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001097 visitor(root->AsMirrorPtr());
1098 }
1099
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001100 private:
Mathieu Chartier97509952015-07-13 14:35:43 -07001101 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001102};
1103
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001104class ConcurrentCopying::AssertToSpaceInvariantObjectVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001105 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001106 explicit AssertToSpaceInvariantObjectVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001107 : collector_(collector) {}
1108 void operator()(mirror::Object* obj) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001109 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001110 ObjectCallback(obj, collector_);
1111 }
1112 static void ObjectCallback(mirror::Object* obj, void *arg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001113 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001114 CHECK(obj != nullptr);
1115 ConcurrentCopying* collector = reinterpret_cast<ConcurrentCopying*>(arg);
1116 space::RegionSpace* region_space = collector->RegionSpace();
1117 CHECK(!region_space->IsInFromSpace(obj)) << "Scanning object " << obj << " in from space";
1118 collector->AssertToSpaceInvariant(nullptr, MemberOffset(0), obj);
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001119 AssertToSpaceInvariantFieldVisitor visitor(collector);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07001120 obj->VisitReferences(visitor, visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001121 }
1122
1123 private:
Mathieu Chartier97509952015-07-13 14:35:43 -07001124 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001125};
1126
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001127class ConcurrentCopying::RevokeThreadLocalMarkStackCheckpoint : public Closure {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001128 public:
Roland Levillain3887c462015-08-12 18:15:42 +01001129 RevokeThreadLocalMarkStackCheckpoint(ConcurrentCopying* concurrent_copying,
1130 bool disable_weak_ref_access)
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001131 : concurrent_copying_(concurrent_copying),
1132 disable_weak_ref_access_(disable_weak_ref_access) {
1133 }
1134
1135 virtual void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
1136 // Note: self is not necessarily equal to thread since thread may be suspended.
1137 Thread* self = Thread::Current();
1138 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
1139 << thread->GetState() << " thread " << thread << " self " << self;
1140 // Revoke thread local mark stacks.
1141 accounting::AtomicStack<mirror::Object>* tl_mark_stack = thread->GetThreadLocalMarkStack();
1142 if (tl_mark_stack != nullptr) {
1143 MutexLock mu(self, concurrent_copying_->mark_stack_lock_);
1144 concurrent_copying_->revoked_mark_stacks_.push_back(tl_mark_stack);
1145 thread->SetThreadLocalMarkStack(nullptr);
1146 }
1147 // Disable weak ref access.
1148 if (disable_weak_ref_access_) {
1149 thread->SetWeakRefAccessEnabled(false);
1150 }
1151 // If thread is a running mutator, then act on behalf of the garbage collector.
1152 // See the code in ThreadList::RunCheckpoint.
Mathieu Chartier10d25082015-10-28 18:36:09 -07001153 concurrent_copying_->GetBarrier().Pass(self);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001154 }
1155
1156 private:
1157 ConcurrentCopying* const concurrent_copying_;
1158 const bool disable_weak_ref_access_;
1159};
1160
1161void ConcurrentCopying::RevokeThreadLocalMarkStacks(bool disable_weak_ref_access) {
1162 Thread* self = Thread::Current();
1163 RevokeThreadLocalMarkStackCheckpoint check_point(this, disable_weak_ref_access);
1164 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1165 gc_barrier_->Init(self, 0);
1166 size_t barrier_count = thread_list->RunCheckpoint(&check_point);
1167 // If there are no threads to wait which implys that all the checkpoint functions are finished,
1168 // then no need to release the mutator lock.
1169 if (barrier_count == 0) {
1170 return;
1171 }
1172 Locks::mutator_lock_->SharedUnlock(self);
1173 {
1174 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
1175 gc_barrier_->Increment(self, barrier_count);
1176 }
1177 Locks::mutator_lock_->SharedLock(self);
1178}
1179
1180void ConcurrentCopying::RevokeThreadLocalMarkStack(Thread* thread) {
1181 Thread* self = Thread::Current();
1182 CHECK_EQ(self, thread);
1183 accounting::AtomicStack<mirror::Object>* tl_mark_stack = thread->GetThreadLocalMarkStack();
1184 if (tl_mark_stack != nullptr) {
1185 CHECK(is_marking_);
1186 MutexLock mu(self, mark_stack_lock_);
1187 revoked_mark_stacks_.push_back(tl_mark_stack);
1188 thread->SetThreadLocalMarkStack(nullptr);
1189 }
1190}
1191
1192void ConcurrentCopying::ProcessMarkStack() {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001193 if (kVerboseMode) {
1194 LOG(INFO) << "ProcessMarkStack. ";
1195 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001196 bool empty_prev = false;
1197 while (true) {
1198 bool empty = ProcessMarkStackOnce();
1199 if (empty_prev && empty) {
1200 // Saw empty mark stack for a second time, done.
1201 break;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001202 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001203 empty_prev = empty;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001204 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001205}
1206
1207bool ConcurrentCopying::ProcessMarkStackOnce() {
1208 Thread* self = Thread::Current();
1209 CHECK(thread_running_gc_ != nullptr);
1210 CHECK(self == thread_running_gc_);
1211 CHECK(self->GetThreadLocalMarkStack() == nullptr);
1212 size_t count = 0;
1213 MarkStackMode mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1214 if (mark_stack_mode == kMarkStackModeThreadLocal) {
1215 // Process the thread-local mark stacks and the GC mark stack.
1216 count += ProcessThreadLocalMarkStacks(false);
1217 while (!gc_mark_stack_->IsEmpty()) {
1218 mirror::Object* to_ref = gc_mark_stack_->PopBack();
1219 ProcessMarkStackRef(to_ref);
1220 ++count;
1221 }
1222 gc_mark_stack_->Reset();
1223 } else if (mark_stack_mode == kMarkStackModeShared) {
1224 // Process the shared GC mark stack with a lock.
1225 {
1226 MutexLock mu(self, mark_stack_lock_);
1227 CHECK(revoked_mark_stacks_.empty());
1228 }
1229 while (true) {
1230 std::vector<mirror::Object*> refs;
1231 {
1232 // Copy refs with lock. Note the number of refs should be small.
1233 MutexLock mu(self, mark_stack_lock_);
1234 if (gc_mark_stack_->IsEmpty()) {
1235 break;
1236 }
1237 for (StackReference<mirror::Object>* p = gc_mark_stack_->Begin();
1238 p != gc_mark_stack_->End(); ++p) {
1239 refs.push_back(p->AsMirrorPtr());
1240 }
1241 gc_mark_stack_->Reset();
1242 }
1243 for (mirror::Object* ref : refs) {
1244 ProcessMarkStackRef(ref);
1245 ++count;
1246 }
1247 }
1248 } else {
1249 CHECK_EQ(static_cast<uint32_t>(mark_stack_mode),
1250 static_cast<uint32_t>(kMarkStackModeGcExclusive));
1251 {
1252 MutexLock mu(self, mark_stack_lock_);
1253 CHECK(revoked_mark_stacks_.empty());
1254 }
1255 // Process the GC mark stack in the exclusive mode. No need to take the lock.
1256 while (!gc_mark_stack_->IsEmpty()) {
1257 mirror::Object* to_ref = gc_mark_stack_->PopBack();
1258 ProcessMarkStackRef(to_ref);
1259 ++count;
1260 }
1261 gc_mark_stack_->Reset();
1262 }
1263
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001264 // Return true if the stack was empty.
1265 return count == 0;
1266}
1267
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001268size_t ConcurrentCopying::ProcessThreadLocalMarkStacks(bool disable_weak_ref_access) {
1269 // Run a checkpoint to collect all thread local mark stacks and iterate over them all.
1270 RevokeThreadLocalMarkStacks(disable_weak_ref_access);
1271 size_t count = 0;
1272 std::vector<accounting::AtomicStack<mirror::Object>*> mark_stacks;
1273 {
1274 MutexLock mu(Thread::Current(), mark_stack_lock_);
1275 // Make a copy of the mark stack vector.
1276 mark_stacks = revoked_mark_stacks_;
1277 revoked_mark_stacks_.clear();
1278 }
1279 for (accounting::AtomicStack<mirror::Object>* mark_stack : mark_stacks) {
1280 for (StackReference<mirror::Object>* p = mark_stack->Begin(); p != mark_stack->End(); ++p) {
1281 mirror::Object* to_ref = p->AsMirrorPtr();
1282 ProcessMarkStackRef(to_ref);
1283 ++count;
1284 }
1285 {
1286 MutexLock mu(Thread::Current(), mark_stack_lock_);
1287 if (pooled_mark_stacks_.size() >= kMarkStackPoolSize) {
1288 // The pool has enough. Delete it.
1289 delete mark_stack;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001290 } else {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001291 // Otherwise, put it into the pool for later reuse.
1292 mark_stack->Reset();
1293 pooled_mark_stacks_.push_back(mark_stack);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001294 }
1295 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001296 }
1297 return count;
1298}
1299
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001300inline void ConcurrentCopying::ProcessMarkStackRef(mirror::Object* to_ref) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001301 DCHECK(!region_space_->IsInFromSpace(to_ref));
1302 if (kUseBakerReadBarrier) {
1303 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr())
1304 << " " << to_ref << " " << to_ref->GetReadBarrierPointer()
1305 << " is_marked=" << IsMarked(to_ref);
1306 }
Mathieu Chartierc381c362016-08-23 13:27:53 -07001307 bool add_to_live_bytes = false;
1308 if (region_space_->IsInUnevacFromSpace(to_ref)) {
1309 // Mark the bitmap only in the GC thread here so that we don't need a CAS.
1310 if (!kUseBakerReadBarrier || !region_space_bitmap_->Set(to_ref)) {
1311 // It may be already marked if we accidentally pushed the same object twice due to the racy
1312 // bitmap read in MarkUnevacFromSpaceRegion.
1313 Scan(to_ref);
1314 // Only add to the live bytes if the object was not already marked.
1315 add_to_live_bytes = true;
1316 }
1317 } else {
1318 Scan(to_ref);
1319 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001320 if (kUseBakerReadBarrier) {
1321 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr())
1322 << " " << to_ref << " " << to_ref->GetReadBarrierPointer()
1323 << " is_marked=" << IsMarked(to_ref);
1324 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001325#ifdef USE_BAKER_OR_BROOKS_READ_BARRIER
1326 if (UNLIKELY((to_ref->GetClass<kVerifyNone, kWithoutReadBarrier>()->IsTypeOfReferenceClass() &&
1327 to_ref->AsReference()->GetReferent<kWithoutReadBarrier>() != nullptr &&
1328 !IsInToSpace(to_ref->AsReference()->GetReferent<kWithoutReadBarrier>())))) {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001329 // Leave this reference gray in the queue so that GetReferent() will trigger a read barrier. We
1330 // will change it to white later in ReferenceQueue::DequeuePendingReference().
Richard Uhlere3627402016-02-02 13:36:55 -08001331 DCHECK(to_ref->AsReference()->GetPendingNext() != nullptr) << "Left unenqueued ref gray " << to_ref;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001332 } else {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001333 // We may occasionally leave a reference white in the queue if its referent happens to be
1334 // concurrently marked after the Scan() call above has enqueued the Reference, in which case the
1335 // above IsInToSpace() evaluates to true and we change the color from gray to white here in this
1336 // else block.
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001337 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001338 bool success = to_ref->AtomicSetReadBarrierPointer</*kCasRelease*/true>(
1339 ReadBarrier::GrayPtr(),
1340 ReadBarrier::WhitePtr());
1341 DCHECK(success) << "Must succeed as we won the race.";
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001342 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001343 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001344#else
1345 DCHECK(!kUseBakerReadBarrier);
1346#endif
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001347
Mathieu Chartierc381c362016-08-23 13:27:53 -07001348 if (add_to_live_bytes) {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001349 // Add to the live bytes per unevacuated from space. Note this code is always run by the
1350 // GC-running thread (no synchronization required).
1351 DCHECK(region_space_bitmap_->Test(to_ref));
1352 // Disable the read barrier in SizeOf for performance, which is safe.
1353 size_t obj_size = to_ref->SizeOf<kDefaultVerifyFlags, kWithoutReadBarrier>();
1354 size_t alloc_size = RoundUp(obj_size, space::RegionSpace::kAlignment);
1355 region_space_->AddLiveBytes(to_ref, alloc_size);
1356 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001357 if (ReadBarrier::kEnableToSpaceInvariantChecks || kIsDebugBuild) {
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001358 AssertToSpaceInvariantObjectVisitor visitor(this);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001359 visitor(to_ref);
1360 }
1361}
1362
1363void ConcurrentCopying::SwitchToSharedMarkStackMode() {
1364 Thread* self = Thread::Current();
1365 CHECK(thread_running_gc_ != nullptr);
1366 CHECK_EQ(self, thread_running_gc_);
1367 CHECK(self->GetThreadLocalMarkStack() == nullptr);
1368 MarkStackMode before_mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1369 CHECK_EQ(static_cast<uint32_t>(before_mark_stack_mode),
1370 static_cast<uint32_t>(kMarkStackModeThreadLocal));
1371 mark_stack_mode_.StoreRelaxed(kMarkStackModeShared);
1372 CHECK(weak_ref_access_enabled_.LoadRelaxed());
1373 weak_ref_access_enabled_.StoreRelaxed(false);
1374 QuasiAtomic::ThreadFenceForConstructor();
1375 // Process the thread local mark stacks one last time after switching to the shared mark stack
1376 // mode and disable weak ref accesses.
1377 ProcessThreadLocalMarkStacks(true);
1378 if (kVerboseMode) {
1379 LOG(INFO) << "Switched to shared mark stack mode and disabled weak ref access";
1380 }
1381}
1382
1383void ConcurrentCopying::SwitchToGcExclusiveMarkStackMode() {
1384 Thread* self = Thread::Current();
1385 CHECK(thread_running_gc_ != nullptr);
1386 CHECK_EQ(self, thread_running_gc_);
1387 CHECK(self->GetThreadLocalMarkStack() == nullptr);
1388 MarkStackMode before_mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1389 CHECK_EQ(static_cast<uint32_t>(before_mark_stack_mode),
1390 static_cast<uint32_t>(kMarkStackModeShared));
1391 mark_stack_mode_.StoreRelaxed(kMarkStackModeGcExclusive);
1392 QuasiAtomic::ThreadFenceForConstructor();
1393 if (kVerboseMode) {
1394 LOG(INFO) << "Switched to GC exclusive mark stack mode";
1395 }
1396}
1397
1398void ConcurrentCopying::CheckEmptyMarkStack() {
1399 Thread* self = Thread::Current();
1400 CHECK(thread_running_gc_ != nullptr);
1401 CHECK_EQ(self, thread_running_gc_);
1402 CHECK(self->GetThreadLocalMarkStack() == nullptr);
1403 MarkStackMode mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1404 if (mark_stack_mode == kMarkStackModeThreadLocal) {
1405 // Thread-local mark stack mode.
1406 RevokeThreadLocalMarkStacks(false);
1407 MutexLock mu(Thread::Current(), mark_stack_lock_);
1408 if (!revoked_mark_stacks_.empty()) {
1409 for (accounting::AtomicStack<mirror::Object>* mark_stack : revoked_mark_stacks_) {
1410 while (!mark_stack->IsEmpty()) {
1411 mirror::Object* obj = mark_stack->PopBack();
1412 if (kUseBakerReadBarrier) {
1413 mirror::Object* rb_ptr = obj->GetReadBarrierPointer();
1414 LOG(INFO) << "On mark queue : " << obj << " " << PrettyTypeOf(obj) << " rb_ptr=" << rb_ptr
1415 << " is_marked=" << IsMarked(obj);
1416 } else {
1417 LOG(INFO) << "On mark queue : " << obj << " " << PrettyTypeOf(obj)
1418 << " is_marked=" << IsMarked(obj);
1419 }
1420 }
1421 }
1422 LOG(FATAL) << "mark stack is not empty";
1423 }
1424 } else {
1425 // Shared, GC-exclusive, or off.
1426 MutexLock mu(Thread::Current(), mark_stack_lock_);
1427 CHECK(gc_mark_stack_->IsEmpty());
1428 CHECK(revoked_mark_stacks_.empty());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001429 }
1430}
1431
1432void ConcurrentCopying::SweepSystemWeaks(Thread* self) {
1433 TimingLogger::ScopedTiming split("SweepSystemWeaks", GetTimings());
1434 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier97509952015-07-13 14:35:43 -07001435 Runtime::Current()->SweepSystemWeaks(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001436}
1437
1438void ConcurrentCopying::Sweep(bool swap_bitmaps) {
1439 {
1440 TimingLogger::ScopedTiming t("MarkStackAsLive", GetTimings());
1441 accounting::ObjectStack* live_stack = heap_->GetLiveStack();
1442 if (kEnableFromSpaceAccountingCheck) {
1443 CHECK_GE(live_stack_freeze_size_, live_stack->Size());
1444 }
1445 heap_->MarkAllocStackAsLive(live_stack);
1446 live_stack->Reset();
1447 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001448 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001449 TimingLogger::ScopedTiming split("Sweep", GetTimings());
1450 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
1451 if (space->IsContinuousMemMapAllocSpace()) {
1452 space::ContinuousMemMapAllocSpace* alloc_space = space->AsContinuousMemMapAllocSpace();
Mathieu Chartier763a31e2015-11-16 16:05:55 -08001453 if (space == region_space_ || immune_spaces_.ContainsSpace(space)) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001454 continue;
1455 }
1456 TimingLogger::ScopedTiming split2(
1457 alloc_space->IsZygoteSpace() ? "SweepZygoteSpace" : "SweepAllocSpace", GetTimings());
1458 RecordFree(alloc_space->Sweep(swap_bitmaps));
1459 }
1460 }
1461 SweepLargeObjects(swap_bitmaps);
1462}
1463
Mathieu Chartier962cd7a2016-08-16 12:15:59 -07001464void ConcurrentCopying::MarkZygoteLargeObjects() {
1465 TimingLogger::ScopedTiming split(__FUNCTION__, GetTimings());
1466 Thread* const self = Thread::Current();
1467 WriterMutexLock rmu(self, *Locks::heap_bitmap_lock_);
1468 space::LargeObjectSpace* const los = heap_->GetLargeObjectsSpace();
1469 // Pick the current live bitmap (mark bitmap if swapped).
1470 accounting::LargeObjectBitmap* const live_bitmap = los->GetLiveBitmap();
1471 accounting::LargeObjectBitmap* const mark_bitmap = los->GetMarkBitmap();
1472 // Walk through all of the objects and explicitly mark the zygote ones so they don't get swept.
1473 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(los->Begin()),
1474 reinterpret_cast<uintptr_t>(los->End()),
1475 [mark_bitmap, los, self](mirror::Object* obj)
1476 REQUIRES(Locks::heap_bitmap_lock_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001477 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier962cd7a2016-08-16 12:15:59 -07001478 if (los->IsZygoteLargeObject(self, obj)) {
1479 mark_bitmap->Set(obj);
1480 }
1481 });
1482}
1483
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001484void ConcurrentCopying::SweepLargeObjects(bool swap_bitmaps) {
1485 TimingLogger::ScopedTiming split("SweepLargeObjects", GetTimings());
1486 RecordFreeLOS(heap_->GetLargeObjectsSpace()->Sweep(swap_bitmaps));
1487}
1488
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001489void ConcurrentCopying::ReclaimPhase() {
1490 TimingLogger::ScopedTiming split("ReclaimPhase", GetTimings());
1491 if (kVerboseMode) {
1492 LOG(INFO) << "GC ReclaimPhase";
1493 }
1494 Thread* self = Thread::Current();
1495
1496 {
1497 // Double-check that the mark stack is empty.
1498 // Note: need to set this after VerifyNoFromSpaceRef().
1499 is_asserting_to_space_invariant_ = false;
1500 QuasiAtomic::ThreadFenceForConstructor();
1501 if (kVerboseMode) {
1502 LOG(INFO) << "Issue an empty check point. ";
1503 }
1504 IssueEmptyCheckpoint();
1505 // Disable the check.
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001506 is_mark_stack_push_disallowed_.StoreSequentiallyConsistent(0);
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001507 if (kUseBakerReadBarrier) {
1508 updated_all_immune_objects_.StoreSequentiallyConsistent(false);
1509 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001510 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001511 }
1512
1513 {
1514 // Record freed objects.
1515 TimingLogger::ScopedTiming split2("RecordFree", GetTimings());
1516 // Don't include thread-locals that are in the to-space.
1517 uint64_t from_bytes = region_space_->GetBytesAllocatedInFromSpace();
1518 uint64_t from_objects = region_space_->GetObjectsAllocatedInFromSpace();
1519 uint64_t unevac_from_bytes = region_space_->GetBytesAllocatedInUnevacFromSpace();
1520 uint64_t unevac_from_objects = region_space_->GetObjectsAllocatedInUnevacFromSpace();
1521 uint64_t to_bytes = bytes_moved_.LoadSequentiallyConsistent();
Mathieu Chartiercca44a02016-08-17 10:07:29 -07001522 cumulative_bytes_moved_.FetchAndAddRelaxed(to_bytes);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001523 uint64_t to_objects = objects_moved_.LoadSequentiallyConsistent();
Mathieu Chartiercca44a02016-08-17 10:07:29 -07001524 cumulative_objects_moved_.FetchAndAddRelaxed(to_objects);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001525 if (kEnableFromSpaceAccountingCheck) {
1526 CHECK_EQ(from_space_num_objects_at_first_pause_, from_objects + unevac_from_objects);
1527 CHECK_EQ(from_space_num_bytes_at_first_pause_, from_bytes + unevac_from_bytes);
1528 }
1529 CHECK_LE(to_objects, from_objects);
1530 CHECK_LE(to_bytes, from_bytes);
1531 int64_t freed_bytes = from_bytes - to_bytes;
1532 int64_t freed_objects = from_objects - to_objects;
1533 if (kVerboseMode) {
1534 LOG(INFO) << "RecordFree:"
1535 << " from_bytes=" << from_bytes << " from_objects=" << from_objects
1536 << " unevac_from_bytes=" << unevac_from_bytes << " unevac_from_objects=" << unevac_from_objects
1537 << " to_bytes=" << to_bytes << " to_objects=" << to_objects
1538 << " freed_bytes=" << freed_bytes << " freed_objects=" << freed_objects
1539 << " from_space size=" << region_space_->FromSpaceSize()
1540 << " unevac_from_space size=" << region_space_->UnevacFromSpaceSize()
1541 << " to_space size=" << region_space_->ToSpaceSize();
1542 LOG(INFO) << "(before) num_bytes_allocated=" << heap_->num_bytes_allocated_.LoadSequentiallyConsistent();
1543 }
1544 RecordFree(ObjectBytePair(freed_objects, freed_bytes));
1545 if (kVerboseMode) {
1546 LOG(INFO) << "(after) num_bytes_allocated=" << heap_->num_bytes_allocated_.LoadSequentiallyConsistent();
1547 }
1548 }
1549
1550 {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001551 TimingLogger::ScopedTiming split4("ClearFromSpace", GetTimings());
1552 region_space_->ClearFromSpace();
1553 }
1554
1555 {
1556 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001557 Sweep(false);
1558 SwapBitmaps();
1559 heap_->UnBindBitmaps();
1560
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001561 // Delete the region bitmap.
1562 DCHECK(region_space_bitmap_ != nullptr);
1563 delete region_space_bitmap_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001564 region_space_bitmap_ = nullptr;
1565 }
1566
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001567 CheckEmptyMarkStack();
1568
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001569 if (kVerboseMode) {
1570 LOG(INFO) << "GC end of ReclaimPhase";
1571 }
1572}
1573
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001574// Assert the to-space invariant.
1575void ConcurrentCopying::AssertToSpaceInvariant(mirror::Object* obj, MemberOffset offset,
1576 mirror::Object* ref) {
1577 CHECK(heap_->collector_type_ == kCollectorTypeCC) << static_cast<size_t>(heap_->collector_type_);
1578 if (is_asserting_to_space_invariant_) {
1579 if (region_space_->IsInToSpace(ref)) {
1580 // OK.
1581 return;
1582 } else if (region_space_->IsInUnevacFromSpace(ref)) {
Mathieu Chartierc381c362016-08-23 13:27:53 -07001583 CHECK(IsMarkedInUnevacFromSpace(ref)) << ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001584 } else if (region_space_->IsInFromSpace(ref)) {
1585 // Not OK. Do extra logging.
1586 if (obj != nullptr) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001587 LogFromSpaceRefHolder(obj, offset);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001588 }
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001589 ref->GetLockWord(false).Dump(LOG(INTERNAL_FATAL));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001590 CHECK(false) << "Found from-space ref " << ref << " " << PrettyTypeOf(ref);
1591 } else {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001592 AssertToSpaceInvariantInNonMovingSpace(obj, ref);
1593 }
1594 }
1595}
1596
1597class RootPrinter {
1598 public:
1599 RootPrinter() { }
1600
1601 template <class MirrorType>
1602 ALWAYS_INLINE void VisitRootIfNonNull(mirror::CompressedReference<MirrorType>* root)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001603 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001604 if (!root->IsNull()) {
1605 VisitRoot(root);
1606 }
1607 }
1608
1609 template <class MirrorType>
1610 void VisitRoot(mirror::Object** root)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001611 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001612 LOG(INTERNAL_FATAL) << "root=" << root << " ref=" << *root;
1613 }
1614
1615 template <class MirrorType>
1616 void VisitRoot(mirror::CompressedReference<MirrorType>* root)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001617 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001618 LOG(INTERNAL_FATAL) << "root=" << root << " ref=" << root->AsMirrorPtr();
1619 }
1620};
1621
1622void ConcurrentCopying::AssertToSpaceInvariant(GcRootSource* gc_root_source,
1623 mirror::Object* ref) {
1624 CHECK(heap_->collector_type_ == kCollectorTypeCC) << static_cast<size_t>(heap_->collector_type_);
1625 if (is_asserting_to_space_invariant_) {
1626 if (region_space_->IsInToSpace(ref)) {
1627 // OK.
1628 return;
1629 } else if (region_space_->IsInUnevacFromSpace(ref)) {
Mathieu Chartierc381c362016-08-23 13:27:53 -07001630 CHECK(IsMarkedInUnevacFromSpace(ref)) << ref;
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001631 } else if (region_space_->IsInFromSpace(ref)) {
1632 // Not OK. Do extra logging.
1633 if (gc_root_source == nullptr) {
1634 // No info.
1635 } else if (gc_root_source->HasArtField()) {
1636 ArtField* field = gc_root_source->GetArtField();
1637 LOG(INTERNAL_FATAL) << "gc root in field " << field << " " << PrettyField(field);
1638 RootPrinter root_printer;
1639 field->VisitRoots(root_printer);
1640 } else if (gc_root_source->HasArtMethod()) {
1641 ArtMethod* method = gc_root_source->GetArtMethod();
1642 LOG(INTERNAL_FATAL) << "gc root in method " << method << " " << PrettyMethod(method);
1643 RootPrinter root_printer;
Andreas Gampe542451c2016-07-26 09:02:02 -07001644 method->VisitRoots(root_printer, kRuntimePointerSize);
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001645 }
1646 ref->GetLockWord(false).Dump(LOG(INTERNAL_FATAL));
1647 region_space_->DumpNonFreeRegions(LOG(INTERNAL_FATAL));
1648 PrintFileToLog("/proc/self/maps", LogSeverity::INTERNAL_FATAL);
1649 MemMap::DumpMaps(LOG(INTERNAL_FATAL), true);
1650 CHECK(false) << "Found from-space ref " << ref << " " << PrettyTypeOf(ref);
1651 } else {
1652 AssertToSpaceInvariantInNonMovingSpace(nullptr, ref);
1653 }
1654 }
1655}
1656
1657void ConcurrentCopying::LogFromSpaceRefHolder(mirror::Object* obj, MemberOffset offset) {
1658 if (kUseBakerReadBarrier) {
1659 LOG(INFO) << "holder=" << obj << " " << PrettyTypeOf(obj)
1660 << " holder rb_ptr=" << obj->GetReadBarrierPointer();
1661 } else {
1662 LOG(INFO) << "holder=" << obj << " " << PrettyTypeOf(obj);
1663 }
1664 if (region_space_->IsInFromSpace(obj)) {
1665 LOG(INFO) << "holder is in the from-space.";
1666 } else if (region_space_->IsInToSpace(obj)) {
1667 LOG(INFO) << "holder is in the to-space.";
1668 } else if (region_space_->IsInUnevacFromSpace(obj)) {
1669 LOG(INFO) << "holder is in the unevac from-space.";
Mathieu Chartierc381c362016-08-23 13:27:53 -07001670 if (IsMarkedInUnevacFromSpace(obj)) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001671 LOG(INFO) << "holder is marked in the region space bitmap.";
1672 } else {
1673 LOG(INFO) << "holder is not marked in the region space bitmap.";
1674 }
1675 } else {
1676 // In a non-moving space.
Mathieu Chartier763a31e2015-11-16 16:05:55 -08001677 if (immune_spaces_.ContainsObject(obj)) {
1678 LOG(INFO) << "holder is in an immune image or the zygote space.";
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001679 } else {
Mathieu Chartier763a31e2015-11-16 16:05:55 -08001680 LOG(INFO) << "holder is in a non-immune, non-moving (or main) space.";
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001681 accounting::ContinuousSpaceBitmap* mark_bitmap =
1682 heap_mark_bitmap_->GetContinuousSpaceBitmap(obj);
1683 accounting::LargeObjectBitmap* los_bitmap =
1684 heap_mark_bitmap_->GetLargeObjectBitmap(obj);
1685 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
1686 bool is_los = mark_bitmap == nullptr;
1687 if (!is_los && mark_bitmap->Test(obj)) {
1688 LOG(INFO) << "holder is marked in the mark bit map.";
1689 } else if (is_los && los_bitmap->Test(obj)) {
1690 LOG(INFO) << "holder is marked in the los bit map.";
1691 } else {
1692 // If ref is on the allocation stack, then it is considered
1693 // mark/alive (but not necessarily on the live stack.)
1694 if (IsOnAllocStack(obj)) {
1695 LOG(INFO) << "holder is on the alloc stack.";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001696 } else {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001697 LOG(INFO) << "holder is not marked or on the alloc stack.";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001698 }
1699 }
1700 }
1701 }
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001702 LOG(INFO) << "offset=" << offset.SizeValue();
1703}
1704
1705void ConcurrentCopying::AssertToSpaceInvariantInNonMovingSpace(mirror::Object* obj,
1706 mirror::Object* ref) {
1707 // In a non-moving spaces. Check that the ref is marked.
Mathieu Chartier763a31e2015-11-16 16:05:55 -08001708 if (immune_spaces_.ContainsObject(ref)) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001709 if (kUseBakerReadBarrier) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001710 // Immune object may not be gray if called from the GC.
1711 if (Thread::Current() == thread_running_gc_ && !gc_grays_immune_objects_) {
1712 return;
1713 }
1714 bool updated_all_immune_objects = updated_all_immune_objects_.LoadSequentiallyConsistent();
1715 CHECK(updated_all_immune_objects || ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr())
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001716 << "Unmarked immune space ref. obj=" << obj << " rb_ptr="
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001717 << (obj != nullptr ? obj->GetReadBarrierPointer() : nullptr)
1718 << " ref=" << ref << " ref rb_ptr=" << ref->GetReadBarrierPointer()
1719 << " updated_all_immune_objects=" << updated_all_immune_objects;
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001720 }
1721 } else {
1722 accounting::ContinuousSpaceBitmap* mark_bitmap =
1723 heap_mark_bitmap_->GetContinuousSpaceBitmap(ref);
1724 accounting::LargeObjectBitmap* los_bitmap =
1725 heap_mark_bitmap_->GetLargeObjectBitmap(ref);
1726 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
1727 bool is_los = mark_bitmap == nullptr;
1728 if ((!is_los && mark_bitmap->Test(ref)) ||
1729 (is_los && los_bitmap->Test(ref))) {
1730 // OK.
1731 } else {
1732 // If ref is on the allocation stack, then it may not be
1733 // marked live, but considered marked/alive (but not
1734 // necessarily on the live stack).
1735 CHECK(IsOnAllocStack(ref)) << "Unmarked ref that's not on the allocation stack. "
1736 << "obj=" << obj << " ref=" << ref;
1737 }
1738 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001739}
1740
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001741// Used to scan ref fields of an object.
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001742class ConcurrentCopying::RefFieldsVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001743 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001744 explicit RefFieldsVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001745 : collector_(collector) {}
1746
1747 void operator()(mirror::Object* obj, MemberOffset offset, bool /* is_static */)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001748 const ALWAYS_INLINE REQUIRES_SHARED(Locks::mutator_lock_)
1749 REQUIRES_SHARED(Locks::heap_bitmap_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001750 collector_->Process(obj, offset);
1751 }
1752
1753 void operator()(mirror::Class* klass, mirror::Reference* ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001754 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001755 CHECK(klass->IsTypeOfReferenceClass());
1756 collector_->DelayReferenceReferent(klass, ref);
1757 }
1758
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001759 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001760 ALWAYS_INLINE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001761 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001762 if (!root->IsNull()) {
1763 VisitRoot(root);
1764 }
1765 }
1766
1767 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001768 ALWAYS_INLINE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001769 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001770 collector_->MarkRoot</*kGrayImmuneObject*/false>(root);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001771 }
1772
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001773 private:
1774 ConcurrentCopying* const collector_;
1775};
1776
1777// Scan ref fields of an object.
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001778inline void ConcurrentCopying::Scan(mirror::Object* to_ref) {
Mathieu Chartierd6636d32016-07-28 11:02:38 -07001779 if (kDisallowReadBarrierDuringScan) {
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07001780 // Avoid all read barriers during visit references to help performance.
1781 Thread::Current()->ModifyDebugDisallowReadBarrier(1);
1782 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001783 DCHECK(!region_space_->IsInFromSpace(to_ref));
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001784 DCHECK_EQ(Thread::Current(), thread_running_gc_);
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001785 RefFieldsVisitor visitor(this);
Hiroshi Yamauchi5496f692016-02-17 13:29:59 -08001786 // Disable the read barrier for a performance reason.
1787 to_ref->VisitReferences</*kVisitNativeRoots*/true, kDefaultVerifyFlags, kWithoutReadBarrier>(
1788 visitor, visitor);
Mathieu Chartierd6636d32016-07-28 11:02:38 -07001789 if (kDisallowReadBarrierDuringScan) {
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07001790 Thread::Current()->ModifyDebugDisallowReadBarrier(-1);
1791 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001792}
1793
1794// Process a field.
1795inline void ConcurrentCopying::Process(mirror::Object* obj, MemberOffset offset) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001796 DCHECK_EQ(Thread::Current(), thread_running_gc_);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001797 mirror::Object* ref = obj->GetFieldObject<
1798 mirror::Object, kVerifyNone, kWithoutReadBarrier, false>(offset);
Mathieu Chartierc381c362016-08-23 13:27:53 -07001799 mirror::Object* to_ref = Mark</*kGrayImmuneObject*/false, /*kFromGCThread*/true>(ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001800 if (to_ref == ref) {
1801 return;
1802 }
1803 // This may fail if the mutator writes to the field at the same time. But it's ok.
1804 mirror::Object* expected_ref = ref;
1805 mirror::Object* new_ref = to_ref;
1806 do {
1807 if (expected_ref !=
1808 obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier, false>(offset)) {
1809 // It was updated by the mutator.
1810 break;
1811 }
Hiroshi Yamauchifed3e2f2015-10-20 11:11:56 -07001812 } while (!obj->CasFieldWeakRelaxedObjectWithoutWriteBarrier<
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001813 false, false, kVerifyNone>(offset, expected_ref, new_ref));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001814}
1815
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001816// Process some roots.
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001817inline void ConcurrentCopying::VisitRoots(
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001818 mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED) {
1819 for (size_t i = 0; i < count; ++i) {
1820 mirror::Object** root = roots[i];
1821 mirror::Object* ref = *root;
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001822 mirror::Object* to_ref = Mark(ref);
1823 if (to_ref == ref) {
Mathieu Chartier4809d0a2015-04-07 10:39:04 -07001824 continue;
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001825 }
1826 Atomic<mirror::Object*>* addr = reinterpret_cast<Atomic<mirror::Object*>*>(root);
1827 mirror::Object* expected_ref = ref;
1828 mirror::Object* new_ref = to_ref;
1829 do {
1830 if (expected_ref != addr->LoadRelaxed()) {
1831 // It was updated by the mutator.
1832 break;
1833 }
Hiroshi Yamauchifed3e2f2015-10-20 11:11:56 -07001834 } while (!addr->CompareExchangeWeakRelaxed(expected_ref, new_ref));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001835 }
1836}
1837
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001838template<bool kGrayImmuneObject>
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001839inline void ConcurrentCopying::MarkRoot(mirror::CompressedReference<mirror::Object>* root) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001840 DCHECK(!root->IsNull());
1841 mirror::Object* const ref = root->AsMirrorPtr();
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001842 mirror::Object* to_ref = Mark<kGrayImmuneObject>(ref);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001843 if (to_ref != ref) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001844 auto* addr = reinterpret_cast<Atomic<mirror::CompressedReference<mirror::Object>>*>(root);
1845 auto expected_ref = mirror::CompressedReference<mirror::Object>::FromMirrorPtr(ref);
1846 auto new_ref = mirror::CompressedReference<mirror::Object>::FromMirrorPtr(to_ref);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001847 // If the cas fails, then it was updated by the mutator.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001848 do {
1849 if (ref != addr->LoadRelaxed().AsMirrorPtr()) {
1850 // It was updated by the mutator.
1851 break;
1852 }
Hiroshi Yamauchifed3e2f2015-10-20 11:11:56 -07001853 } while (!addr->CompareExchangeWeakRelaxed(expected_ref, new_ref));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001854 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001855}
1856
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001857inline void ConcurrentCopying::VisitRoots(
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001858 mirror::CompressedReference<mirror::Object>** roots, size_t count,
1859 const RootInfo& info ATTRIBUTE_UNUSED) {
1860 for (size_t i = 0; i < count; ++i) {
1861 mirror::CompressedReference<mirror::Object>* const root = roots[i];
1862 if (!root->IsNull()) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001863 // kGrayImmuneObject is true because this is used for the thread flip.
1864 MarkRoot</*kGrayImmuneObject*/true>(root);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001865 }
1866 }
1867}
1868
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001869// Temporary set gc_grays_immune_objects_ to true in a scope if the current thread is GC.
1870class ConcurrentCopying::ScopedGcGraysImmuneObjects {
1871 public:
1872 explicit ScopedGcGraysImmuneObjects(ConcurrentCopying* collector)
1873 : collector_(collector), enabled_(false) {
1874 if (kUseBakerReadBarrier &&
1875 collector_->thread_running_gc_ == Thread::Current() &&
1876 !collector_->gc_grays_immune_objects_) {
1877 collector_->gc_grays_immune_objects_ = true;
1878 enabled_ = true;
1879 }
1880 }
1881
1882 ~ScopedGcGraysImmuneObjects() {
1883 if (kUseBakerReadBarrier &&
1884 collector_->thread_running_gc_ == Thread::Current() &&
1885 enabled_) {
1886 DCHECK(collector_->gc_grays_immune_objects_);
1887 collector_->gc_grays_immune_objects_ = false;
1888 }
1889 }
1890
1891 private:
1892 ConcurrentCopying* const collector_;
1893 bool enabled_;
1894};
1895
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001896// Fill the given memory block with a dummy object. Used to fill in a
1897// copy of objects that was lost in race.
1898void ConcurrentCopying::FillWithDummyObject(mirror::Object* dummy_obj, size_t byte_size) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001899 // GC doesn't gray immune objects while scanning immune objects. But we need to trigger the read
1900 // barriers here because we need the updated reference to the int array class, etc. Temporary set
1901 // gc_grays_immune_objects_ to true so that we won't cause a DCHECK failure in MarkImmuneSpace().
1902 ScopedGcGraysImmuneObjects scoped_gc_gray_immune_objects(this);
Roland Levillain14d90572015-07-16 10:52:26 +01001903 CHECK_ALIGNED(byte_size, kObjectAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001904 memset(dummy_obj, 0, byte_size);
Mathieu Chartierd6636d32016-07-28 11:02:38 -07001905 // Avoid going through read barrier for since kDisallowReadBarrierDuringScan may be enabled.
1906 // Explicitly mark to make sure to get an object in the to-space.
1907 mirror::Class* int_array_class = down_cast<mirror::Class*>(
1908 Mark(mirror::IntArray::GetArrayClass<kWithoutReadBarrier>()));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001909 CHECK(int_array_class != nullptr);
1910 AssertToSpaceInvariant(nullptr, MemberOffset(0), int_array_class);
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07001911 size_t component_size = int_array_class->GetComponentSize<kWithoutReadBarrier>();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001912 CHECK_EQ(component_size, sizeof(int32_t));
1913 size_t data_offset = mirror::Array::DataOffset(component_size).SizeValue();
1914 if (data_offset > byte_size) {
1915 // An int array is too big. Use java.lang.Object.
1916 mirror::Class* java_lang_Object = WellKnownClasses::ToClass(WellKnownClasses::java_lang_Object);
1917 AssertToSpaceInvariant(nullptr, MemberOffset(0), java_lang_Object);
Mathieu Chartierd6636d32016-07-28 11:02:38 -07001918 CHECK_EQ(byte_size, (java_lang_Object->GetObjectSize<kVerifyNone, kWithoutReadBarrier>()));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001919 dummy_obj->SetClass(java_lang_Object);
Mathieu Chartierd6636d32016-07-28 11:02:38 -07001920 CHECK_EQ(byte_size, (dummy_obj->SizeOf<kVerifyNone, kWithoutReadBarrier>()));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001921 } else {
1922 // Use an int array.
1923 dummy_obj->SetClass(int_array_class);
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07001924 CHECK((dummy_obj->IsArrayInstance<kVerifyNone, kWithoutReadBarrier>()));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001925 int32_t length = (byte_size - data_offset) / component_size;
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07001926 mirror::Array* dummy_arr = dummy_obj->AsArray<kVerifyNone, kWithoutReadBarrier>();
1927 dummy_arr->SetLength(length);
1928 CHECK_EQ(dummy_arr->GetLength(), length)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001929 << "byte_size=" << byte_size << " length=" << length
1930 << " component_size=" << component_size << " data_offset=" << data_offset;
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07001931 CHECK_EQ(byte_size, (dummy_obj->SizeOf<kVerifyNone, kWithoutReadBarrier>()))
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001932 << "byte_size=" << byte_size << " length=" << length
1933 << " component_size=" << component_size << " data_offset=" << data_offset;
1934 }
1935}
1936
1937// Reuse the memory blocks that were copy of objects that were lost in race.
1938mirror::Object* ConcurrentCopying::AllocateInSkippedBlock(size_t alloc_size) {
1939 // Try to reuse the blocks that were unused due to CAS failures.
Roland Levillain14d90572015-07-16 10:52:26 +01001940 CHECK_ALIGNED(alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001941 Thread* self = Thread::Current();
1942 size_t min_object_size = RoundUp(sizeof(mirror::Object), space::RegionSpace::kAlignment);
Mathieu Chartierd6636d32016-07-28 11:02:38 -07001943 size_t byte_size;
1944 uint8_t* addr;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001945 {
Mathieu Chartierd6636d32016-07-28 11:02:38 -07001946 MutexLock mu(self, skipped_blocks_lock_);
1947 auto it = skipped_blocks_map_.lower_bound(alloc_size);
1948 if (it == skipped_blocks_map_.end()) {
1949 // Not found.
1950 return nullptr;
1951 }
1952 byte_size = it->first;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001953 CHECK_GE(byte_size, alloc_size);
1954 if (byte_size > alloc_size && byte_size - alloc_size < min_object_size) {
1955 // If remainder would be too small for a dummy object, retry with a larger request size.
1956 it = skipped_blocks_map_.lower_bound(alloc_size + min_object_size);
1957 if (it == skipped_blocks_map_.end()) {
1958 // Not found.
1959 return nullptr;
1960 }
Roland Levillain14d90572015-07-16 10:52:26 +01001961 CHECK_ALIGNED(it->first - alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001962 CHECK_GE(it->first - alloc_size, min_object_size)
1963 << "byte_size=" << byte_size << " it->first=" << it->first << " alloc_size=" << alloc_size;
1964 }
Mathieu Chartierd6636d32016-07-28 11:02:38 -07001965 // Found a block.
1966 CHECK(it != skipped_blocks_map_.end());
1967 byte_size = it->first;
1968 addr = it->second;
1969 CHECK_GE(byte_size, alloc_size);
1970 CHECK(region_space_->IsInToSpace(reinterpret_cast<mirror::Object*>(addr)));
1971 CHECK_ALIGNED(byte_size, space::RegionSpace::kAlignment);
1972 if (kVerboseMode) {
1973 LOG(INFO) << "Reusing skipped bytes : " << reinterpret_cast<void*>(addr) << ", " << byte_size;
1974 }
1975 skipped_blocks_map_.erase(it);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001976 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001977 memset(addr, 0, byte_size);
1978 if (byte_size > alloc_size) {
1979 // Return the remainder to the map.
Roland Levillain14d90572015-07-16 10:52:26 +01001980 CHECK_ALIGNED(byte_size - alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001981 CHECK_GE(byte_size - alloc_size, min_object_size);
Mathieu Chartierd6636d32016-07-28 11:02:38 -07001982 // FillWithDummyObject may mark an object, avoid holding skipped_blocks_lock_ to prevent lock
1983 // violation and possible deadlock. The deadlock case is a recursive case:
1984 // FillWithDummyObject -> IntArray::GetArrayClass -> Mark -> Copy -> AllocateInSkippedBlock.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001985 FillWithDummyObject(reinterpret_cast<mirror::Object*>(addr + alloc_size),
1986 byte_size - alloc_size);
1987 CHECK(region_space_->IsInToSpace(reinterpret_cast<mirror::Object*>(addr + alloc_size)));
Mathieu Chartierd6636d32016-07-28 11:02:38 -07001988 {
1989 MutexLock mu(self, skipped_blocks_lock_);
1990 skipped_blocks_map_.insert(std::make_pair(byte_size - alloc_size, addr + alloc_size));
1991 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001992 }
1993 return reinterpret_cast<mirror::Object*>(addr);
1994}
1995
1996mirror::Object* ConcurrentCopying::Copy(mirror::Object* from_ref) {
1997 DCHECK(region_space_->IsInFromSpace(from_ref));
1998 // No read barrier to avoid nested RB that might violate the to-space
1999 // invariant. Note that from_ref is a from space ref so the SizeOf()
2000 // call will access the from-space meta objects, but it's ok and necessary.
2001 size_t obj_size = from_ref->SizeOf<kDefaultVerifyFlags, kWithoutReadBarrier>();
2002 size_t region_space_alloc_size = RoundUp(obj_size, space::RegionSpace::kAlignment);
2003 size_t region_space_bytes_allocated = 0U;
2004 size_t non_moving_space_bytes_allocated = 0U;
2005 size_t bytes_allocated = 0U;
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07002006 size_t dummy;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002007 mirror::Object* to_ref = region_space_->AllocNonvirtual<true>(
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07002008 region_space_alloc_size, &region_space_bytes_allocated, nullptr, &dummy);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002009 bytes_allocated = region_space_bytes_allocated;
2010 if (to_ref != nullptr) {
2011 DCHECK_EQ(region_space_alloc_size, region_space_bytes_allocated);
2012 }
2013 bool fall_back_to_non_moving = false;
2014 if (UNLIKELY(to_ref == nullptr)) {
2015 // Failed to allocate in the region space. Try the skipped blocks.
2016 to_ref = AllocateInSkippedBlock(region_space_alloc_size);
2017 if (to_ref != nullptr) {
2018 // Succeeded to allocate in a skipped block.
2019 if (heap_->use_tlab_) {
2020 // This is necessary for the tlab case as it's not accounted in the space.
2021 region_space_->RecordAlloc(to_ref);
2022 }
2023 bytes_allocated = region_space_alloc_size;
2024 } else {
2025 // Fall back to the non-moving space.
2026 fall_back_to_non_moving = true;
2027 if (kVerboseMode) {
2028 LOG(INFO) << "Out of memory in the to-space. Fall back to non-moving. skipped_bytes="
2029 << to_space_bytes_skipped_.LoadSequentiallyConsistent()
2030 << " skipped_objects=" << to_space_objects_skipped_.LoadSequentiallyConsistent();
2031 }
2032 fall_back_to_non_moving = true;
2033 to_ref = heap_->non_moving_space_->Alloc(Thread::Current(), obj_size,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07002034 &non_moving_space_bytes_allocated, nullptr, &dummy);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002035 CHECK(to_ref != nullptr) << "Fall-back non-moving space allocation failed";
2036 bytes_allocated = non_moving_space_bytes_allocated;
2037 // Mark it in the mark bitmap.
2038 accounting::ContinuousSpaceBitmap* mark_bitmap =
2039 heap_mark_bitmap_->GetContinuousSpaceBitmap(to_ref);
2040 CHECK(mark_bitmap != nullptr);
2041 CHECK(!mark_bitmap->AtomicTestAndSet(to_ref));
2042 }
2043 }
2044 DCHECK(to_ref != nullptr);
2045
2046 // Attempt to install the forward pointer. This is in a loop as the
2047 // lock word atomic write can fail.
2048 while (true) {
2049 // Copy the object. TODO: copy only the lockword in the second iteration and on?
2050 memcpy(to_ref, from_ref, obj_size);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002051
2052 LockWord old_lock_word = to_ref->GetLockWord(false);
2053
2054 if (old_lock_word.GetState() == LockWord::kForwardingAddress) {
2055 // Lost the race. Another thread (either GC or mutator) stored
2056 // the forwarding pointer first. Make the lost copy (to_ref)
2057 // look like a valid but dead (dummy) object and keep it for
2058 // future reuse.
2059 FillWithDummyObject(to_ref, bytes_allocated);
2060 if (!fall_back_to_non_moving) {
2061 DCHECK(region_space_->IsInToSpace(to_ref));
2062 if (bytes_allocated > space::RegionSpace::kRegionSize) {
2063 // Free the large alloc.
2064 region_space_->FreeLarge(to_ref, bytes_allocated);
2065 } else {
2066 // Record the lost copy for later reuse.
2067 heap_->num_bytes_allocated_.FetchAndAddSequentiallyConsistent(bytes_allocated);
2068 to_space_bytes_skipped_.FetchAndAddSequentiallyConsistent(bytes_allocated);
2069 to_space_objects_skipped_.FetchAndAddSequentiallyConsistent(1);
2070 MutexLock mu(Thread::Current(), skipped_blocks_lock_);
2071 skipped_blocks_map_.insert(std::make_pair(bytes_allocated,
2072 reinterpret_cast<uint8_t*>(to_ref)));
2073 }
2074 } else {
2075 DCHECK(heap_->non_moving_space_->HasAddress(to_ref));
2076 DCHECK_EQ(bytes_allocated, non_moving_space_bytes_allocated);
2077 // Free the non-moving-space chunk.
2078 accounting::ContinuousSpaceBitmap* mark_bitmap =
2079 heap_mark_bitmap_->GetContinuousSpaceBitmap(to_ref);
2080 CHECK(mark_bitmap != nullptr);
2081 CHECK(mark_bitmap->Clear(to_ref));
2082 heap_->non_moving_space_->Free(Thread::Current(), to_ref);
2083 }
2084
2085 // Get the winner's forward ptr.
2086 mirror::Object* lost_fwd_ptr = to_ref;
2087 to_ref = reinterpret_cast<mirror::Object*>(old_lock_word.ForwardingAddress());
2088 CHECK(to_ref != nullptr);
2089 CHECK_NE(to_ref, lost_fwd_ptr);
2090 CHECK(region_space_->IsInToSpace(to_ref) || heap_->non_moving_space_->HasAddress(to_ref));
2091 CHECK_NE(to_ref->GetLockWord(false).GetState(), LockWord::kForwardingAddress);
2092 return to_ref;
2093 }
2094
Hiroshi Yamauchi60f63f52015-04-23 16:12:40 -07002095 // Set the gray ptr.
2096 if (kUseBakerReadBarrier) {
2097 to_ref->SetReadBarrierPointer(ReadBarrier::GrayPtr());
2098 }
2099
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002100 LockWord new_lock_word = LockWord::FromForwardingAddress(reinterpret_cast<size_t>(to_ref));
2101
2102 // Try to atomically write the fwd ptr.
2103 bool success = from_ref->CasLockWordWeakSequentiallyConsistent(old_lock_word, new_lock_word);
2104 if (LIKELY(success)) {
2105 // The CAS succeeded.
2106 objects_moved_.FetchAndAddSequentiallyConsistent(1);
2107 bytes_moved_.FetchAndAddSequentiallyConsistent(region_space_alloc_size);
2108 if (LIKELY(!fall_back_to_non_moving)) {
2109 DCHECK(region_space_->IsInToSpace(to_ref));
2110 } else {
2111 DCHECK(heap_->non_moving_space_->HasAddress(to_ref));
2112 DCHECK_EQ(bytes_allocated, non_moving_space_bytes_allocated);
2113 }
2114 if (kUseBakerReadBarrier) {
2115 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr());
2116 }
2117 DCHECK(GetFwdPtr(from_ref) == to_ref);
2118 CHECK_NE(to_ref->GetLockWord(false).GetState(), LockWord::kForwardingAddress);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002119 PushOntoMarkStack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002120 return to_ref;
2121 } else {
2122 // The CAS failed. It may have lost the race or may have failed
2123 // due to monitor/hashcode ops. Either way, retry.
2124 }
2125 }
2126}
2127
2128mirror::Object* ConcurrentCopying::IsMarked(mirror::Object* from_ref) {
2129 DCHECK(from_ref != nullptr);
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08002130 space::RegionSpace::RegionType rtype = region_space_->GetRegionType(from_ref);
2131 if (rtype == space::RegionSpace::RegionType::kRegionTypeToSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002132 // It's already marked.
2133 return from_ref;
2134 }
2135 mirror::Object* to_ref;
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08002136 if (rtype == space::RegionSpace::RegionType::kRegionTypeFromSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002137 to_ref = GetFwdPtr(from_ref);
2138 DCHECK(to_ref == nullptr || region_space_->IsInToSpace(to_ref) ||
2139 heap_->non_moving_space_->HasAddress(to_ref))
2140 << "from_ref=" << from_ref << " to_ref=" << to_ref;
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08002141 } else if (rtype == space::RegionSpace::RegionType::kRegionTypeUnevacFromSpace) {
Mathieu Chartierc381c362016-08-23 13:27:53 -07002142 if (IsMarkedInUnevacFromSpace(from_ref)) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002143 to_ref = from_ref;
2144 } else {
2145 to_ref = nullptr;
2146 }
2147 } else {
2148 // from_ref is in a non-moving space.
Mathieu Chartier763a31e2015-11-16 16:05:55 -08002149 if (immune_spaces_.ContainsObject(from_ref)) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002150 // An immune object is alive.
2151 to_ref = from_ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002152 } else {
2153 // Non-immune non-moving space. Use the mark bitmap.
2154 accounting::ContinuousSpaceBitmap* mark_bitmap =
2155 heap_mark_bitmap_->GetContinuousSpaceBitmap(from_ref);
2156 accounting::LargeObjectBitmap* los_bitmap =
2157 heap_mark_bitmap_->GetLargeObjectBitmap(from_ref);
2158 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
2159 bool is_los = mark_bitmap == nullptr;
2160 if (!is_los && mark_bitmap->Test(from_ref)) {
2161 // Already marked.
2162 to_ref = from_ref;
2163 } else if (is_los && los_bitmap->Test(from_ref)) {
2164 // Already marked in LOS.
2165 to_ref = from_ref;
2166 } else {
2167 // Not marked.
2168 if (IsOnAllocStack(from_ref)) {
2169 // If on the allocation stack, it's considered marked.
2170 to_ref = from_ref;
2171 } else {
2172 // Not marked.
2173 to_ref = nullptr;
2174 }
2175 }
2176 }
2177 }
2178 return to_ref;
2179}
2180
2181bool ConcurrentCopying::IsOnAllocStack(mirror::Object* ref) {
2182 QuasiAtomic::ThreadFenceAcquire();
2183 accounting::ObjectStack* alloc_stack = GetAllocationStack();
Mathieu Chartiercb535da2015-01-23 13:50:03 -08002184 return alloc_stack->Contains(ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002185}
2186
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002187mirror::Object* ConcurrentCopying::MarkNonMoving(mirror::Object* ref) {
2188 // ref is in a non-moving space (from_ref == to_ref).
2189 DCHECK(!region_space_->HasAddress(ref)) << ref;
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002190 DCHECK(!immune_spaces_.ContainsObject(ref));
2191 // Use the mark bitmap.
2192 accounting::ContinuousSpaceBitmap* mark_bitmap =
2193 heap_mark_bitmap_->GetContinuousSpaceBitmap(ref);
2194 accounting::LargeObjectBitmap* los_bitmap =
2195 heap_mark_bitmap_->GetLargeObjectBitmap(ref);
2196 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
2197 bool is_los = mark_bitmap == nullptr;
2198 if (!is_los && mark_bitmap->Test(ref)) {
2199 // Already marked.
2200 if (kUseBakerReadBarrier) {
2201 DCHECK(ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr() ||
2202 ref->GetReadBarrierPointer() == ReadBarrier::WhitePtr());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002203 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002204 } else if (is_los && los_bitmap->Test(ref)) {
2205 // Already marked in LOS.
2206 if (kUseBakerReadBarrier) {
2207 DCHECK(ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr() ||
2208 ref->GetReadBarrierPointer() == ReadBarrier::WhitePtr());
2209 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002210 } else {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002211 // Not marked.
2212 if (IsOnAllocStack(ref)) {
2213 // If it's on the allocation stack, it's considered marked. Keep it white.
2214 // Objects on the allocation stack need not be marked.
2215 if (!is_los) {
2216 DCHECK(!mark_bitmap->Test(ref));
2217 } else {
2218 DCHECK(!los_bitmap->Test(ref));
Nicolas Geoffrayddeb1722016-06-28 08:25:59 +00002219 }
Nicolas Geoffrayddeb1722016-06-28 08:25:59 +00002220 if (kUseBakerReadBarrier) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002221 DCHECK_EQ(ref->GetReadBarrierPointer(), ReadBarrier::WhitePtr());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002222 }
2223 } else {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002224 // For the baker-style RB, we need to handle 'false-gray' cases. See the
2225 // kRegionTypeUnevacFromSpace-case comment in Mark().
2226 if (kUseBakerReadBarrier) {
2227 // Test the bitmap first to reduce the chance of false gray cases.
2228 if ((!is_los && mark_bitmap->Test(ref)) ||
2229 (is_los && los_bitmap->Test(ref))) {
2230 return ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002231 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002232 }
2233 // Not marked or on the allocation stack. Try to mark it.
2234 // This may or may not succeed, which is ok.
2235 bool cas_success = false;
2236 if (kUseBakerReadBarrier) {
2237 cas_success = ref->AtomicSetReadBarrierPointer(ReadBarrier::WhitePtr(),
2238 ReadBarrier::GrayPtr());
2239 }
2240 if (!is_los && mark_bitmap->AtomicTestAndSet(ref)) {
2241 // Already marked.
2242 if (kUseBakerReadBarrier && cas_success &&
2243 ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr()) {
2244 PushOntoFalseGrayStack(ref);
2245 }
2246 } else if (is_los && los_bitmap->AtomicTestAndSet(ref)) {
2247 // Already marked in LOS.
2248 if (kUseBakerReadBarrier && cas_success &&
2249 ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr()) {
2250 PushOntoFalseGrayStack(ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002251 }
2252 } else {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002253 // Newly marked.
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08002254 if (kUseBakerReadBarrier) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002255 DCHECK_EQ(ref->GetReadBarrierPointer(), ReadBarrier::GrayPtr());
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08002256 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002257 PushOntoMarkStack(ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002258 }
2259 }
2260 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002261 return ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002262}
2263
2264void ConcurrentCopying::FinishPhase() {
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -08002265 Thread* const self = Thread::Current();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002266 {
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -08002267 MutexLock mu(self, mark_stack_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002268 CHECK_EQ(pooled_mark_stacks_.size(), kMarkStackPoolSize);
2269 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002270 region_space_ = nullptr;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002271 {
2272 MutexLock mu(Thread::Current(), skipped_blocks_lock_);
2273 skipped_blocks_map_.clear();
2274 }
Mathieu Chartier56fe2582016-07-14 13:30:03 -07002275 {
2276 ReaderMutexLock mu(self, *Locks::mutator_lock_);
Mathieu Chartier21328a12016-07-22 10:47:45 -07002277 {
2278 WriterMutexLock mu2(self, *Locks::heap_bitmap_lock_);
2279 heap_->ClearMarkedObjects();
2280 }
2281 if (kUseBakerReadBarrier && kFilterModUnionCards) {
2282 TimingLogger::ScopedTiming split("FilterModUnionCards", GetTimings());
2283 ReaderMutexLock mu2(self, *Locks::heap_bitmap_lock_);
2284 gc::Heap* const heap = Runtime::Current()->GetHeap();
2285 for (space::ContinuousSpace* space : immune_spaces_.GetSpaces()) {
2286 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
2287 accounting::ModUnionTable* table = heap->FindModUnionTableFromSpace(space);
2288 // Filter out cards that don't need to be set.
2289 if (table != nullptr) {
2290 table->FilterCards();
2291 }
2292 }
2293 }
Mathieu Chartier36a270a2016-07-28 18:08:51 -07002294 if (kUseBakerReadBarrier) {
2295 TimingLogger::ScopedTiming split("EmptyRBMarkBitStack", GetTimings());
2296 DCHECK(rb_mark_bit_stack_.get() != nullptr);
2297 const auto* limit = rb_mark_bit_stack_->End();
2298 for (StackReference<mirror::Object>* it = rb_mark_bit_stack_->Begin(); it != limit; ++it) {
2299 CHECK(it->AsMirrorPtr()->AtomicSetMarkBit(1, 0));
2300 }
2301 rb_mark_bit_stack_->Reset();
2302 }
Mathieu Chartier56fe2582016-07-14 13:30:03 -07002303 }
2304 if (measure_read_barrier_slow_path_) {
2305 MutexLock mu(self, rb_slow_path_histogram_lock_);
2306 rb_slow_path_time_histogram_.AdjustAndAddValue(rb_slow_path_ns_.LoadRelaxed());
2307 rb_slow_path_count_total_ += rb_slow_path_count_.LoadRelaxed();
2308 rb_slow_path_count_gc_total_ += rb_slow_path_count_gc_.LoadRelaxed();
2309 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002310}
2311
Mathieu Chartier97509952015-07-13 14:35:43 -07002312bool ConcurrentCopying::IsMarkedHeapReference(mirror::HeapReference<mirror::Object>* field) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002313 mirror::Object* from_ref = field->AsMirrorPtr();
Mathieu Chartier97509952015-07-13 14:35:43 -07002314 mirror::Object* to_ref = IsMarked(from_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002315 if (to_ref == nullptr) {
2316 return false;
2317 }
2318 if (from_ref != to_ref) {
2319 QuasiAtomic::ThreadFenceRelease();
2320 field->Assign(to_ref);
2321 QuasiAtomic::ThreadFenceSequentiallyConsistent();
2322 }
2323 return true;
2324}
2325
Mathieu Chartier97509952015-07-13 14:35:43 -07002326mirror::Object* ConcurrentCopying::MarkObject(mirror::Object* from_ref) {
2327 return Mark(from_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002328}
2329
2330void ConcurrentCopying::DelayReferenceReferent(mirror::Class* klass, mirror::Reference* reference) {
Mathieu Chartier97509952015-07-13 14:35:43 -07002331 heap_->GetReferenceProcessor()->DelayReferenceReferent(klass, reference, this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002332}
2333
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002334void ConcurrentCopying::ProcessReferences(Thread* self) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002335 TimingLogger::ScopedTiming split("ProcessReferences", GetTimings());
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002336 // 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 -08002337 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
2338 GetHeap()->GetReferenceProcessor()->ProcessReferences(
Mathieu Chartier97509952015-07-13 14:35:43 -07002339 true /*concurrent*/, GetTimings(), GetCurrentIteration()->GetClearSoftReferences(), this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002340}
2341
2342void ConcurrentCopying::RevokeAllThreadLocalBuffers() {
2343 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
2344 region_space_->RevokeAllThreadLocalBuffers();
2345}
2346
Mathieu Chartier56fe2582016-07-14 13:30:03 -07002347mirror::Object* ConcurrentCopying::MarkFromReadBarrierWithMeasurements(mirror::Object* from_ref) {
2348 if (Thread::Current() != thread_running_gc_) {
2349 rb_slow_path_count_.FetchAndAddRelaxed(1u);
2350 } else {
2351 rb_slow_path_count_gc_.FetchAndAddRelaxed(1u);
2352 }
2353 ScopedTrace tr(__FUNCTION__);
2354 const uint64_t start_time = measure_read_barrier_slow_path_ ? NanoTime() : 0u;
2355 mirror::Object* ret = Mark(from_ref);
2356 if (measure_read_barrier_slow_path_) {
2357 rb_slow_path_ns_.FetchAndAddRelaxed(NanoTime() - start_time);
2358 }
2359 return ret;
2360}
2361
2362void ConcurrentCopying::DumpPerformanceInfo(std::ostream& os) {
2363 GarbageCollector::DumpPerformanceInfo(os);
2364 MutexLock mu(Thread::Current(), rb_slow_path_histogram_lock_);
2365 if (rb_slow_path_time_histogram_.SampleSize() > 0) {
2366 Histogram<uint64_t>::CumulativeData cumulative_data;
2367 rb_slow_path_time_histogram_.CreateHistogram(&cumulative_data);
2368 rb_slow_path_time_histogram_.PrintConfidenceIntervals(os, 0.99, cumulative_data);
2369 }
2370 if (rb_slow_path_count_total_ > 0) {
2371 os << "Slow path count " << rb_slow_path_count_total_ << "\n";
2372 }
2373 if (rb_slow_path_count_gc_total_ > 0) {
2374 os << "GC slow path count " << rb_slow_path_count_gc_total_ << "\n";
2375 }
Mathieu Chartiercca44a02016-08-17 10:07:29 -07002376 os << "Cumulative bytes moved " << cumulative_bytes_moved_.LoadRelaxed() << "\n";
2377 os << "Cumulative objects moved " << cumulative_objects_moved_.LoadRelaxed() << "\n";
Mathieu Chartier56fe2582016-07-14 13:30:03 -07002378}
2379
Hiroshi Yamauchid5307ec2014-03-27 21:07:51 -07002380} // namespace collector
2381} // namespace gc
2382} // namespace art