blob: 6044053b4f45d415ad6be81f0493e93870412ab6 [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"
Mathieu Chartier0795f232016-09-27 18:43:30 -070035#include "scoped_thread_state_change-inl.h"
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080036#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() ? "" : " ") +
Hiroshi Yamauchi88e08162017-01-06 15:03:26 -080061 "concurrent copying"),
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_) {
Mathieu Chartier7ec38dc2016-10-07 15:24:46 -0700173 // It is OK to clear the bitmap with mutators running since the only place it is read is
174 // VisitObjects which has exclusion with CC.
175 region_space_bitmap_ = region_space_->GetMarkBitmap();
176 region_space_bitmap_->Clear();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800177 }
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;
Mathieu Chartierfe814e82016-11-09 14:32:49 -0800249 thread->SetIsGcMarkingAndUpdateEntrypoints(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
Mathieu Chartier31e88222016-10-14 18:43:19 -0700357 void operator()(ObjPtr<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
Mathieu Chartier31e88222016-10-14 18:43:19 -0700364 void operator()(ObjPtr<mirror::Class> klass, ObjPtr<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
Mathieu Chartier31e88222016-10-14 18:43:19 -0700389 void CheckReference(ObjPtr<mirror::Object> ref,
390 ObjPtr<mirror::Object> holder,
391 MemberOffset offset) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700392 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700393 if (ref != nullptr) {
Mathieu Chartier31e88222016-10-14 18:43:19 -0700394 if (!collector_->immune_spaces_.ContainsObject(ref.Ptr())) {
Mathieu Chartier962cd7a2016-08-16 12:15:59 -0700395 // Not immune, must be a zygote large object.
396 CHECK(Runtime::Current()->GetHeap()->GetLargeObjectsSpace()->IsZygoteLargeObject(
Mathieu Chartier31e88222016-10-14 18:43:19 -0700397 Thread::Current(), ref.Ptr()))
Mathieu Chartier962cd7a2016-08-16 12:15:59 -0700398 << "Non gray object references non immune, non zygote large object "<< ref << " "
David Sehr709b0702016-10-13 09:12:37 -0700399 << mirror::Object::PrettyTypeOf(ref) << " in holder " << holder << " "
400 << mirror::Object::PrettyTypeOf(holder) << " offset=" << offset.Uint32Value();
Mathieu Chartier962cd7a2016-08-16 12:15:59 -0700401 } else {
402 // Make sure the large object class is immune since we will never scan the large object.
403 CHECK(collector_->immune_spaces_.ContainsObject(
404 ref->GetClass<kVerifyNone, kWithoutReadBarrier>()));
405 }
Mathieu Chartier21328a12016-07-22 10:47:45 -0700406 }
407 }
408};
409
410void ConcurrentCopying::VerifyGrayImmuneObjects() {
411 TimingLogger::ScopedTiming split(__FUNCTION__, GetTimings());
412 for (auto& space : immune_spaces_.GetSpaces()) {
413 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
414 accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
415 VerifyGrayImmuneObjectsVisitor visitor(this);
416 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()),
417 reinterpret_cast<uintptr_t>(space->Limit()),
418 [&visitor](mirror::Object* obj)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700419 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700420 // If an object is not gray, it should only have references to things in the immune spaces.
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700421 if (obj->GetReadBarrierState() != ReadBarrier::GrayState()) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700422 obj->VisitReferences</*kVisitNativeRoots*/true,
423 kDefaultVerifyFlags,
424 kWithoutReadBarrier>(visitor, visitor);
425 }
426 });
427 }
428}
429
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800430// Switch threads that from from-space to to-space refs. Forward/mark the thread roots.
431void ConcurrentCopying::FlipThreadRoots() {
432 TimingLogger::ScopedTiming split("FlipThreadRoots", GetTimings());
433 if (kVerboseMode) {
434 LOG(INFO) << "time=" << region_space_->Time();
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700435 region_space_->DumpNonFreeRegions(LOG_STREAM(INFO));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800436 }
437 Thread* self = Thread::Current();
438 Locks::mutator_lock_->AssertNotHeld(self);
439 gc_barrier_->Init(self, 0);
440 ThreadFlipVisitor thread_flip_visitor(this, heap_->use_tlab_);
441 FlipCallback flip_callback(this);
442 size_t barrier_count = Runtime::Current()->FlipThreadRoots(
443 &thread_flip_visitor, &flip_callback, this);
444 {
445 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
446 gc_barrier_->Increment(self, barrier_count);
447 }
448 is_asserting_to_space_invariant_ = true;
449 QuasiAtomic::ThreadFenceForConstructor();
450 if (kVerboseMode) {
451 LOG(INFO) << "time=" << region_space_->Time();
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700452 region_space_->DumpNonFreeRegions(LOG_STREAM(INFO));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800453 LOG(INFO) << "GC end of FlipThreadRoots";
454 }
455}
456
Mathieu Chartier21328a12016-07-22 10:47:45 -0700457class ConcurrentCopying::GrayImmuneObjectVisitor {
458 public:
459 explicit GrayImmuneObjectVisitor() {}
460
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700461 ALWAYS_INLINE void operator()(mirror::Object* obj) const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700462 if (kUseBakerReadBarrier) {
463 if (kIsDebugBuild) {
464 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
465 }
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700466 obj->SetReadBarrierState(ReadBarrier::GrayState());
Mathieu Chartier21328a12016-07-22 10:47:45 -0700467 }
468 }
469
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700470 static void Callback(mirror::Object* obj, void* arg) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700471 reinterpret_cast<GrayImmuneObjectVisitor*>(arg)->operator()(obj);
472 }
473};
474
475void ConcurrentCopying::GrayAllDirtyImmuneObjects() {
476 TimingLogger::ScopedTiming split(__FUNCTION__, GetTimings());
477 gc::Heap* const heap = Runtime::Current()->GetHeap();
478 accounting::CardTable* const card_table = heap->GetCardTable();
479 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
480 for (space::ContinuousSpace* space : immune_spaces_.GetSpaces()) {
481 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
482 GrayImmuneObjectVisitor visitor;
483 accounting::ModUnionTable* table = heap->FindModUnionTableFromSpace(space);
484 // Mark all the objects on dirty cards since these may point to objects in other space.
485 // Once these are marked, the GC will eventually clear them later.
486 // Table is non null for boot image and zygote spaces. It is only null for application image
487 // spaces.
488 if (table != nullptr) {
Mathieu Chartier6e6078a2016-10-24 15:45:41 -0700489 // TODO: Consider adding precleaning outside the pause.
490 table->ProcessCards();
Mathieu Chartier21328a12016-07-22 10:47:45 -0700491 table->VisitObjects(GrayImmuneObjectVisitor::Callback, &visitor);
Mathieu Chartier6e6078a2016-10-24 15:45:41 -0700492 // Since the cards are recorded in the mod-union table and this is paused, we can clear
493 // the cards for the space (to madvise).
494 TimingLogger::ScopedTiming split2("(Paused)ClearCards", GetTimings());
495 card_table->ClearCardRange(space->Begin(),
496 AlignDown(space->End(), accounting::CardTable::kCardSize));
Mathieu Chartier21328a12016-07-22 10:47:45 -0700497 } else {
498 // TODO: Consider having a mark bitmap for app image spaces and avoid scanning during the
499 // pause because app image spaces are all dirty pages anyways.
500 card_table->Scan<false>(space->GetMarkBitmap(), space->Begin(), space->End(), visitor);
501 }
502 }
503 // Since all of the objects that may point to other spaces are marked, we can avoid all the read
504 // barriers in the immune spaces.
505 updated_all_immune_objects_.StoreRelaxed(true);
506}
507
Mathieu Chartiera4f6af92015-08-11 17:35:25 -0700508void ConcurrentCopying::SwapStacks() {
509 heap_->SwapStacks();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800510}
511
512void ConcurrentCopying::RecordLiveStackFreezeSize(Thread* self) {
513 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
514 live_stack_freeze_size_ = heap_->GetLiveStack()->Size();
515}
516
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700517// Used to visit objects in the immune spaces.
518inline void ConcurrentCopying::ScanImmuneObject(mirror::Object* obj) {
519 DCHECK(obj != nullptr);
520 DCHECK(immune_spaces_.ContainsObject(obj));
521 // Update the fields without graying it or pushing it onto the mark stack.
522 Scan(obj);
523}
524
525class ConcurrentCopying::ImmuneSpaceScanObjVisitor {
526 public:
527 explicit ImmuneSpaceScanObjVisitor(ConcurrentCopying* cc)
528 : collector_(cc) {}
529
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700530 ALWAYS_INLINE void operator()(mirror::Object* obj) const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700531 if (kUseBakerReadBarrier && kGrayDirtyImmuneObjects) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700532 if (obj->GetReadBarrierState() == ReadBarrier::GrayState()) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700533 collector_->ScanImmuneObject(obj);
534 // Done scanning the object, go back to white.
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700535 bool success = obj->AtomicSetReadBarrierState(ReadBarrier::GrayState(),
536 ReadBarrier::WhiteState());
Mathieu Chartier21328a12016-07-22 10:47:45 -0700537 CHECK(success);
538 }
539 } else {
540 collector_->ScanImmuneObject(obj);
541 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700542 }
543
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700544 static void Callback(mirror::Object* obj, void* arg) REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi5408f232016-07-29 15:07:05 -0700545 reinterpret_cast<ImmuneSpaceScanObjVisitor*>(arg)->operator()(obj);
546 }
547
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700548 private:
549 ConcurrentCopying* const collector_;
550};
551
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800552// Concurrently mark roots that are guarded by read barriers and process the mark stack.
553void ConcurrentCopying::MarkingPhase() {
554 TimingLogger::ScopedTiming split("MarkingPhase", GetTimings());
555 if (kVerboseMode) {
556 LOG(INFO) << "GC MarkingPhase";
557 }
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -0700558 Thread* self = Thread::Current();
559 if (kIsDebugBuild) {
560 MutexLock mu(self, *Locks::thread_list_lock_);
561 CHECK(weak_ref_access_enabled_);
562 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700563
564 // Scan immune spaces.
565 // Update all the fields in the immune spaces first without graying the objects so that we
566 // minimize dirty pages in the immune spaces. Note mutators can concurrently access and gray some
567 // of the objects.
568 if (kUseBakerReadBarrier) {
569 gc_grays_immune_objects_ = false;
Hiroshi Yamauchi16292fc2016-06-20 20:23:34 -0700570 }
Mathieu Chartier21328a12016-07-22 10:47:45 -0700571 {
572 TimingLogger::ScopedTiming split2("ScanImmuneSpaces", GetTimings());
573 for (auto& space : immune_spaces_.GetSpaces()) {
574 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
575 accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
Hiroshi Yamauchi5408f232016-07-29 15:07:05 -0700576 accounting::ModUnionTable* table = heap_->FindModUnionTableFromSpace(space);
Mathieu Chartier21328a12016-07-22 10:47:45 -0700577 ImmuneSpaceScanObjVisitor visitor(this);
Hiroshi Yamauchi5408f232016-07-29 15:07:05 -0700578 if (kUseBakerReadBarrier && kGrayDirtyImmuneObjects && table != nullptr) {
579 table->VisitObjects(ImmuneSpaceScanObjVisitor::Callback, &visitor);
580 } else {
581 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()),
582 reinterpret_cast<uintptr_t>(space->Limit()),
583 visitor);
584 }
Mathieu Chartier21328a12016-07-22 10:47:45 -0700585 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700586 }
587 if (kUseBakerReadBarrier) {
588 // This release fence makes the field updates in the above loop visible before allowing mutator
589 // getting access to immune objects without graying it first.
590 updated_all_immune_objects_.StoreRelease(true);
591 // Now whiten immune objects concurrently accessed and grayed by mutators. We can't do this in
592 // the above loop because we would incorrectly disable the read barrier by whitening an object
593 // which may point to an unscanned, white object, breaking the to-space invariant.
594 //
595 // Make sure no mutators are in the middle of marking an immune object before whitening immune
596 // objects.
597 IssueEmptyCheckpoint();
598 MutexLock mu(Thread::Current(), immune_gray_stack_lock_);
599 if (kVerboseMode) {
600 LOG(INFO) << "immune gray stack size=" << immune_gray_stack_.size();
601 }
602 for (mirror::Object* obj : immune_gray_stack_) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700603 DCHECK(obj->GetReadBarrierState() == ReadBarrier::GrayState());
604 bool success = obj->AtomicSetReadBarrierState(ReadBarrier::GrayState(),
605 ReadBarrier::WhiteState());
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700606 DCHECK(success);
607 }
608 immune_gray_stack_.clear();
609 }
610
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800611 {
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -0700612 TimingLogger::ScopedTiming split2("VisitConcurrentRoots", GetTimings());
613 Runtime::Current()->VisitConcurrentRoots(this, kVisitRootFlagAllRoots);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800614 }
615 {
616 // TODO: don't visit the transaction roots if it's not active.
617 TimingLogger::ScopedTiming split5("VisitNonThreadRoots", GetTimings());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700618 Runtime::Current()->VisitNonThreadRoots(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800619 }
620
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800621 {
Mathieu Chartiera6b1ead2015-10-06 10:32:38 -0700622 TimingLogger::ScopedTiming split7("ProcessMarkStack", GetTimings());
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700623 // We transition through three mark stack modes (thread-local, shared, GC-exclusive). The
624 // primary reasons are the fact that we need to use a checkpoint to process thread-local mark
625 // stacks, but after we disable weak refs accesses, we can't use a checkpoint due to a deadlock
626 // issue because running threads potentially blocking at WaitHoldingLocks, and that once we
627 // reach the point where we process weak references, we can avoid using a lock when accessing
628 // the GC mark stack, which makes mark stack processing more efficient.
629
630 // Process the mark stack once in the thread local stack mode. This marks most of the live
631 // objects, aside from weak ref accesses with read barriers (Reference::GetReferent() and system
632 // weaks) that may happen concurrently while we processing the mark stack and newly mark/gray
633 // objects and push refs on the mark stack.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800634 ProcessMarkStack();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700635 // Switch to the shared mark stack mode. That is, revoke and process thread-local mark stacks
636 // for the last time before transitioning to the shared mark stack mode, which would process new
637 // refs that may have been concurrently pushed onto the mark stack during the ProcessMarkStack()
638 // call above. At the same time, disable weak ref accesses using a per-thread flag. It's
639 // important to do these together in a single checkpoint so that we can ensure that mutators
640 // won't newly gray objects and push new refs onto the mark stack due to weak ref accesses and
641 // mutators safely transition to the shared mark stack mode (without leaving unprocessed refs on
642 // the thread-local mark stacks), without a race. This is why we use a thread-local weak ref
643 // access flag Thread::tls32_.weak_ref_access_enabled_ instead of the global ones.
644 SwitchToSharedMarkStackMode();
645 CHECK(!self->GetWeakRefAccessEnabled());
646 // Now that weak refs accesses are disabled, once we exhaust the shared mark stack again here
647 // (which may be non-empty if there were refs found on thread-local mark stacks during the above
648 // SwitchToSharedMarkStackMode() call), we won't have new refs to process, that is, mutators
649 // (via read barriers) have no way to produce any more refs to process. Marking converges once
650 // before we process weak refs below.
651 ProcessMarkStack();
652 CheckEmptyMarkStack();
653 // Switch to the GC exclusive mark stack mode so that we can process the mark stack without a
654 // lock from this point on.
655 SwitchToGcExclusiveMarkStackMode();
656 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800657 if (kVerboseMode) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800658 LOG(INFO) << "ProcessReferences";
659 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700660 // Process weak references. This may produce new refs to process and have them processed via
Mathieu Chartier97509952015-07-13 14:35:43 -0700661 // ProcessMarkStack (in the GC exclusive mark stack mode).
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700662 ProcessReferences(self);
663 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800664 if (kVerboseMode) {
665 LOG(INFO) << "SweepSystemWeaks";
666 }
667 SweepSystemWeaks(self);
668 if (kVerboseMode) {
669 LOG(INFO) << "SweepSystemWeaks done";
670 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700671 // Process the mark stack here one last time because the above SweepSystemWeaks() call may have
672 // marked some objects (strings alive) as hash_set::Erase() can call the hash function for
673 // arbitrary elements in the weak intern table in InternTable::Table::SweepWeaks().
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800674 ProcessMarkStack();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700675 CheckEmptyMarkStack();
676 // Re-enable weak ref accesses.
677 ReenableWeakRefAccess(self);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -0700678 // Free data for class loaders that we unloaded.
679 Runtime::Current()->GetClassLinker()->CleanupClassLoaders();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700680 // Marking is done. Disable marking.
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700681 DisableMarking();
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800682 if (kUseBakerReadBarrier) {
683 ProcessFalseGrayStack();
684 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700685 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800686 }
687
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -0700688 if (kIsDebugBuild) {
689 MutexLock mu(self, *Locks::thread_list_lock_);
690 CHECK(weak_ref_access_enabled_);
691 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800692 if (kVerboseMode) {
693 LOG(INFO) << "GC end of MarkingPhase";
694 }
695}
696
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700697void ConcurrentCopying::ReenableWeakRefAccess(Thread* self) {
698 if (kVerboseMode) {
699 LOG(INFO) << "ReenableWeakRefAccess";
700 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700701 // Iterate all threads (don't need to or can't use a checkpoint) and re-enable weak ref access.
702 {
703 MutexLock mu(self, *Locks::thread_list_lock_);
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -0700704 weak_ref_access_enabled_ = true; // This is for new threads.
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700705 std::list<Thread*> thread_list = Runtime::Current()->GetThreadList()->GetList();
706 for (Thread* thread : thread_list) {
707 thread->SetWeakRefAccessEnabled(true);
708 }
709 }
710 // Unblock blocking threads.
711 GetHeap()->GetReferenceProcessor()->BroadcastForSlowPath(self);
712 Runtime::Current()->BroadcastForNewSystemWeaks();
713}
714
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700715class ConcurrentCopying::DisableMarkingCheckpoint : public Closure {
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700716 public:
717 explicit DisableMarkingCheckpoint(ConcurrentCopying* concurrent_copying)
718 : concurrent_copying_(concurrent_copying) {
719 }
720
721 void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
722 // Note: self is not necessarily equal to thread since thread may be suspended.
723 Thread* self = Thread::Current();
724 DCHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
725 << thread->GetState() << " thread " << thread << " self " << self;
726 // Disable the thread-local is_gc_marking flag.
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -0700727 // Note a thread that has just started right before this checkpoint may have already this flag
728 // set to false, which is ok.
Mathieu Chartierfe814e82016-11-09 14:32:49 -0800729 thread->SetIsGcMarkingAndUpdateEntrypoints(false);
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700730 // If thread is a running mutator, then act on behalf of the garbage collector.
731 // See the code in ThreadList::RunCheckpoint.
Mathieu Chartier10d25082015-10-28 18:36:09 -0700732 concurrent_copying_->GetBarrier().Pass(self);
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700733 }
734
735 private:
736 ConcurrentCopying* const concurrent_copying_;
737};
738
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -0700739class ConcurrentCopying::DisableMarkingCallback : public Closure {
740 public:
741 explicit DisableMarkingCallback(ConcurrentCopying* concurrent_copying)
742 : concurrent_copying_(concurrent_copying) {
743 }
744
745 void Run(Thread* self ATTRIBUTE_UNUSED) OVERRIDE REQUIRES(Locks::thread_list_lock_) {
746 // This needs to run under the thread_list_lock_ critical section in ThreadList::RunCheckpoint()
747 // to avoid a race with ThreadList::Register().
748 CHECK(concurrent_copying_->is_marking_);
749 concurrent_copying_->is_marking_ = false;
750 }
751
752 private:
753 ConcurrentCopying* const concurrent_copying_;
754};
755
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700756void ConcurrentCopying::IssueDisableMarkingCheckpoint() {
757 Thread* self = Thread::Current();
758 DisableMarkingCheckpoint check_point(this);
759 ThreadList* thread_list = Runtime::Current()->GetThreadList();
760 gc_barrier_->Init(self, 0);
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -0700761 DisableMarkingCallback dmc(this);
762 size_t barrier_count = thread_list->RunCheckpoint(&check_point, &dmc);
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700763 // If there are no threads to wait which implies that all the checkpoint functions are finished,
764 // then no need to release the mutator lock.
765 if (barrier_count == 0) {
766 return;
767 }
768 // Release locks then wait for all mutator threads to pass the barrier.
769 Locks::mutator_lock_->SharedUnlock(self);
770 {
771 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
772 gc_barrier_->Increment(self, barrier_count);
773 }
774 Locks::mutator_lock_->SharedLock(self);
775}
776
777void ConcurrentCopying::DisableMarking() {
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -0700778 // Use a checkpoint to turn off the global is_marking and the thread-local is_gc_marking flags and
779 // to ensure no threads are still in the middle of a read barrier which may have a from-space ref
780 // cached in a local variable.
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700781 IssueDisableMarkingCheckpoint();
782 if (kUseTableLookupReadBarrier) {
783 heap_->rb_table_->ClearAll();
784 DCHECK(heap_->rb_table_->IsAllCleared());
785 }
786 is_mark_stack_push_disallowed_.StoreSequentiallyConsistent(1);
787 mark_stack_mode_.StoreSequentiallyConsistent(kMarkStackModeOff);
788}
789
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800790void ConcurrentCopying::PushOntoFalseGrayStack(mirror::Object* ref) {
791 CHECK(kUseBakerReadBarrier);
792 DCHECK(ref != nullptr);
793 MutexLock mu(Thread::Current(), mark_stack_lock_);
794 false_gray_stack_.push_back(ref);
795}
796
797void ConcurrentCopying::ProcessFalseGrayStack() {
798 CHECK(kUseBakerReadBarrier);
799 // Change the objects on the false gray stack from gray to white.
800 MutexLock mu(Thread::Current(), mark_stack_lock_);
801 for (mirror::Object* obj : false_gray_stack_) {
802 DCHECK(IsMarked(obj));
803 // The object could be white here if a thread got preempted after a success at the
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700804 // AtomicSetReadBarrierState in Mark(), GC started marking through it (but not finished so
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800805 // still gray), and the thread ran to register it onto the false gray stack.
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700806 if (obj->GetReadBarrierState() == ReadBarrier::GrayState()) {
807 bool success = obj->AtomicSetReadBarrierState(ReadBarrier::GrayState(),
808 ReadBarrier::WhiteState());
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800809 DCHECK(success);
810 }
811 }
812 false_gray_stack_.clear();
813}
814
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800815void ConcurrentCopying::IssueEmptyCheckpoint() {
816 Thread* self = Thread::Current();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800817 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Hiroshi Yamauchi30493242016-11-03 13:06:52 -0700818 Barrier* barrier = thread_list->EmptyCheckpointBarrier();
819 barrier->Init(self, 0);
Hiroshi Yamauchia82769c2016-12-02 17:01:51 -0800820 std::vector<uint32_t> runnable_thread_ids; // Used in debug build only
821 size_t barrier_count = thread_list->RunEmptyCheckpoint(runnable_thread_ids);
Lei Lidd9943d2015-02-02 14:24:44 +0800822 // If there are no threads to wait which implys that all the checkpoint functions are finished,
823 // then no need to release the mutator lock.
824 if (barrier_count == 0) {
825 return;
826 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800827 // Release locks then wait for all mutator threads to pass the barrier.
828 Locks::mutator_lock_->SharedUnlock(self);
829 {
830 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
Hiroshi Yamauchia82769c2016-12-02 17:01:51 -0800831 if (kIsDebugBuild) {
832 static constexpr uint64_t kEmptyCheckpointTimeoutMs = 600 * 1000; // 10 minutes.
833 bool timed_out = barrier->Increment(self, barrier_count, kEmptyCheckpointTimeoutMs);
834 if (timed_out) {
Hiroshi Yamauchia82769c2016-12-02 17:01:51 -0800835 std::ostringstream ss;
836 ss << "Empty checkpoint timeout\n";
837 ss << "Barrier count " << barrier->GetCount(self) << "\n";
838 ss << "Runnable thread IDs";
839 for (uint32_t tid : runnable_thread_ids) {
840 ss << " " << tid;
841 }
842 ss << "\n";
843 Locks::mutator_lock_->Dump(ss);
844 ss << "\n";
Hiroshi Yamauchif612aa62017-01-04 20:32:57 -0800845 LOG(FATAL_WITHOUT_ABORT) << ss.str();
846 // Some threads in 'runnable_thread_ids' are probably stuck. Try to dump their stacks.
Hiroshi Yamauchi4b6b5bb2017-01-06 10:45:17 -0800847 // Avoid using ThreadList::Dump() initially because it is likely to get stuck as well.
Hiroshi Yamauchif612aa62017-01-04 20:32:57 -0800848 {
Hiroshi Yamauchic77364c2017-01-17 13:59:59 -0800849 ScopedObjectAccess soa(self);
Hiroshi Yamauchif612aa62017-01-04 20:32:57 -0800850 MutexLock mu1(self, *Locks::thread_list_lock_);
Hiroshi Yamauchi4b6b5bb2017-01-06 10:45:17 -0800851 for (Thread* thread : thread_list->GetList()) {
Hiroshi Yamauchif612aa62017-01-04 20:32:57 -0800852 uint32_t tid = thread->GetThreadId();
853 bool is_in_runnable_thread_ids =
854 std::find(runnable_thread_ids.begin(), runnable_thread_ids.end(), tid) !=
855 runnable_thread_ids.end();
856 if (is_in_runnable_thread_ids &&
857 thread->ReadFlag(kEmptyCheckpointRequest)) {
858 // Found a runnable thread that hasn't responded to the empty checkpoint request.
859 // Assume it's stuck and safe to dump its stack.
860 thread->Dump(LOG_STREAM(FATAL_WITHOUT_ABORT));
861 }
862 }
863 }
Hiroshi Yamauchi4b6b5bb2017-01-06 10:45:17 -0800864 LOG(FATAL_WITHOUT_ABORT)
865 << "Dumped runnable threads that haven't responded to empty checkpoint.";
866 // Now use ThreadList::Dump() to dump more threads, noting it may get stuck.
867 thread_list->Dump(LOG_STREAM(FATAL_WITHOUT_ABORT));
868 LOG(FATAL) << "Dumped all threads.";
Hiroshi Yamauchia82769c2016-12-02 17:01:51 -0800869 }
870 } else {
871 barrier->Increment(self, barrier_count);
872 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800873 }
874 Locks::mutator_lock_->SharedLock(self);
875}
876
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -0700877void ConcurrentCopying::ExpandGcMarkStack() {
878 DCHECK(gc_mark_stack_->IsFull());
879 const size_t new_size = gc_mark_stack_->Capacity() * 2;
880 std::vector<StackReference<mirror::Object>> temp(gc_mark_stack_->Begin(),
881 gc_mark_stack_->End());
882 gc_mark_stack_->Resize(new_size);
883 for (auto& ref : temp) {
884 gc_mark_stack_->PushBack(ref.AsMirrorPtr());
885 }
886 DCHECK(!gc_mark_stack_->IsFull());
887}
888
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800889void ConcurrentCopying::PushOntoMarkStack(mirror::Object* to_ref) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700890 CHECK_EQ(is_mark_stack_push_disallowed_.LoadRelaxed(), 0)
David Sehr709b0702016-10-13 09:12:37 -0700891 << " " << to_ref << " " << mirror::Object::PrettyTypeOf(to_ref);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700892 Thread* self = Thread::Current(); // TODO: pass self as an argument from call sites?
893 CHECK(thread_running_gc_ != nullptr);
894 MarkStackMode mark_stack_mode = mark_stack_mode_.LoadRelaxed();
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -0700895 if (LIKELY(mark_stack_mode == kMarkStackModeThreadLocal)) {
896 if (LIKELY(self == thread_running_gc_)) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700897 // If GC-running thread, use the GC mark stack instead of a thread-local mark stack.
898 CHECK(self->GetThreadLocalMarkStack() == nullptr);
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -0700899 if (UNLIKELY(gc_mark_stack_->IsFull())) {
900 ExpandGcMarkStack();
901 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700902 gc_mark_stack_->PushBack(to_ref);
903 } else {
904 // Otherwise, use a thread-local mark stack.
905 accounting::AtomicStack<mirror::Object>* tl_mark_stack = self->GetThreadLocalMarkStack();
906 if (UNLIKELY(tl_mark_stack == nullptr || tl_mark_stack->IsFull())) {
907 MutexLock mu(self, mark_stack_lock_);
908 // Get a new thread local mark stack.
909 accounting::AtomicStack<mirror::Object>* new_tl_mark_stack;
910 if (!pooled_mark_stacks_.empty()) {
911 // Use a pooled mark stack.
912 new_tl_mark_stack = pooled_mark_stacks_.back();
913 pooled_mark_stacks_.pop_back();
914 } else {
915 // None pooled. Create a new one.
916 new_tl_mark_stack =
917 accounting::AtomicStack<mirror::Object>::Create(
918 "thread local mark stack", 4 * KB, 4 * KB);
919 }
920 DCHECK(new_tl_mark_stack != nullptr);
921 DCHECK(new_tl_mark_stack->IsEmpty());
922 new_tl_mark_stack->PushBack(to_ref);
923 self->SetThreadLocalMarkStack(new_tl_mark_stack);
924 if (tl_mark_stack != nullptr) {
925 // Store the old full stack into a vector.
926 revoked_mark_stacks_.push_back(tl_mark_stack);
927 }
928 } else {
929 tl_mark_stack->PushBack(to_ref);
930 }
931 }
932 } else if (mark_stack_mode == kMarkStackModeShared) {
933 // Access the shared GC mark stack with a lock.
934 MutexLock mu(self, mark_stack_lock_);
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -0700935 if (UNLIKELY(gc_mark_stack_->IsFull())) {
936 ExpandGcMarkStack();
937 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700938 gc_mark_stack_->PushBack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800939 } else {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700940 CHECK_EQ(static_cast<uint32_t>(mark_stack_mode),
Hiroshi Yamauchifa755182015-09-30 20:12:11 -0700941 static_cast<uint32_t>(kMarkStackModeGcExclusive))
942 << "ref=" << to_ref
943 << " self->gc_marking=" << self->GetIsGcMarking()
944 << " cc->is_marking=" << is_marking_;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700945 CHECK(self == thread_running_gc_)
946 << "Only GC-running thread should access the mark stack "
947 << "in the GC exclusive mark stack mode";
948 // Access the GC mark stack without a lock.
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -0700949 if (UNLIKELY(gc_mark_stack_->IsFull())) {
950 ExpandGcMarkStack();
951 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700952 gc_mark_stack_->PushBack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800953 }
954}
955
956accounting::ObjectStack* ConcurrentCopying::GetAllocationStack() {
957 return heap_->allocation_stack_.get();
958}
959
960accounting::ObjectStack* ConcurrentCopying::GetLiveStack() {
961 return heap_->live_stack_.get();
962}
963
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800964// The following visitors are used to verify that there's no references to the from-space left after
965// marking.
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700966class ConcurrentCopying::VerifyNoFromSpaceRefsVisitor : public SingleRootVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800967 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700968 explicit VerifyNoFromSpaceRefsVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800969 : collector_(collector) {}
970
971 void operator()(mirror::Object* ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700972 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800973 if (ref == nullptr) {
974 // OK.
975 return;
976 }
977 collector_->AssertToSpaceInvariant(nullptr, MemberOffset(0), ref);
978 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700979 CHECK_EQ(ref->GetReadBarrierState(), ReadBarrier::WhiteState())
David Sehr709b0702016-10-13 09:12:37 -0700980 << "Ref " << ref << " " << ref->PrettyTypeOf()
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700981 << " has non-white rb_state ";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800982 }
983 }
984
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700985 void VisitRoot(mirror::Object* root, const RootInfo& info ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700986 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800987 DCHECK(root != nullptr);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700988 operator()(root);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800989 }
990
991 private:
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700992 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800993};
994
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700995class ConcurrentCopying::VerifyNoFromSpaceRefsFieldVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800996 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700997 explicit VerifyNoFromSpaceRefsFieldVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800998 : collector_(collector) {}
999
Mathieu Chartier31e88222016-10-14 18:43:19 -07001000 void operator()(ObjPtr<mirror::Object> obj,
1001 MemberOffset offset,
1002 bool is_static ATTRIBUTE_UNUSED) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001003 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001004 mirror::Object* ref =
1005 obj->GetFieldObject<mirror::Object, kDefaultVerifyFlags, kWithoutReadBarrier>(offset);
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001006 VerifyNoFromSpaceRefsVisitor visitor(collector_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001007 visitor(ref);
1008 }
Mathieu Chartier31e88222016-10-14 18:43:19 -07001009 void operator()(ObjPtr<mirror::Class> klass,
1010 ObjPtr<mirror::Reference> ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001011 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001012 CHECK(klass->IsTypeOfReferenceClass());
1013 this->operator()(ref, mirror::Reference::ReferentOffset(), false);
1014 }
1015
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001016 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001017 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001018 if (!root->IsNull()) {
1019 VisitRoot(root);
1020 }
1021 }
1022
1023 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001024 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001025 VerifyNoFromSpaceRefsVisitor visitor(collector_);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001026 visitor(root->AsMirrorPtr());
1027 }
1028
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001029 private:
Mathieu Chartier97509952015-07-13 14:35:43 -07001030 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001031};
1032
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001033class ConcurrentCopying::VerifyNoFromSpaceRefsObjectVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001034 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001035 explicit VerifyNoFromSpaceRefsObjectVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001036 : collector_(collector) {}
1037 void operator()(mirror::Object* obj) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001038 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001039 ObjectCallback(obj, collector_);
1040 }
1041 static void ObjectCallback(mirror::Object* obj, void *arg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001042 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001043 CHECK(obj != nullptr);
1044 ConcurrentCopying* collector = reinterpret_cast<ConcurrentCopying*>(arg);
1045 space::RegionSpace* region_space = collector->RegionSpace();
1046 CHECK(!region_space->IsInFromSpace(obj)) << "Scanning object " << obj << " in from space";
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001047 VerifyNoFromSpaceRefsFieldVisitor visitor(collector);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07001048 obj->VisitReferences(visitor, visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001049 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001050 CHECK_EQ(obj->GetReadBarrierState(), ReadBarrier::WhiteState())
1051 << "obj=" << obj << " non-white rb_state " << obj->GetReadBarrierState();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001052 }
1053 }
1054
1055 private:
1056 ConcurrentCopying* const collector_;
1057};
1058
1059// Verify there's no from-space references left after the marking phase.
1060void ConcurrentCopying::VerifyNoFromSpaceReferences() {
1061 Thread* self = Thread::Current();
1062 DCHECK(Locks::mutator_lock_->IsExclusiveHeld(self));
Hiroshi Yamauchi00370822015-08-18 14:47:25 -07001063 // Verify all threads have is_gc_marking to be false
1064 {
1065 MutexLock mu(self, *Locks::thread_list_lock_);
1066 std::list<Thread*> thread_list = Runtime::Current()->GetThreadList()->GetList();
1067 for (Thread* thread : thread_list) {
1068 CHECK(!thread->GetIsGcMarking());
1069 }
1070 }
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001071 VerifyNoFromSpaceRefsObjectVisitor visitor(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001072 // Roots.
1073 {
1074 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001075 VerifyNoFromSpaceRefsVisitor ref_visitor(this);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001076 Runtime::Current()->VisitRoots(&ref_visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001077 }
1078 // The to-space.
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001079 region_space_->WalkToSpace(VerifyNoFromSpaceRefsObjectVisitor::ObjectCallback, this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001080 // Non-moving spaces.
1081 {
1082 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1083 heap_->GetMarkBitmap()->Visit(visitor);
1084 }
1085 // The alloc stack.
1086 {
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001087 VerifyNoFromSpaceRefsVisitor ref_visitor(this);
Mathieu Chartiercb535da2015-01-23 13:50:03 -08001088 for (auto* it = heap_->allocation_stack_->Begin(), *end = heap_->allocation_stack_->End();
1089 it < end; ++it) {
1090 mirror::Object* const obj = it->AsMirrorPtr();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001091 if (obj != nullptr && obj->GetClass() != nullptr) {
1092 // TODO: need to call this only if obj is alive?
1093 ref_visitor(obj);
1094 visitor(obj);
1095 }
1096 }
1097 }
1098 // TODO: LOS. But only refs in LOS are classes.
1099}
1100
1101// The following visitors are used to assert the to-space invariant.
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001102class ConcurrentCopying::AssertToSpaceInvariantRefsVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001103 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001104 explicit AssertToSpaceInvariantRefsVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001105 : collector_(collector) {}
1106
1107 void operator()(mirror::Object* ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001108 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001109 if (ref == nullptr) {
1110 // OK.
1111 return;
1112 }
1113 collector_->AssertToSpaceInvariant(nullptr, MemberOffset(0), ref);
1114 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001115
1116 private:
Mathieu Chartier97509952015-07-13 14:35:43 -07001117 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001118};
1119
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001120class ConcurrentCopying::AssertToSpaceInvariantFieldVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001121 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001122 explicit AssertToSpaceInvariantFieldVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001123 : collector_(collector) {}
1124
Mathieu Chartier31e88222016-10-14 18:43:19 -07001125 void operator()(ObjPtr<mirror::Object> obj,
1126 MemberOffset offset,
1127 bool is_static ATTRIBUTE_UNUSED) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001128 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001129 mirror::Object* ref =
1130 obj->GetFieldObject<mirror::Object, kDefaultVerifyFlags, kWithoutReadBarrier>(offset);
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001131 AssertToSpaceInvariantRefsVisitor visitor(collector_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001132 visitor(ref);
1133 }
Mathieu Chartier31e88222016-10-14 18:43:19 -07001134 void operator()(ObjPtr<mirror::Class> klass, ObjPtr<mirror::Reference> ref ATTRIBUTE_UNUSED) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001135 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001136 CHECK(klass->IsTypeOfReferenceClass());
1137 }
1138
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001139 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001140 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001141 if (!root->IsNull()) {
1142 VisitRoot(root);
1143 }
1144 }
1145
1146 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001147 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001148 AssertToSpaceInvariantRefsVisitor visitor(collector_);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001149 visitor(root->AsMirrorPtr());
1150 }
1151
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001152 private:
Mathieu Chartier97509952015-07-13 14:35:43 -07001153 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001154};
1155
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001156class ConcurrentCopying::AssertToSpaceInvariantObjectVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001157 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001158 explicit AssertToSpaceInvariantObjectVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001159 : collector_(collector) {}
1160 void operator()(mirror::Object* obj) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001161 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001162 ObjectCallback(obj, collector_);
1163 }
1164 static void ObjectCallback(mirror::Object* obj, void *arg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001165 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001166 CHECK(obj != nullptr);
1167 ConcurrentCopying* collector = reinterpret_cast<ConcurrentCopying*>(arg);
1168 space::RegionSpace* region_space = collector->RegionSpace();
1169 CHECK(!region_space->IsInFromSpace(obj)) << "Scanning object " << obj << " in from space";
1170 collector->AssertToSpaceInvariant(nullptr, MemberOffset(0), obj);
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001171 AssertToSpaceInvariantFieldVisitor visitor(collector);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07001172 obj->VisitReferences(visitor, visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001173 }
1174
1175 private:
Mathieu Chartier97509952015-07-13 14:35:43 -07001176 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001177};
1178
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001179class ConcurrentCopying::RevokeThreadLocalMarkStackCheckpoint : public Closure {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001180 public:
Roland Levillain3887c462015-08-12 18:15:42 +01001181 RevokeThreadLocalMarkStackCheckpoint(ConcurrentCopying* concurrent_copying,
1182 bool disable_weak_ref_access)
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001183 : concurrent_copying_(concurrent_copying),
1184 disable_weak_ref_access_(disable_weak_ref_access) {
1185 }
1186
1187 virtual void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
1188 // Note: self is not necessarily equal to thread since thread may be suspended.
1189 Thread* self = Thread::Current();
1190 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
1191 << thread->GetState() << " thread " << thread << " self " << self;
1192 // Revoke thread local mark stacks.
1193 accounting::AtomicStack<mirror::Object>* tl_mark_stack = thread->GetThreadLocalMarkStack();
1194 if (tl_mark_stack != nullptr) {
1195 MutexLock mu(self, concurrent_copying_->mark_stack_lock_);
1196 concurrent_copying_->revoked_mark_stacks_.push_back(tl_mark_stack);
1197 thread->SetThreadLocalMarkStack(nullptr);
1198 }
1199 // Disable weak ref access.
1200 if (disable_weak_ref_access_) {
1201 thread->SetWeakRefAccessEnabled(false);
1202 }
1203 // If thread is a running mutator, then act on behalf of the garbage collector.
1204 // See the code in ThreadList::RunCheckpoint.
Mathieu Chartier10d25082015-10-28 18:36:09 -07001205 concurrent_copying_->GetBarrier().Pass(self);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001206 }
1207
1208 private:
1209 ConcurrentCopying* const concurrent_copying_;
1210 const bool disable_weak_ref_access_;
1211};
1212
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001213void ConcurrentCopying::RevokeThreadLocalMarkStacks(bool disable_weak_ref_access,
1214 Closure* checkpoint_callback) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001215 Thread* self = Thread::Current();
1216 RevokeThreadLocalMarkStackCheckpoint check_point(this, disable_weak_ref_access);
1217 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1218 gc_barrier_->Init(self, 0);
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001219 size_t barrier_count = thread_list->RunCheckpoint(&check_point, checkpoint_callback);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001220 // If there are no threads to wait which implys that all the checkpoint functions are finished,
1221 // then no need to release the mutator lock.
1222 if (barrier_count == 0) {
1223 return;
1224 }
1225 Locks::mutator_lock_->SharedUnlock(self);
1226 {
1227 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
1228 gc_barrier_->Increment(self, barrier_count);
1229 }
1230 Locks::mutator_lock_->SharedLock(self);
1231}
1232
1233void ConcurrentCopying::RevokeThreadLocalMarkStack(Thread* thread) {
1234 Thread* self = Thread::Current();
1235 CHECK_EQ(self, thread);
1236 accounting::AtomicStack<mirror::Object>* tl_mark_stack = thread->GetThreadLocalMarkStack();
1237 if (tl_mark_stack != nullptr) {
1238 CHECK(is_marking_);
1239 MutexLock mu(self, mark_stack_lock_);
1240 revoked_mark_stacks_.push_back(tl_mark_stack);
1241 thread->SetThreadLocalMarkStack(nullptr);
1242 }
1243}
1244
1245void ConcurrentCopying::ProcessMarkStack() {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001246 if (kVerboseMode) {
1247 LOG(INFO) << "ProcessMarkStack. ";
1248 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001249 bool empty_prev = false;
1250 while (true) {
1251 bool empty = ProcessMarkStackOnce();
1252 if (empty_prev && empty) {
1253 // Saw empty mark stack for a second time, done.
1254 break;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001255 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001256 empty_prev = empty;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001257 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001258}
1259
1260bool ConcurrentCopying::ProcessMarkStackOnce() {
1261 Thread* self = Thread::Current();
1262 CHECK(thread_running_gc_ != nullptr);
1263 CHECK(self == thread_running_gc_);
1264 CHECK(self->GetThreadLocalMarkStack() == nullptr);
1265 size_t count = 0;
1266 MarkStackMode mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1267 if (mark_stack_mode == kMarkStackModeThreadLocal) {
1268 // Process the thread-local mark stacks and the GC mark stack.
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001269 count += ProcessThreadLocalMarkStacks(false, nullptr);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001270 while (!gc_mark_stack_->IsEmpty()) {
1271 mirror::Object* to_ref = gc_mark_stack_->PopBack();
1272 ProcessMarkStackRef(to_ref);
1273 ++count;
1274 }
1275 gc_mark_stack_->Reset();
1276 } else if (mark_stack_mode == kMarkStackModeShared) {
Hiroshi Yamauchi30493242016-11-03 13:06:52 -07001277 // Do an empty checkpoint to avoid a race with a mutator preempted in the middle of a read
1278 // barrier but before pushing onto the mark stack. b/32508093. Note the weak ref access is
1279 // disabled at this point.
1280 IssueEmptyCheckpoint();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001281 // Process the shared GC mark stack with a lock.
1282 {
1283 MutexLock mu(self, mark_stack_lock_);
1284 CHECK(revoked_mark_stacks_.empty());
1285 }
1286 while (true) {
1287 std::vector<mirror::Object*> refs;
1288 {
1289 // Copy refs with lock. Note the number of refs should be small.
1290 MutexLock mu(self, mark_stack_lock_);
1291 if (gc_mark_stack_->IsEmpty()) {
1292 break;
1293 }
1294 for (StackReference<mirror::Object>* p = gc_mark_stack_->Begin();
1295 p != gc_mark_stack_->End(); ++p) {
1296 refs.push_back(p->AsMirrorPtr());
1297 }
1298 gc_mark_stack_->Reset();
1299 }
1300 for (mirror::Object* ref : refs) {
1301 ProcessMarkStackRef(ref);
1302 ++count;
1303 }
1304 }
1305 } else {
1306 CHECK_EQ(static_cast<uint32_t>(mark_stack_mode),
1307 static_cast<uint32_t>(kMarkStackModeGcExclusive));
1308 {
1309 MutexLock mu(self, mark_stack_lock_);
1310 CHECK(revoked_mark_stacks_.empty());
1311 }
1312 // Process the GC mark stack in the exclusive mode. No need to take the lock.
1313 while (!gc_mark_stack_->IsEmpty()) {
1314 mirror::Object* to_ref = gc_mark_stack_->PopBack();
1315 ProcessMarkStackRef(to_ref);
1316 ++count;
1317 }
1318 gc_mark_stack_->Reset();
1319 }
1320
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001321 // Return true if the stack was empty.
1322 return count == 0;
1323}
1324
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001325size_t ConcurrentCopying::ProcessThreadLocalMarkStacks(bool disable_weak_ref_access,
1326 Closure* checkpoint_callback) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001327 // Run a checkpoint to collect all thread local mark stacks and iterate over them all.
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001328 RevokeThreadLocalMarkStacks(disable_weak_ref_access, checkpoint_callback);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001329 size_t count = 0;
1330 std::vector<accounting::AtomicStack<mirror::Object>*> mark_stacks;
1331 {
1332 MutexLock mu(Thread::Current(), mark_stack_lock_);
1333 // Make a copy of the mark stack vector.
1334 mark_stacks = revoked_mark_stacks_;
1335 revoked_mark_stacks_.clear();
1336 }
1337 for (accounting::AtomicStack<mirror::Object>* mark_stack : mark_stacks) {
1338 for (StackReference<mirror::Object>* p = mark_stack->Begin(); p != mark_stack->End(); ++p) {
1339 mirror::Object* to_ref = p->AsMirrorPtr();
1340 ProcessMarkStackRef(to_ref);
1341 ++count;
1342 }
1343 {
1344 MutexLock mu(Thread::Current(), mark_stack_lock_);
1345 if (pooled_mark_stacks_.size() >= kMarkStackPoolSize) {
1346 // The pool has enough. Delete it.
1347 delete mark_stack;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001348 } else {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001349 // Otherwise, put it into the pool for later reuse.
1350 mark_stack->Reset();
1351 pooled_mark_stacks_.push_back(mark_stack);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001352 }
1353 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001354 }
1355 return count;
1356}
1357
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001358inline void ConcurrentCopying::ProcessMarkStackRef(mirror::Object* to_ref) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001359 DCHECK(!region_space_->IsInFromSpace(to_ref));
1360 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001361 DCHECK(to_ref->GetReadBarrierState() == ReadBarrier::GrayState())
1362 << " " << to_ref << " " << to_ref->GetReadBarrierState()
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001363 << " is_marked=" << IsMarked(to_ref);
1364 }
Mathieu Chartierc381c362016-08-23 13:27:53 -07001365 bool add_to_live_bytes = false;
1366 if (region_space_->IsInUnevacFromSpace(to_ref)) {
1367 // Mark the bitmap only in the GC thread here so that we don't need a CAS.
1368 if (!kUseBakerReadBarrier || !region_space_bitmap_->Set(to_ref)) {
1369 // It may be already marked if we accidentally pushed the same object twice due to the racy
1370 // bitmap read in MarkUnevacFromSpaceRegion.
1371 Scan(to_ref);
1372 // Only add to the live bytes if the object was not already marked.
1373 add_to_live_bytes = true;
1374 }
1375 } else {
1376 Scan(to_ref);
1377 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001378 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001379 DCHECK(to_ref->GetReadBarrierState() == ReadBarrier::GrayState())
1380 << " " << to_ref << " " << to_ref->GetReadBarrierState()
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001381 << " is_marked=" << IsMarked(to_ref);
1382 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001383#ifdef USE_BAKER_OR_BROOKS_READ_BARRIER
Hiroshi Yamauchi39c12d42016-12-06 16:46:37 -08001384 mirror::Object* referent = nullptr;
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001385 if (UNLIKELY((to_ref->GetClass<kVerifyNone, kWithoutReadBarrier>()->IsTypeOfReferenceClass() &&
Hiroshi Yamauchi39c12d42016-12-06 16:46:37 -08001386 (referent = to_ref->AsReference()->GetReferent<kWithoutReadBarrier>()) != nullptr &&
1387 !IsInToSpace(referent)))) {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001388 // Leave this reference gray in the queue so that GetReferent() will trigger a read barrier. We
1389 // will change it to white later in ReferenceQueue::DequeuePendingReference().
Richard Uhlere3627402016-02-02 13:36:55 -08001390 DCHECK(to_ref->AsReference()->GetPendingNext() != nullptr) << "Left unenqueued ref gray " << to_ref;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001391 } else {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001392 // We may occasionally leave a reference white in the queue if its referent happens to be
1393 // concurrently marked after the Scan() call above has enqueued the Reference, in which case the
1394 // above IsInToSpace() evaluates to true and we change the color from gray to white here in this
1395 // else block.
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001396 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001397 bool success = to_ref->AtomicSetReadBarrierState</*kCasRelease*/true>(
1398 ReadBarrier::GrayState(),
1399 ReadBarrier::WhiteState());
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001400 DCHECK(success) << "Must succeed as we won the race.";
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001401 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001402 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001403#else
1404 DCHECK(!kUseBakerReadBarrier);
1405#endif
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001406
Mathieu Chartierc381c362016-08-23 13:27:53 -07001407 if (add_to_live_bytes) {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001408 // Add to the live bytes per unevacuated from space. Note this code is always run by the
1409 // GC-running thread (no synchronization required).
1410 DCHECK(region_space_bitmap_->Test(to_ref));
1411 // Disable the read barrier in SizeOf for performance, which is safe.
1412 size_t obj_size = to_ref->SizeOf<kDefaultVerifyFlags, kWithoutReadBarrier>();
1413 size_t alloc_size = RoundUp(obj_size, space::RegionSpace::kAlignment);
1414 region_space_->AddLiveBytes(to_ref, alloc_size);
1415 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001416 if (ReadBarrier::kEnableToSpaceInvariantChecks || kIsDebugBuild) {
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001417 AssertToSpaceInvariantObjectVisitor visitor(this);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001418 visitor(to_ref);
1419 }
1420}
1421
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001422class ConcurrentCopying::DisableWeakRefAccessCallback : public Closure {
1423 public:
1424 explicit DisableWeakRefAccessCallback(ConcurrentCopying* concurrent_copying)
1425 : concurrent_copying_(concurrent_copying) {
1426 }
1427
1428 void Run(Thread* self ATTRIBUTE_UNUSED) OVERRIDE REQUIRES(Locks::thread_list_lock_) {
1429 // This needs to run under the thread_list_lock_ critical section in ThreadList::RunCheckpoint()
1430 // to avoid a deadlock b/31500969.
1431 CHECK(concurrent_copying_->weak_ref_access_enabled_);
1432 concurrent_copying_->weak_ref_access_enabled_ = false;
1433 }
1434
1435 private:
1436 ConcurrentCopying* const concurrent_copying_;
1437};
1438
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001439void ConcurrentCopying::SwitchToSharedMarkStackMode() {
1440 Thread* self = Thread::Current();
1441 CHECK(thread_running_gc_ != nullptr);
1442 CHECK_EQ(self, thread_running_gc_);
1443 CHECK(self->GetThreadLocalMarkStack() == nullptr);
1444 MarkStackMode before_mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1445 CHECK_EQ(static_cast<uint32_t>(before_mark_stack_mode),
1446 static_cast<uint32_t>(kMarkStackModeThreadLocal));
1447 mark_stack_mode_.StoreRelaxed(kMarkStackModeShared);
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001448 DisableWeakRefAccessCallback dwrac(this);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001449 // Process the thread local mark stacks one last time after switching to the shared mark stack
1450 // mode and disable weak ref accesses.
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001451 ProcessThreadLocalMarkStacks(true, &dwrac);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001452 if (kVerboseMode) {
1453 LOG(INFO) << "Switched to shared mark stack mode and disabled weak ref access";
1454 }
1455}
1456
1457void ConcurrentCopying::SwitchToGcExclusiveMarkStackMode() {
1458 Thread* self = Thread::Current();
1459 CHECK(thread_running_gc_ != nullptr);
1460 CHECK_EQ(self, thread_running_gc_);
1461 CHECK(self->GetThreadLocalMarkStack() == nullptr);
1462 MarkStackMode before_mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1463 CHECK_EQ(static_cast<uint32_t>(before_mark_stack_mode),
1464 static_cast<uint32_t>(kMarkStackModeShared));
1465 mark_stack_mode_.StoreRelaxed(kMarkStackModeGcExclusive);
1466 QuasiAtomic::ThreadFenceForConstructor();
1467 if (kVerboseMode) {
1468 LOG(INFO) << "Switched to GC exclusive mark stack mode";
1469 }
1470}
1471
1472void ConcurrentCopying::CheckEmptyMarkStack() {
1473 Thread* self = Thread::Current();
1474 CHECK(thread_running_gc_ != nullptr);
1475 CHECK_EQ(self, thread_running_gc_);
1476 CHECK(self->GetThreadLocalMarkStack() == nullptr);
1477 MarkStackMode mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1478 if (mark_stack_mode == kMarkStackModeThreadLocal) {
1479 // Thread-local mark stack mode.
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001480 RevokeThreadLocalMarkStacks(false, nullptr);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001481 MutexLock mu(Thread::Current(), mark_stack_lock_);
1482 if (!revoked_mark_stacks_.empty()) {
1483 for (accounting::AtomicStack<mirror::Object>* mark_stack : revoked_mark_stacks_) {
1484 while (!mark_stack->IsEmpty()) {
1485 mirror::Object* obj = mark_stack->PopBack();
1486 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001487 uint32_t rb_state = obj->GetReadBarrierState();
1488 LOG(INFO) << "On mark queue : " << obj << " " << obj->PrettyTypeOf() << " rb_state="
1489 << rb_state << " is_marked=" << IsMarked(obj);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001490 } else {
David Sehr709b0702016-10-13 09:12:37 -07001491 LOG(INFO) << "On mark queue : " << obj << " " << obj->PrettyTypeOf()
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001492 << " is_marked=" << IsMarked(obj);
1493 }
1494 }
1495 }
1496 LOG(FATAL) << "mark stack is not empty";
1497 }
1498 } else {
1499 // Shared, GC-exclusive, or off.
1500 MutexLock mu(Thread::Current(), mark_stack_lock_);
1501 CHECK(gc_mark_stack_->IsEmpty());
1502 CHECK(revoked_mark_stacks_.empty());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001503 }
1504}
1505
1506void ConcurrentCopying::SweepSystemWeaks(Thread* self) {
1507 TimingLogger::ScopedTiming split("SweepSystemWeaks", GetTimings());
1508 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier97509952015-07-13 14:35:43 -07001509 Runtime::Current()->SweepSystemWeaks(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001510}
1511
1512void ConcurrentCopying::Sweep(bool swap_bitmaps) {
1513 {
1514 TimingLogger::ScopedTiming t("MarkStackAsLive", GetTimings());
1515 accounting::ObjectStack* live_stack = heap_->GetLiveStack();
1516 if (kEnableFromSpaceAccountingCheck) {
1517 CHECK_GE(live_stack_freeze_size_, live_stack->Size());
1518 }
1519 heap_->MarkAllocStackAsLive(live_stack);
1520 live_stack->Reset();
1521 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001522 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001523 TimingLogger::ScopedTiming split("Sweep", GetTimings());
1524 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
1525 if (space->IsContinuousMemMapAllocSpace()) {
1526 space::ContinuousMemMapAllocSpace* alloc_space = space->AsContinuousMemMapAllocSpace();
Mathieu Chartier763a31e2015-11-16 16:05:55 -08001527 if (space == region_space_ || immune_spaces_.ContainsSpace(space)) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001528 continue;
1529 }
1530 TimingLogger::ScopedTiming split2(
1531 alloc_space->IsZygoteSpace() ? "SweepZygoteSpace" : "SweepAllocSpace", GetTimings());
1532 RecordFree(alloc_space->Sweep(swap_bitmaps));
1533 }
1534 }
1535 SweepLargeObjects(swap_bitmaps);
1536}
1537
Mathieu Chartier962cd7a2016-08-16 12:15:59 -07001538void ConcurrentCopying::MarkZygoteLargeObjects() {
1539 TimingLogger::ScopedTiming split(__FUNCTION__, GetTimings());
1540 Thread* const self = Thread::Current();
1541 WriterMutexLock rmu(self, *Locks::heap_bitmap_lock_);
1542 space::LargeObjectSpace* const los = heap_->GetLargeObjectsSpace();
1543 // Pick the current live bitmap (mark bitmap if swapped).
1544 accounting::LargeObjectBitmap* const live_bitmap = los->GetLiveBitmap();
1545 accounting::LargeObjectBitmap* const mark_bitmap = los->GetMarkBitmap();
1546 // Walk through all of the objects and explicitly mark the zygote ones so they don't get swept.
Mathieu Chartier208aaf02016-10-25 10:45:08 -07001547 std::pair<uint8_t*, uint8_t*> range = los->GetBeginEndAtomic();
1548 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(range.first),
1549 reinterpret_cast<uintptr_t>(range.second),
Mathieu Chartier962cd7a2016-08-16 12:15:59 -07001550 [mark_bitmap, los, self](mirror::Object* obj)
1551 REQUIRES(Locks::heap_bitmap_lock_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001552 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier962cd7a2016-08-16 12:15:59 -07001553 if (los->IsZygoteLargeObject(self, obj)) {
1554 mark_bitmap->Set(obj);
1555 }
1556 });
1557}
1558
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001559void ConcurrentCopying::SweepLargeObjects(bool swap_bitmaps) {
1560 TimingLogger::ScopedTiming split("SweepLargeObjects", GetTimings());
1561 RecordFreeLOS(heap_->GetLargeObjectsSpace()->Sweep(swap_bitmaps));
1562}
1563
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001564void ConcurrentCopying::ReclaimPhase() {
1565 TimingLogger::ScopedTiming split("ReclaimPhase", GetTimings());
1566 if (kVerboseMode) {
1567 LOG(INFO) << "GC ReclaimPhase";
1568 }
1569 Thread* self = Thread::Current();
1570
1571 {
1572 // Double-check that the mark stack is empty.
1573 // Note: need to set this after VerifyNoFromSpaceRef().
1574 is_asserting_to_space_invariant_ = false;
1575 QuasiAtomic::ThreadFenceForConstructor();
1576 if (kVerboseMode) {
1577 LOG(INFO) << "Issue an empty check point. ";
1578 }
1579 IssueEmptyCheckpoint();
1580 // Disable the check.
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001581 is_mark_stack_push_disallowed_.StoreSequentiallyConsistent(0);
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001582 if (kUseBakerReadBarrier) {
1583 updated_all_immune_objects_.StoreSequentiallyConsistent(false);
1584 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001585 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001586 }
1587
1588 {
1589 // Record freed objects.
1590 TimingLogger::ScopedTiming split2("RecordFree", GetTimings());
1591 // Don't include thread-locals that are in the to-space.
1592 uint64_t from_bytes = region_space_->GetBytesAllocatedInFromSpace();
1593 uint64_t from_objects = region_space_->GetObjectsAllocatedInFromSpace();
1594 uint64_t unevac_from_bytes = region_space_->GetBytesAllocatedInUnevacFromSpace();
1595 uint64_t unevac_from_objects = region_space_->GetObjectsAllocatedInUnevacFromSpace();
1596 uint64_t to_bytes = bytes_moved_.LoadSequentiallyConsistent();
Mathieu Chartiercca44a02016-08-17 10:07:29 -07001597 cumulative_bytes_moved_.FetchAndAddRelaxed(to_bytes);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001598 uint64_t to_objects = objects_moved_.LoadSequentiallyConsistent();
Mathieu Chartiercca44a02016-08-17 10:07:29 -07001599 cumulative_objects_moved_.FetchAndAddRelaxed(to_objects);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001600 if (kEnableFromSpaceAccountingCheck) {
1601 CHECK_EQ(from_space_num_objects_at_first_pause_, from_objects + unevac_from_objects);
1602 CHECK_EQ(from_space_num_bytes_at_first_pause_, from_bytes + unevac_from_bytes);
1603 }
1604 CHECK_LE(to_objects, from_objects);
1605 CHECK_LE(to_bytes, from_bytes);
1606 int64_t freed_bytes = from_bytes - to_bytes;
1607 int64_t freed_objects = from_objects - to_objects;
1608 if (kVerboseMode) {
1609 LOG(INFO) << "RecordFree:"
1610 << " from_bytes=" << from_bytes << " from_objects=" << from_objects
1611 << " unevac_from_bytes=" << unevac_from_bytes << " unevac_from_objects=" << unevac_from_objects
1612 << " to_bytes=" << to_bytes << " to_objects=" << to_objects
1613 << " freed_bytes=" << freed_bytes << " freed_objects=" << freed_objects
1614 << " from_space size=" << region_space_->FromSpaceSize()
1615 << " unevac_from_space size=" << region_space_->UnevacFromSpaceSize()
1616 << " to_space size=" << region_space_->ToSpaceSize();
1617 LOG(INFO) << "(before) num_bytes_allocated=" << heap_->num_bytes_allocated_.LoadSequentiallyConsistent();
1618 }
1619 RecordFree(ObjectBytePair(freed_objects, freed_bytes));
1620 if (kVerboseMode) {
1621 LOG(INFO) << "(after) num_bytes_allocated=" << heap_->num_bytes_allocated_.LoadSequentiallyConsistent();
1622 }
1623 }
1624
1625 {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001626 TimingLogger::ScopedTiming split4("ClearFromSpace", GetTimings());
1627 region_space_->ClearFromSpace();
1628 }
1629
1630 {
1631 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001632 Sweep(false);
1633 SwapBitmaps();
1634 heap_->UnBindBitmaps();
1635
Mathieu Chartier7ec38dc2016-10-07 15:24:46 -07001636 // The bitmap was cleared at the start of the GC, there is nothing we need to do here.
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001637 DCHECK(region_space_bitmap_ != nullptr);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001638 region_space_bitmap_ = nullptr;
1639 }
1640
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001641 CheckEmptyMarkStack();
1642
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001643 if (kVerboseMode) {
1644 LOG(INFO) << "GC end of ReclaimPhase";
1645 }
1646}
1647
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001648// Assert the to-space invariant.
1649void ConcurrentCopying::AssertToSpaceInvariant(mirror::Object* obj, MemberOffset offset,
1650 mirror::Object* ref) {
1651 CHECK(heap_->collector_type_ == kCollectorTypeCC) << static_cast<size_t>(heap_->collector_type_);
1652 if (is_asserting_to_space_invariant_) {
1653 if (region_space_->IsInToSpace(ref)) {
1654 // OK.
1655 return;
1656 } else if (region_space_->IsInUnevacFromSpace(ref)) {
Mathieu Chartierc381c362016-08-23 13:27:53 -07001657 CHECK(IsMarkedInUnevacFromSpace(ref)) << ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001658 } else if (region_space_->IsInFromSpace(ref)) {
1659 // Not OK. Do extra logging.
1660 if (obj != nullptr) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001661 LogFromSpaceRefHolder(obj, offset);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001662 }
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07001663 ref->GetLockWord(false).Dump(LOG_STREAM(FATAL_WITHOUT_ABORT));
David Sehr709b0702016-10-13 09:12:37 -07001664 CHECK(false) << "Found from-space ref " << ref << " " << ref->PrettyTypeOf();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001665 } else {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001666 AssertToSpaceInvariantInNonMovingSpace(obj, ref);
1667 }
1668 }
1669}
1670
1671class RootPrinter {
1672 public:
1673 RootPrinter() { }
1674
1675 template <class MirrorType>
1676 ALWAYS_INLINE void VisitRootIfNonNull(mirror::CompressedReference<MirrorType>* root)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001677 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001678 if (!root->IsNull()) {
1679 VisitRoot(root);
1680 }
1681 }
1682
1683 template <class MirrorType>
1684 void VisitRoot(mirror::Object** root)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001685 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07001686 LOG(FATAL_WITHOUT_ABORT) << "root=" << root << " ref=" << *root;
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001687 }
1688
1689 template <class MirrorType>
1690 void VisitRoot(mirror::CompressedReference<MirrorType>* root)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001691 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07001692 LOG(FATAL_WITHOUT_ABORT) << "root=" << root << " ref=" << root->AsMirrorPtr();
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001693 }
1694};
1695
1696void ConcurrentCopying::AssertToSpaceInvariant(GcRootSource* gc_root_source,
1697 mirror::Object* ref) {
1698 CHECK(heap_->collector_type_ == kCollectorTypeCC) << static_cast<size_t>(heap_->collector_type_);
1699 if (is_asserting_to_space_invariant_) {
1700 if (region_space_->IsInToSpace(ref)) {
1701 // OK.
1702 return;
1703 } else if (region_space_->IsInUnevacFromSpace(ref)) {
Mathieu Chartierc381c362016-08-23 13:27:53 -07001704 CHECK(IsMarkedInUnevacFromSpace(ref)) << ref;
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001705 } else if (region_space_->IsInFromSpace(ref)) {
1706 // Not OK. Do extra logging.
1707 if (gc_root_source == nullptr) {
1708 // No info.
1709 } else if (gc_root_source->HasArtField()) {
1710 ArtField* field = gc_root_source->GetArtField();
David Sehr709b0702016-10-13 09:12:37 -07001711 LOG(FATAL_WITHOUT_ABORT) << "gc root in field " << field << " "
1712 << ArtField::PrettyField(field);
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001713 RootPrinter root_printer;
1714 field->VisitRoots(root_printer);
1715 } else if (gc_root_source->HasArtMethod()) {
1716 ArtMethod* method = gc_root_source->GetArtMethod();
David Sehr709b0702016-10-13 09:12:37 -07001717 LOG(FATAL_WITHOUT_ABORT) << "gc root in method " << method << " "
1718 << ArtMethod::PrettyMethod(method);
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001719 RootPrinter root_printer;
Andreas Gampe542451c2016-07-26 09:02:02 -07001720 method->VisitRoots(root_printer, kRuntimePointerSize);
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001721 }
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07001722 ref->GetLockWord(false).Dump(LOG_STREAM(FATAL_WITHOUT_ABORT));
1723 region_space_->DumpNonFreeRegions(LOG_STREAM(FATAL_WITHOUT_ABORT));
1724 PrintFileToLog("/proc/self/maps", LogSeverity::FATAL_WITHOUT_ABORT);
1725 MemMap::DumpMaps(LOG_STREAM(FATAL_WITHOUT_ABORT), true);
David Sehr709b0702016-10-13 09:12:37 -07001726 CHECK(false) << "Found from-space ref " << ref << " " << ref->PrettyTypeOf();
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001727 } else {
1728 AssertToSpaceInvariantInNonMovingSpace(nullptr, ref);
1729 }
1730 }
1731}
1732
1733void ConcurrentCopying::LogFromSpaceRefHolder(mirror::Object* obj, MemberOffset offset) {
1734 if (kUseBakerReadBarrier) {
David Sehr709b0702016-10-13 09:12:37 -07001735 LOG(INFO) << "holder=" << obj << " " << obj->PrettyTypeOf()
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001736 << " holder rb_state=" << obj->GetReadBarrierState();
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001737 } else {
David Sehr709b0702016-10-13 09:12:37 -07001738 LOG(INFO) << "holder=" << obj << " " << obj->PrettyTypeOf();
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001739 }
1740 if (region_space_->IsInFromSpace(obj)) {
1741 LOG(INFO) << "holder is in the from-space.";
1742 } else if (region_space_->IsInToSpace(obj)) {
1743 LOG(INFO) << "holder is in the to-space.";
1744 } else if (region_space_->IsInUnevacFromSpace(obj)) {
1745 LOG(INFO) << "holder is in the unevac from-space.";
Mathieu Chartierc381c362016-08-23 13:27:53 -07001746 if (IsMarkedInUnevacFromSpace(obj)) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001747 LOG(INFO) << "holder is marked in the region space bitmap.";
1748 } else {
1749 LOG(INFO) << "holder is not marked in the region space bitmap.";
1750 }
1751 } else {
1752 // In a non-moving space.
Mathieu Chartier763a31e2015-11-16 16:05:55 -08001753 if (immune_spaces_.ContainsObject(obj)) {
1754 LOG(INFO) << "holder is in an immune image or the zygote space.";
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001755 } else {
Mathieu Chartier763a31e2015-11-16 16:05:55 -08001756 LOG(INFO) << "holder is in a non-immune, non-moving (or main) space.";
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001757 accounting::ContinuousSpaceBitmap* mark_bitmap =
1758 heap_mark_bitmap_->GetContinuousSpaceBitmap(obj);
1759 accounting::LargeObjectBitmap* los_bitmap =
1760 heap_mark_bitmap_->GetLargeObjectBitmap(obj);
1761 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
1762 bool is_los = mark_bitmap == nullptr;
1763 if (!is_los && mark_bitmap->Test(obj)) {
1764 LOG(INFO) << "holder is marked in the mark bit map.";
1765 } else if (is_los && los_bitmap->Test(obj)) {
1766 LOG(INFO) << "holder is marked in the los bit map.";
1767 } else {
1768 // If ref is on the allocation stack, then it is considered
1769 // mark/alive (but not necessarily on the live stack.)
1770 if (IsOnAllocStack(obj)) {
1771 LOG(INFO) << "holder is on the alloc stack.";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001772 } else {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001773 LOG(INFO) << "holder is not marked or on the alloc stack.";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001774 }
1775 }
1776 }
1777 }
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001778 LOG(INFO) << "offset=" << offset.SizeValue();
1779}
1780
1781void ConcurrentCopying::AssertToSpaceInvariantInNonMovingSpace(mirror::Object* obj,
1782 mirror::Object* ref) {
1783 // In a non-moving spaces. Check that the ref is marked.
Mathieu Chartier763a31e2015-11-16 16:05:55 -08001784 if (immune_spaces_.ContainsObject(ref)) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001785 if (kUseBakerReadBarrier) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001786 // Immune object may not be gray if called from the GC.
1787 if (Thread::Current() == thread_running_gc_ && !gc_grays_immune_objects_) {
1788 return;
1789 }
1790 bool updated_all_immune_objects = updated_all_immune_objects_.LoadSequentiallyConsistent();
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001791 CHECK(updated_all_immune_objects || ref->GetReadBarrierState() == ReadBarrier::GrayState())
1792 << "Unmarked immune space ref. obj=" << obj << " rb_state="
1793 << (obj != nullptr ? obj->GetReadBarrierState() : 0U)
1794 << " ref=" << ref << " ref rb_state=" << ref->GetReadBarrierState()
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001795 << " updated_all_immune_objects=" << updated_all_immune_objects;
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001796 }
1797 } else {
1798 accounting::ContinuousSpaceBitmap* mark_bitmap =
1799 heap_mark_bitmap_->GetContinuousSpaceBitmap(ref);
1800 accounting::LargeObjectBitmap* los_bitmap =
1801 heap_mark_bitmap_->GetLargeObjectBitmap(ref);
1802 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
1803 bool is_los = mark_bitmap == nullptr;
1804 if ((!is_los && mark_bitmap->Test(ref)) ||
1805 (is_los && los_bitmap->Test(ref))) {
1806 // OK.
1807 } else {
1808 // If ref is on the allocation stack, then it may not be
1809 // marked live, but considered marked/alive (but not
1810 // necessarily on the live stack).
1811 CHECK(IsOnAllocStack(ref)) << "Unmarked ref that's not on the allocation stack. "
1812 << "obj=" << obj << " ref=" << ref;
1813 }
1814 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001815}
1816
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001817// Used to scan ref fields of an object.
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001818class ConcurrentCopying::RefFieldsVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001819 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001820 explicit RefFieldsVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001821 : collector_(collector) {}
1822
Mathieu Chartier31e88222016-10-14 18:43:19 -07001823 void operator()(ObjPtr<mirror::Object> obj, MemberOffset offset, bool /* is_static */)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001824 const ALWAYS_INLINE REQUIRES_SHARED(Locks::mutator_lock_)
1825 REQUIRES_SHARED(Locks::heap_bitmap_lock_) {
Mathieu Chartier31e88222016-10-14 18:43:19 -07001826 collector_->Process(obj.Ptr(), offset);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001827 }
1828
Mathieu Chartier31e88222016-10-14 18:43:19 -07001829 void operator()(ObjPtr<mirror::Class> klass, ObjPtr<mirror::Reference> ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001830 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001831 CHECK(klass->IsTypeOfReferenceClass());
1832 collector_->DelayReferenceReferent(klass, ref);
1833 }
1834
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001835 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001836 ALWAYS_INLINE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001837 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001838 if (!root->IsNull()) {
1839 VisitRoot(root);
1840 }
1841 }
1842
1843 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001844 ALWAYS_INLINE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001845 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001846 collector_->MarkRoot</*kGrayImmuneObject*/false>(root);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001847 }
1848
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001849 private:
1850 ConcurrentCopying* const collector_;
1851};
1852
1853// Scan ref fields of an object.
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001854inline void ConcurrentCopying::Scan(mirror::Object* to_ref) {
Mathieu Chartierd6636d32016-07-28 11:02:38 -07001855 if (kDisallowReadBarrierDuringScan) {
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07001856 // Avoid all read barriers during visit references to help performance.
1857 Thread::Current()->ModifyDebugDisallowReadBarrier(1);
1858 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001859 DCHECK(!region_space_->IsInFromSpace(to_ref));
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001860 DCHECK_EQ(Thread::Current(), thread_running_gc_);
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001861 RefFieldsVisitor visitor(this);
Hiroshi Yamauchi5496f692016-02-17 13:29:59 -08001862 // Disable the read barrier for a performance reason.
1863 to_ref->VisitReferences</*kVisitNativeRoots*/true, kDefaultVerifyFlags, kWithoutReadBarrier>(
1864 visitor, visitor);
Mathieu Chartierd6636d32016-07-28 11:02:38 -07001865 if (kDisallowReadBarrierDuringScan) {
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07001866 Thread::Current()->ModifyDebugDisallowReadBarrier(-1);
1867 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001868}
1869
1870// Process a field.
1871inline void ConcurrentCopying::Process(mirror::Object* obj, MemberOffset offset) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001872 DCHECK_EQ(Thread::Current(), thread_running_gc_);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001873 mirror::Object* ref = obj->GetFieldObject<
1874 mirror::Object, kVerifyNone, kWithoutReadBarrier, false>(offset);
Mathieu Chartierc381c362016-08-23 13:27:53 -07001875 mirror::Object* to_ref = Mark</*kGrayImmuneObject*/false, /*kFromGCThread*/true>(ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001876 if (to_ref == ref) {
1877 return;
1878 }
1879 // This may fail if the mutator writes to the field at the same time. But it's ok.
1880 mirror::Object* expected_ref = ref;
1881 mirror::Object* new_ref = to_ref;
1882 do {
1883 if (expected_ref !=
1884 obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier, false>(offset)) {
1885 // It was updated by the mutator.
1886 break;
1887 }
Hiroshi Yamauchifed3e2f2015-10-20 11:11:56 -07001888 } while (!obj->CasFieldWeakRelaxedObjectWithoutWriteBarrier<
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001889 false, false, kVerifyNone>(offset, expected_ref, new_ref));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001890}
1891
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001892// Process some roots.
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001893inline void ConcurrentCopying::VisitRoots(
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001894 mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED) {
1895 for (size_t i = 0; i < count; ++i) {
1896 mirror::Object** root = roots[i];
1897 mirror::Object* ref = *root;
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001898 mirror::Object* to_ref = Mark(ref);
1899 if (to_ref == ref) {
Mathieu Chartier4809d0a2015-04-07 10:39:04 -07001900 continue;
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001901 }
1902 Atomic<mirror::Object*>* addr = reinterpret_cast<Atomic<mirror::Object*>*>(root);
1903 mirror::Object* expected_ref = ref;
1904 mirror::Object* new_ref = to_ref;
1905 do {
1906 if (expected_ref != addr->LoadRelaxed()) {
1907 // It was updated by the mutator.
1908 break;
1909 }
Hiroshi Yamauchifed3e2f2015-10-20 11:11:56 -07001910 } while (!addr->CompareExchangeWeakRelaxed(expected_ref, new_ref));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001911 }
1912}
1913
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001914template<bool kGrayImmuneObject>
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001915inline void ConcurrentCopying::MarkRoot(mirror::CompressedReference<mirror::Object>* root) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001916 DCHECK(!root->IsNull());
1917 mirror::Object* const ref = root->AsMirrorPtr();
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001918 mirror::Object* to_ref = Mark<kGrayImmuneObject>(ref);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001919 if (to_ref != ref) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001920 auto* addr = reinterpret_cast<Atomic<mirror::CompressedReference<mirror::Object>>*>(root);
1921 auto expected_ref = mirror::CompressedReference<mirror::Object>::FromMirrorPtr(ref);
1922 auto new_ref = mirror::CompressedReference<mirror::Object>::FromMirrorPtr(to_ref);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001923 // If the cas fails, then it was updated by the mutator.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001924 do {
1925 if (ref != addr->LoadRelaxed().AsMirrorPtr()) {
1926 // It was updated by the mutator.
1927 break;
1928 }
Hiroshi Yamauchifed3e2f2015-10-20 11:11:56 -07001929 } while (!addr->CompareExchangeWeakRelaxed(expected_ref, new_ref));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001930 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001931}
1932
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001933inline void ConcurrentCopying::VisitRoots(
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001934 mirror::CompressedReference<mirror::Object>** roots, size_t count,
1935 const RootInfo& info ATTRIBUTE_UNUSED) {
1936 for (size_t i = 0; i < count; ++i) {
1937 mirror::CompressedReference<mirror::Object>* const root = roots[i];
1938 if (!root->IsNull()) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001939 // kGrayImmuneObject is true because this is used for the thread flip.
1940 MarkRoot</*kGrayImmuneObject*/true>(root);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001941 }
1942 }
1943}
1944
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001945// Temporary set gc_grays_immune_objects_ to true in a scope if the current thread is GC.
1946class ConcurrentCopying::ScopedGcGraysImmuneObjects {
1947 public:
1948 explicit ScopedGcGraysImmuneObjects(ConcurrentCopying* collector)
1949 : collector_(collector), enabled_(false) {
1950 if (kUseBakerReadBarrier &&
1951 collector_->thread_running_gc_ == Thread::Current() &&
1952 !collector_->gc_grays_immune_objects_) {
1953 collector_->gc_grays_immune_objects_ = true;
1954 enabled_ = true;
1955 }
1956 }
1957
1958 ~ScopedGcGraysImmuneObjects() {
1959 if (kUseBakerReadBarrier &&
1960 collector_->thread_running_gc_ == Thread::Current() &&
1961 enabled_) {
1962 DCHECK(collector_->gc_grays_immune_objects_);
1963 collector_->gc_grays_immune_objects_ = false;
1964 }
1965 }
1966
1967 private:
1968 ConcurrentCopying* const collector_;
1969 bool enabled_;
1970};
1971
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001972// Fill the given memory block with a dummy object. Used to fill in a
1973// copy of objects that was lost in race.
1974void ConcurrentCopying::FillWithDummyObject(mirror::Object* dummy_obj, size_t byte_size) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001975 // GC doesn't gray immune objects while scanning immune objects. But we need to trigger the read
1976 // barriers here because we need the updated reference to the int array class, etc. Temporary set
1977 // gc_grays_immune_objects_ to true so that we won't cause a DCHECK failure in MarkImmuneSpace().
1978 ScopedGcGraysImmuneObjects scoped_gc_gray_immune_objects(this);
Roland Levillain14d90572015-07-16 10:52:26 +01001979 CHECK_ALIGNED(byte_size, kObjectAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001980 memset(dummy_obj, 0, byte_size);
Mathieu Chartierd6636d32016-07-28 11:02:38 -07001981 // Avoid going through read barrier for since kDisallowReadBarrierDuringScan may be enabled.
1982 // Explicitly mark to make sure to get an object in the to-space.
1983 mirror::Class* int_array_class = down_cast<mirror::Class*>(
1984 Mark(mirror::IntArray::GetArrayClass<kWithoutReadBarrier>()));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001985 CHECK(int_array_class != nullptr);
1986 AssertToSpaceInvariant(nullptr, MemberOffset(0), int_array_class);
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07001987 size_t component_size = int_array_class->GetComponentSize<kWithoutReadBarrier>();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001988 CHECK_EQ(component_size, sizeof(int32_t));
1989 size_t data_offset = mirror::Array::DataOffset(component_size).SizeValue();
1990 if (data_offset > byte_size) {
1991 // An int array is too big. Use java.lang.Object.
Mathieu Chartierc4f39252016-10-05 18:32:08 -07001992 ObjPtr<mirror::Class> java_lang_Object =
1993 WellKnownClasses::ToClass(WellKnownClasses::java_lang_Object);
1994 AssertToSpaceInvariant(nullptr, MemberOffset(0), java_lang_Object.Ptr());
Mathieu Chartierd6636d32016-07-28 11:02:38 -07001995 CHECK_EQ(byte_size, (java_lang_Object->GetObjectSize<kVerifyNone, kWithoutReadBarrier>()));
Mathieu Chartierc4f39252016-10-05 18:32:08 -07001996 dummy_obj->SetClass(java_lang_Object.Ptr());
Mathieu Chartierd6636d32016-07-28 11:02:38 -07001997 CHECK_EQ(byte_size, (dummy_obj->SizeOf<kVerifyNone, kWithoutReadBarrier>()));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001998 } else {
1999 // Use an int array.
2000 dummy_obj->SetClass(int_array_class);
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07002001 CHECK((dummy_obj->IsArrayInstance<kVerifyNone, kWithoutReadBarrier>()));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002002 int32_t length = (byte_size - data_offset) / component_size;
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07002003 mirror::Array* dummy_arr = dummy_obj->AsArray<kVerifyNone, kWithoutReadBarrier>();
2004 dummy_arr->SetLength(length);
2005 CHECK_EQ(dummy_arr->GetLength(), length)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002006 << "byte_size=" << byte_size << " length=" << length
2007 << " component_size=" << component_size << " data_offset=" << data_offset;
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07002008 CHECK_EQ(byte_size, (dummy_obj->SizeOf<kVerifyNone, kWithoutReadBarrier>()))
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002009 << "byte_size=" << byte_size << " length=" << length
2010 << " component_size=" << component_size << " data_offset=" << data_offset;
2011 }
2012}
2013
2014// Reuse the memory blocks that were copy of objects that were lost in race.
2015mirror::Object* ConcurrentCopying::AllocateInSkippedBlock(size_t alloc_size) {
2016 // Try to reuse the blocks that were unused due to CAS failures.
Roland Levillain14d90572015-07-16 10:52:26 +01002017 CHECK_ALIGNED(alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002018 Thread* self = Thread::Current();
2019 size_t min_object_size = RoundUp(sizeof(mirror::Object), space::RegionSpace::kAlignment);
Mathieu Chartierd6636d32016-07-28 11:02:38 -07002020 size_t byte_size;
2021 uint8_t* addr;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002022 {
Mathieu Chartierd6636d32016-07-28 11:02:38 -07002023 MutexLock mu(self, skipped_blocks_lock_);
2024 auto it = skipped_blocks_map_.lower_bound(alloc_size);
2025 if (it == skipped_blocks_map_.end()) {
2026 // Not found.
2027 return nullptr;
2028 }
2029 byte_size = it->first;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002030 CHECK_GE(byte_size, alloc_size);
2031 if (byte_size > alloc_size && byte_size - alloc_size < min_object_size) {
2032 // If remainder would be too small for a dummy object, retry with a larger request size.
2033 it = skipped_blocks_map_.lower_bound(alloc_size + min_object_size);
2034 if (it == skipped_blocks_map_.end()) {
2035 // Not found.
2036 return nullptr;
2037 }
Roland Levillain14d90572015-07-16 10:52:26 +01002038 CHECK_ALIGNED(it->first - alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002039 CHECK_GE(it->first - alloc_size, min_object_size)
2040 << "byte_size=" << byte_size << " it->first=" << it->first << " alloc_size=" << alloc_size;
2041 }
Mathieu Chartierd6636d32016-07-28 11:02:38 -07002042 // Found a block.
2043 CHECK(it != skipped_blocks_map_.end());
2044 byte_size = it->first;
2045 addr = it->second;
2046 CHECK_GE(byte_size, alloc_size);
2047 CHECK(region_space_->IsInToSpace(reinterpret_cast<mirror::Object*>(addr)));
2048 CHECK_ALIGNED(byte_size, space::RegionSpace::kAlignment);
2049 if (kVerboseMode) {
2050 LOG(INFO) << "Reusing skipped bytes : " << reinterpret_cast<void*>(addr) << ", " << byte_size;
2051 }
2052 skipped_blocks_map_.erase(it);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002053 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002054 memset(addr, 0, byte_size);
2055 if (byte_size > alloc_size) {
2056 // Return the remainder to the map.
Roland Levillain14d90572015-07-16 10:52:26 +01002057 CHECK_ALIGNED(byte_size - alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002058 CHECK_GE(byte_size - alloc_size, min_object_size);
Mathieu Chartierd6636d32016-07-28 11:02:38 -07002059 // FillWithDummyObject may mark an object, avoid holding skipped_blocks_lock_ to prevent lock
2060 // violation and possible deadlock. The deadlock case is a recursive case:
2061 // FillWithDummyObject -> IntArray::GetArrayClass -> Mark -> Copy -> AllocateInSkippedBlock.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002062 FillWithDummyObject(reinterpret_cast<mirror::Object*>(addr + alloc_size),
2063 byte_size - alloc_size);
2064 CHECK(region_space_->IsInToSpace(reinterpret_cast<mirror::Object*>(addr + alloc_size)));
Mathieu Chartierd6636d32016-07-28 11:02:38 -07002065 {
2066 MutexLock mu(self, skipped_blocks_lock_);
2067 skipped_blocks_map_.insert(std::make_pair(byte_size - alloc_size, addr + alloc_size));
2068 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002069 }
2070 return reinterpret_cast<mirror::Object*>(addr);
2071}
2072
2073mirror::Object* ConcurrentCopying::Copy(mirror::Object* from_ref) {
2074 DCHECK(region_space_->IsInFromSpace(from_ref));
2075 // No read barrier to avoid nested RB that might violate the to-space
2076 // invariant. Note that from_ref is a from space ref so the SizeOf()
2077 // call will access the from-space meta objects, but it's ok and necessary.
2078 size_t obj_size = from_ref->SizeOf<kDefaultVerifyFlags, kWithoutReadBarrier>();
2079 size_t region_space_alloc_size = RoundUp(obj_size, space::RegionSpace::kAlignment);
2080 size_t region_space_bytes_allocated = 0U;
2081 size_t non_moving_space_bytes_allocated = 0U;
2082 size_t bytes_allocated = 0U;
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07002083 size_t dummy;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002084 mirror::Object* to_ref = region_space_->AllocNonvirtual<true>(
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07002085 region_space_alloc_size, &region_space_bytes_allocated, nullptr, &dummy);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002086 bytes_allocated = region_space_bytes_allocated;
2087 if (to_ref != nullptr) {
2088 DCHECK_EQ(region_space_alloc_size, region_space_bytes_allocated);
2089 }
2090 bool fall_back_to_non_moving = false;
2091 if (UNLIKELY(to_ref == nullptr)) {
2092 // Failed to allocate in the region space. Try the skipped blocks.
2093 to_ref = AllocateInSkippedBlock(region_space_alloc_size);
2094 if (to_ref != nullptr) {
2095 // Succeeded to allocate in a skipped block.
2096 if (heap_->use_tlab_) {
2097 // This is necessary for the tlab case as it's not accounted in the space.
2098 region_space_->RecordAlloc(to_ref);
2099 }
2100 bytes_allocated = region_space_alloc_size;
2101 } else {
2102 // Fall back to the non-moving space.
2103 fall_back_to_non_moving = true;
2104 if (kVerboseMode) {
2105 LOG(INFO) << "Out of memory in the to-space. Fall back to non-moving. skipped_bytes="
2106 << to_space_bytes_skipped_.LoadSequentiallyConsistent()
2107 << " skipped_objects=" << to_space_objects_skipped_.LoadSequentiallyConsistent();
2108 }
2109 fall_back_to_non_moving = true;
2110 to_ref = heap_->non_moving_space_->Alloc(Thread::Current(), obj_size,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07002111 &non_moving_space_bytes_allocated, nullptr, &dummy);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002112 CHECK(to_ref != nullptr) << "Fall-back non-moving space allocation failed";
2113 bytes_allocated = non_moving_space_bytes_allocated;
2114 // Mark it in the mark bitmap.
2115 accounting::ContinuousSpaceBitmap* mark_bitmap =
2116 heap_mark_bitmap_->GetContinuousSpaceBitmap(to_ref);
2117 CHECK(mark_bitmap != nullptr);
2118 CHECK(!mark_bitmap->AtomicTestAndSet(to_ref));
2119 }
2120 }
2121 DCHECK(to_ref != nullptr);
2122
Mathieu Chartierd818adb2016-09-15 13:12:47 -07002123 // Copy the object excluding the lock word since that is handled in the loop.
2124 to_ref->SetClass(from_ref->GetClass<kVerifyNone, kWithoutReadBarrier>());
2125 const size_t kObjectHeaderSize = sizeof(mirror::Object);
2126 DCHECK_GE(obj_size, kObjectHeaderSize);
2127 static_assert(kObjectHeaderSize == sizeof(mirror::HeapReference<mirror::Class>) +
2128 sizeof(LockWord),
2129 "Object header size does not match");
2130 // Memcpy can tear for words since it may do byte copy. It is only safe to do this since the
2131 // object in the from space is immutable other than the lock word. b/31423258
2132 memcpy(reinterpret_cast<uint8_t*>(to_ref) + kObjectHeaderSize,
2133 reinterpret_cast<const uint8_t*>(from_ref) + kObjectHeaderSize,
2134 obj_size - kObjectHeaderSize);
2135
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002136 // Attempt to install the forward pointer. This is in a loop as the
2137 // lock word atomic write can fail.
2138 while (true) {
Mathieu Chartierd818adb2016-09-15 13:12:47 -07002139 LockWord old_lock_word = from_ref->GetLockWord(false);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002140
2141 if (old_lock_word.GetState() == LockWord::kForwardingAddress) {
2142 // Lost the race. Another thread (either GC or mutator) stored
2143 // the forwarding pointer first. Make the lost copy (to_ref)
2144 // look like a valid but dead (dummy) object and keep it for
2145 // future reuse.
2146 FillWithDummyObject(to_ref, bytes_allocated);
2147 if (!fall_back_to_non_moving) {
2148 DCHECK(region_space_->IsInToSpace(to_ref));
2149 if (bytes_allocated > space::RegionSpace::kRegionSize) {
2150 // Free the large alloc.
2151 region_space_->FreeLarge(to_ref, bytes_allocated);
2152 } else {
2153 // Record the lost copy for later reuse.
2154 heap_->num_bytes_allocated_.FetchAndAddSequentiallyConsistent(bytes_allocated);
2155 to_space_bytes_skipped_.FetchAndAddSequentiallyConsistent(bytes_allocated);
2156 to_space_objects_skipped_.FetchAndAddSequentiallyConsistent(1);
2157 MutexLock mu(Thread::Current(), skipped_blocks_lock_);
2158 skipped_blocks_map_.insert(std::make_pair(bytes_allocated,
2159 reinterpret_cast<uint8_t*>(to_ref)));
2160 }
2161 } else {
2162 DCHECK(heap_->non_moving_space_->HasAddress(to_ref));
2163 DCHECK_EQ(bytes_allocated, non_moving_space_bytes_allocated);
2164 // Free the non-moving-space chunk.
2165 accounting::ContinuousSpaceBitmap* mark_bitmap =
2166 heap_mark_bitmap_->GetContinuousSpaceBitmap(to_ref);
2167 CHECK(mark_bitmap != nullptr);
2168 CHECK(mark_bitmap->Clear(to_ref));
2169 heap_->non_moving_space_->Free(Thread::Current(), to_ref);
2170 }
2171
2172 // Get the winner's forward ptr.
2173 mirror::Object* lost_fwd_ptr = to_ref;
2174 to_ref = reinterpret_cast<mirror::Object*>(old_lock_word.ForwardingAddress());
2175 CHECK(to_ref != nullptr);
2176 CHECK_NE(to_ref, lost_fwd_ptr);
Mathieu Chartierdfcd6f42016-09-13 10:02:48 -07002177 CHECK(region_space_->IsInToSpace(to_ref) || heap_->non_moving_space_->HasAddress(to_ref))
2178 << "to_ref=" << to_ref << " " << heap_->DumpSpaces();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002179 CHECK_NE(to_ref->GetLockWord(false).GetState(), LockWord::kForwardingAddress);
2180 return to_ref;
2181 }
2182
Mathieu Chartierd818adb2016-09-15 13:12:47 -07002183 // Copy the old lock word over since we did not copy it yet.
2184 to_ref->SetLockWord(old_lock_word, false);
Hiroshi Yamauchi60f63f52015-04-23 16:12:40 -07002185 // Set the gray ptr.
2186 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002187 to_ref->SetReadBarrierState(ReadBarrier::GrayState());
Hiroshi Yamauchi60f63f52015-04-23 16:12:40 -07002188 }
2189
Mathieu Chartiera8131262016-11-29 17:55:19 -08002190 // Do a fence to prevent the field CAS in ConcurrentCopying::Process from possibly reordering
2191 // before the object copy.
2192 QuasiAtomic::ThreadFenceRelease();
2193
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002194 LockWord new_lock_word = LockWord::FromForwardingAddress(reinterpret_cast<size_t>(to_ref));
2195
2196 // Try to atomically write the fwd ptr.
Mathieu Chartiera8131262016-11-29 17:55:19 -08002197 bool success = from_ref->CasLockWordWeakRelaxed(old_lock_word, new_lock_word);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002198 if (LIKELY(success)) {
2199 // The CAS succeeded.
Mathieu Chartiera8131262016-11-29 17:55:19 -08002200 objects_moved_.FetchAndAddRelaxed(1);
2201 bytes_moved_.FetchAndAddRelaxed(region_space_alloc_size);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002202 if (LIKELY(!fall_back_to_non_moving)) {
2203 DCHECK(region_space_->IsInToSpace(to_ref));
2204 } else {
2205 DCHECK(heap_->non_moving_space_->HasAddress(to_ref));
2206 DCHECK_EQ(bytes_allocated, non_moving_space_bytes_allocated);
2207 }
2208 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002209 DCHECK(to_ref->GetReadBarrierState() == ReadBarrier::GrayState());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002210 }
2211 DCHECK(GetFwdPtr(from_ref) == to_ref);
2212 CHECK_NE(to_ref->GetLockWord(false).GetState(), LockWord::kForwardingAddress);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002213 PushOntoMarkStack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002214 return to_ref;
2215 } else {
2216 // The CAS failed. It may have lost the race or may have failed
2217 // due to monitor/hashcode ops. Either way, retry.
2218 }
2219 }
2220}
2221
2222mirror::Object* ConcurrentCopying::IsMarked(mirror::Object* from_ref) {
2223 DCHECK(from_ref != nullptr);
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08002224 space::RegionSpace::RegionType rtype = region_space_->GetRegionType(from_ref);
2225 if (rtype == space::RegionSpace::RegionType::kRegionTypeToSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002226 // It's already marked.
2227 return from_ref;
2228 }
2229 mirror::Object* to_ref;
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08002230 if (rtype == space::RegionSpace::RegionType::kRegionTypeFromSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002231 to_ref = GetFwdPtr(from_ref);
2232 DCHECK(to_ref == nullptr || region_space_->IsInToSpace(to_ref) ||
2233 heap_->non_moving_space_->HasAddress(to_ref))
2234 << "from_ref=" << from_ref << " to_ref=" << to_ref;
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08002235 } else if (rtype == space::RegionSpace::RegionType::kRegionTypeUnevacFromSpace) {
Mathieu Chartierc381c362016-08-23 13:27:53 -07002236 if (IsMarkedInUnevacFromSpace(from_ref)) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002237 to_ref = from_ref;
2238 } else {
2239 to_ref = nullptr;
2240 }
2241 } else {
2242 // from_ref is in a non-moving space.
Mathieu Chartier763a31e2015-11-16 16:05:55 -08002243 if (immune_spaces_.ContainsObject(from_ref)) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002244 // An immune object is alive.
2245 to_ref = from_ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002246 } else {
2247 // Non-immune non-moving space. Use the mark bitmap.
2248 accounting::ContinuousSpaceBitmap* mark_bitmap =
2249 heap_mark_bitmap_->GetContinuousSpaceBitmap(from_ref);
2250 accounting::LargeObjectBitmap* los_bitmap =
2251 heap_mark_bitmap_->GetLargeObjectBitmap(from_ref);
2252 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
2253 bool is_los = mark_bitmap == nullptr;
2254 if (!is_los && mark_bitmap->Test(from_ref)) {
2255 // Already marked.
2256 to_ref = from_ref;
2257 } else if (is_los && los_bitmap->Test(from_ref)) {
2258 // Already marked in LOS.
2259 to_ref = from_ref;
2260 } else {
2261 // Not marked.
2262 if (IsOnAllocStack(from_ref)) {
2263 // If on the allocation stack, it's considered marked.
2264 to_ref = from_ref;
2265 } else {
2266 // Not marked.
2267 to_ref = nullptr;
2268 }
2269 }
2270 }
2271 }
2272 return to_ref;
2273}
2274
2275bool ConcurrentCopying::IsOnAllocStack(mirror::Object* ref) {
2276 QuasiAtomic::ThreadFenceAcquire();
2277 accounting::ObjectStack* alloc_stack = GetAllocationStack();
Mathieu Chartiercb535da2015-01-23 13:50:03 -08002278 return alloc_stack->Contains(ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002279}
2280
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002281mirror::Object* ConcurrentCopying::MarkNonMoving(mirror::Object* ref) {
2282 // ref is in a non-moving space (from_ref == to_ref).
2283 DCHECK(!region_space_->HasAddress(ref)) << ref;
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002284 DCHECK(!immune_spaces_.ContainsObject(ref));
2285 // Use the mark bitmap.
2286 accounting::ContinuousSpaceBitmap* mark_bitmap =
2287 heap_mark_bitmap_->GetContinuousSpaceBitmap(ref);
2288 accounting::LargeObjectBitmap* los_bitmap =
2289 heap_mark_bitmap_->GetLargeObjectBitmap(ref);
2290 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
2291 bool is_los = mark_bitmap == nullptr;
2292 if (!is_los && mark_bitmap->Test(ref)) {
2293 // Already marked.
2294 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002295 DCHECK(ref->GetReadBarrierState() == ReadBarrier::GrayState() ||
2296 ref->GetReadBarrierState() == ReadBarrier::WhiteState());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002297 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002298 } else if (is_los && los_bitmap->Test(ref)) {
2299 // Already marked in LOS.
2300 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002301 DCHECK(ref->GetReadBarrierState() == ReadBarrier::GrayState() ||
2302 ref->GetReadBarrierState() == ReadBarrier::WhiteState());
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002303 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002304 } else {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002305 // Not marked.
2306 if (IsOnAllocStack(ref)) {
2307 // If it's on the allocation stack, it's considered marked. Keep it white.
2308 // Objects on the allocation stack need not be marked.
2309 if (!is_los) {
2310 DCHECK(!mark_bitmap->Test(ref));
2311 } else {
2312 DCHECK(!los_bitmap->Test(ref));
Nicolas Geoffrayddeb1722016-06-28 08:25:59 +00002313 }
Nicolas Geoffrayddeb1722016-06-28 08:25:59 +00002314 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002315 DCHECK_EQ(ref->GetReadBarrierState(), ReadBarrier::WhiteState());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002316 }
2317 } else {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002318 // For the baker-style RB, we need to handle 'false-gray' cases. See the
2319 // kRegionTypeUnevacFromSpace-case comment in Mark().
2320 if (kUseBakerReadBarrier) {
2321 // Test the bitmap first to reduce the chance of false gray cases.
2322 if ((!is_los && mark_bitmap->Test(ref)) ||
2323 (is_los && los_bitmap->Test(ref))) {
2324 return ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002325 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002326 }
2327 // Not marked or on the allocation stack. Try to mark it.
2328 // This may or may not succeed, which is ok.
2329 bool cas_success = false;
2330 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002331 cas_success = ref->AtomicSetReadBarrierState(ReadBarrier::WhiteState(),
2332 ReadBarrier::GrayState());
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002333 }
2334 if (!is_los && mark_bitmap->AtomicTestAndSet(ref)) {
2335 // Already marked.
2336 if (kUseBakerReadBarrier && cas_success &&
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002337 ref->GetReadBarrierState() == ReadBarrier::GrayState()) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002338 PushOntoFalseGrayStack(ref);
2339 }
2340 } else if (is_los && los_bitmap->AtomicTestAndSet(ref)) {
2341 // Already marked in LOS.
2342 if (kUseBakerReadBarrier && cas_success &&
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002343 ref->GetReadBarrierState() == ReadBarrier::GrayState()) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002344 PushOntoFalseGrayStack(ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002345 }
2346 } else {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002347 // Newly marked.
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08002348 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002349 DCHECK_EQ(ref->GetReadBarrierState(), ReadBarrier::GrayState());
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08002350 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002351 PushOntoMarkStack(ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002352 }
2353 }
2354 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002355 return ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002356}
2357
2358void ConcurrentCopying::FinishPhase() {
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -08002359 Thread* const self = Thread::Current();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002360 {
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -08002361 MutexLock mu(self, mark_stack_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002362 CHECK_EQ(pooled_mark_stacks_.size(), kMarkStackPoolSize);
2363 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002364 {
Mathieu Chartier6e6078a2016-10-24 15:45:41 -07002365 TimingLogger::ScopedTiming split("ClearRegionSpaceCards", GetTimings());
2366 // We do not currently use the region space cards at all, madvise them away to save ram.
2367 heap_->GetCardTable()->ClearCardRange(region_space_->Begin(), region_space_->Limit());
Mathieu Chartier6e6078a2016-10-24 15:45:41 -07002368 }
2369 {
2370 MutexLock mu(self, skipped_blocks_lock_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002371 skipped_blocks_map_.clear();
2372 }
Mathieu Chartier56fe2582016-07-14 13:30:03 -07002373 {
2374 ReaderMutexLock mu(self, *Locks::mutator_lock_);
Mathieu Chartier21328a12016-07-22 10:47:45 -07002375 {
2376 WriterMutexLock mu2(self, *Locks::heap_bitmap_lock_);
2377 heap_->ClearMarkedObjects();
2378 }
2379 if (kUseBakerReadBarrier && kFilterModUnionCards) {
2380 TimingLogger::ScopedTiming split("FilterModUnionCards", GetTimings());
2381 ReaderMutexLock mu2(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier21328a12016-07-22 10:47:45 -07002382 for (space::ContinuousSpace* space : immune_spaces_.GetSpaces()) {
2383 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
Mathieu Chartier6e6078a2016-10-24 15:45:41 -07002384 accounting::ModUnionTable* table = heap_->FindModUnionTableFromSpace(space);
Mathieu Chartier21328a12016-07-22 10:47:45 -07002385 // Filter out cards that don't need to be set.
2386 if (table != nullptr) {
2387 table->FilterCards();
2388 }
2389 }
2390 }
Mathieu Chartier36a270a2016-07-28 18:08:51 -07002391 if (kUseBakerReadBarrier) {
2392 TimingLogger::ScopedTiming split("EmptyRBMarkBitStack", GetTimings());
Mathieu Chartier6e6078a2016-10-24 15:45:41 -07002393 DCHECK(rb_mark_bit_stack_ != nullptr);
Mathieu Chartier36a270a2016-07-28 18:08:51 -07002394 const auto* limit = rb_mark_bit_stack_->End();
2395 for (StackReference<mirror::Object>* it = rb_mark_bit_stack_->Begin(); it != limit; ++it) {
2396 CHECK(it->AsMirrorPtr()->AtomicSetMarkBit(1, 0));
2397 }
2398 rb_mark_bit_stack_->Reset();
2399 }
Mathieu Chartier56fe2582016-07-14 13:30:03 -07002400 }
2401 if (measure_read_barrier_slow_path_) {
2402 MutexLock mu(self, rb_slow_path_histogram_lock_);
2403 rb_slow_path_time_histogram_.AdjustAndAddValue(rb_slow_path_ns_.LoadRelaxed());
2404 rb_slow_path_count_total_ += rb_slow_path_count_.LoadRelaxed();
2405 rb_slow_path_count_gc_total_ += rb_slow_path_count_gc_.LoadRelaxed();
2406 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002407}
2408
Hiroshi Yamauchi65f5f242016-12-19 11:44:47 -08002409bool ConcurrentCopying::IsNullOrMarkedHeapReference(mirror::HeapReference<mirror::Object>* field,
2410 bool do_atomic_update) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002411 mirror::Object* from_ref = field->AsMirrorPtr();
Hiroshi Yamauchi65f5f242016-12-19 11:44:47 -08002412 if (from_ref == nullptr) {
2413 return true;
2414 }
Mathieu Chartier97509952015-07-13 14:35:43 -07002415 mirror::Object* to_ref = IsMarked(from_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002416 if (to_ref == nullptr) {
2417 return false;
2418 }
2419 if (from_ref != to_ref) {
Hiroshi Yamauchi65f5f242016-12-19 11:44:47 -08002420 if (do_atomic_update) {
2421 do {
2422 if (field->AsMirrorPtr() != from_ref) {
2423 // Concurrently overwritten by a mutator.
2424 break;
2425 }
2426 } while (!field->CasWeakRelaxed(from_ref, to_ref));
2427 } else {
2428 QuasiAtomic::ThreadFenceRelease();
2429 field->Assign(to_ref);
2430 QuasiAtomic::ThreadFenceSequentiallyConsistent();
2431 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002432 }
2433 return true;
2434}
2435
Mathieu Chartier97509952015-07-13 14:35:43 -07002436mirror::Object* ConcurrentCopying::MarkObject(mirror::Object* from_ref) {
2437 return Mark(from_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002438}
2439
Mathieu Chartier31e88222016-10-14 18:43:19 -07002440void ConcurrentCopying::DelayReferenceReferent(ObjPtr<mirror::Class> klass,
2441 ObjPtr<mirror::Reference> reference) {
Mathieu Chartier97509952015-07-13 14:35:43 -07002442 heap_->GetReferenceProcessor()->DelayReferenceReferent(klass, reference, this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002443}
2444
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002445void ConcurrentCopying::ProcessReferences(Thread* self) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002446 TimingLogger::ScopedTiming split("ProcessReferences", GetTimings());
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002447 // 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 -08002448 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
2449 GetHeap()->GetReferenceProcessor()->ProcessReferences(
Mathieu Chartier97509952015-07-13 14:35:43 -07002450 true /*concurrent*/, GetTimings(), GetCurrentIteration()->GetClearSoftReferences(), this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002451}
2452
2453void ConcurrentCopying::RevokeAllThreadLocalBuffers() {
2454 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
2455 region_space_->RevokeAllThreadLocalBuffers();
2456}
2457
Mathieu Chartier56fe2582016-07-14 13:30:03 -07002458mirror::Object* ConcurrentCopying::MarkFromReadBarrierWithMeasurements(mirror::Object* from_ref) {
2459 if (Thread::Current() != thread_running_gc_) {
2460 rb_slow_path_count_.FetchAndAddRelaxed(1u);
2461 } else {
2462 rb_slow_path_count_gc_.FetchAndAddRelaxed(1u);
2463 }
2464 ScopedTrace tr(__FUNCTION__);
2465 const uint64_t start_time = measure_read_barrier_slow_path_ ? NanoTime() : 0u;
2466 mirror::Object* ret = Mark(from_ref);
2467 if (measure_read_barrier_slow_path_) {
2468 rb_slow_path_ns_.FetchAndAddRelaxed(NanoTime() - start_time);
2469 }
2470 return ret;
2471}
2472
2473void ConcurrentCopying::DumpPerformanceInfo(std::ostream& os) {
2474 GarbageCollector::DumpPerformanceInfo(os);
2475 MutexLock mu(Thread::Current(), rb_slow_path_histogram_lock_);
2476 if (rb_slow_path_time_histogram_.SampleSize() > 0) {
2477 Histogram<uint64_t>::CumulativeData cumulative_data;
2478 rb_slow_path_time_histogram_.CreateHistogram(&cumulative_data);
2479 rb_slow_path_time_histogram_.PrintConfidenceIntervals(os, 0.99, cumulative_data);
2480 }
2481 if (rb_slow_path_count_total_ > 0) {
2482 os << "Slow path count " << rb_slow_path_count_total_ << "\n";
2483 }
2484 if (rb_slow_path_count_gc_total_ > 0) {
2485 os << "GC slow path count " << rb_slow_path_count_gc_total_ << "\n";
2486 }
Mathieu Chartiercca44a02016-08-17 10:07:29 -07002487 os << "Cumulative bytes moved " << cumulative_bytes_moved_.LoadRelaxed() << "\n";
2488 os << "Cumulative objects moved " << cumulative_objects_moved_.LoadRelaxed() << "\n";
Mathieu Chartier56fe2582016-07-14 13:30:03 -07002489}
2490
Hiroshi Yamauchid5307ec2014-03-27 21:07:51 -07002491} // namespace collector
2492} // namespace gc
2493} // namespace art