blob: b7b5aa00590401a5e3f3623d097a20789a21ec37 [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"
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070020#include "base/stl_util.h"
Mathieu Chartiera6b1ead2015-10-06 10:32:38 -070021#include "debugger.h"
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080022#include "gc/accounting/heap_bitmap-inl.h"
23#include "gc/accounting/space_bitmap-inl.h"
Mathieu Chartier3cf22532015-07-09 15:15:09 -070024#include "gc/reference_processor.h"
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080025#include "gc/space/image_space.h"
Mathieu Chartier073b16c2015-11-10 14:13:23 -080026#include "gc/space/space-inl.h"
Mathieu Chartier4a26f172016-01-26 14:26:18 -080027#include "image-inl.h"
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080028#include "intern_table.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070029#include "mirror/class-inl.h"
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080030#include "mirror/object-inl.h"
31#include "scoped_thread_state_change.h"
32#include "thread-inl.h"
33#include "thread_list.h"
34#include "well_known_classes.h"
35
Hiroshi Yamauchid5307ec2014-03-27 21:07:51 -070036namespace art {
37namespace gc {
38namespace collector {
39
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -070040static constexpr size_t kDefaultGcMarkStackSize = 2 * MB;
41
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080042ConcurrentCopying::ConcurrentCopying(Heap* heap, const std::string& name_prefix)
43 : GarbageCollector(heap,
44 name_prefix + (name_prefix.empty() ? "" : " ") +
45 "concurrent copying + mark sweep"),
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070046 region_space_(nullptr), gc_barrier_(new Barrier(0)),
47 gc_mark_stack_(accounting::ObjectStack::Create("concurrent copying gc mark stack",
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -070048 kDefaultGcMarkStackSize,
49 kDefaultGcMarkStackSize)),
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070050 mark_stack_lock_("concurrent copying mark stack lock", kMarkSweepMarkStackLock),
51 thread_running_gc_(nullptr),
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080052 is_marking_(false), is_active_(false), is_asserting_to_space_invariant_(false),
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -070053 region_space_bitmap_(nullptr),
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070054 heap_mark_bitmap_(nullptr), live_stack_freeze_size_(0), mark_stack_mode_(kMarkStackModeOff),
55 weak_ref_access_enabled_(true),
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080056 skipped_blocks_lock_("concurrent copying bytes blocks lock", kMarkSweepMarkStackLock),
57 rb_table_(heap_->GetReadBarrierTable()),
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -070058 force_evacuate_all_(false),
59 immune_gray_stack_lock_("concurrent copying immune gray stack lock",
60 kMarkSweepMarkStackLock) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080061 static_assert(space::RegionSpace::kRegionSize == accounting::ReadBarrierTable::kRegionSize,
62 "The region space size and the read barrier table region size must match");
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070063 Thread* self = Thread::Current();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080064 {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080065 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
66 // Cache this so that we won't have to lock heap_bitmap_lock_ in
67 // Mark() which could cause a nested lock on heap_bitmap_lock_
68 // when GC causes a RB while doing GC or a lock order violation
69 // (class_linker_lock_ and heap_bitmap_lock_).
70 heap_mark_bitmap_ = heap->GetMarkBitmap();
71 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070072 {
73 MutexLock mu(self, mark_stack_lock_);
74 for (size_t i = 0; i < kMarkStackPoolSize; ++i) {
75 accounting::AtomicStack<mirror::Object>* mark_stack =
76 accounting::AtomicStack<mirror::Object>::Create(
77 "thread local mark stack", kMarkStackSize, kMarkStackSize);
78 pooled_mark_stacks_.push_back(mark_stack);
79 }
80 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080081}
82
Mathieu Chartierb19ccb12015-07-15 10:24:16 -070083void ConcurrentCopying::MarkHeapReference(mirror::HeapReference<mirror::Object>* from_ref) {
84 // Used for preserving soft references, should be OK to not have a CAS here since there should be
85 // no other threads which can trigger read barriers on the same referent during reference
86 // processing.
87 from_ref->Assign(Mark(from_ref->AsMirrorPtr()));
Mathieu Chartier81187812015-07-15 14:24:07 -070088 DCHECK(!from_ref->IsNull());
Mathieu Chartier97509952015-07-13 14:35:43 -070089}
90
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080091ConcurrentCopying::~ConcurrentCopying() {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070092 STLDeleteElements(&pooled_mark_stacks_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080093}
94
95void ConcurrentCopying::RunPhases() {
96 CHECK(kUseBakerReadBarrier || kUseTableLookupReadBarrier);
97 CHECK(!is_active_);
98 is_active_ = true;
99 Thread* self = Thread::Current();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700100 thread_running_gc_ = self;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800101 Locks::mutator_lock_->AssertNotHeld(self);
102 {
103 ReaderMutexLock mu(self, *Locks::mutator_lock_);
104 InitializePhase();
105 }
106 FlipThreadRoots();
107 {
108 ReaderMutexLock mu(self, *Locks::mutator_lock_);
109 MarkingPhase();
110 }
111 // Verify no from space refs. This causes a pause.
112 if (kEnableNoFromSpaceRefsVerification || kIsDebugBuild) {
113 TimingLogger::ScopedTiming split("(Paused)VerifyNoFromSpaceReferences", GetTimings());
114 ScopedPause pause(this);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700115 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800116 if (kVerboseMode) {
117 LOG(INFO) << "Verifying no from-space refs";
118 }
119 VerifyNoFromSpaceReferences();
Mathieu Chartier720e71a2015-04-06 17:10:58 -0700120 if (kVerboseMode) {
121 LOG(INFO) << "Done verifying no from-space refs";
122 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700123 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800124 }
125 {
126 ReaderMutexLock mu(self, *Locks::mutator_lock_);
127 ReclaimPhase();
128 }
129 FinishPhase();
130 CHECK(is_active_);
131 is_active_ = false;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700132 thread_running_gc_ = nullptr;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800133}
134
135void ConcurrentCopying::BindBitmaps() {
136 Thread* self = Thread::Current();
137 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
138 // Mark all of the spaces we never collect as immune.
139 for (const auto& space : heap_->GetContinuousSpaces()) {
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800140 if (space->GetGcRetentionPolicy() == space::kGcRetentionPolicyNeverCollect ||
141 space->GetGcRetentionPolicy() == space::kGcRetentionPolicyFullCollect) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800142 CHECK(space->IsZygoteSpace() || space->IsImageSpace());
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800143 immune_spaces_.AddSpace(space);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800144 } else if (space == region_space_) {
145 accounting::ContinuousSpaceBitmap* bitmap =
146 accounting::ContinuousSpaceBitmap::Create("cc region space bitmap",
147 space->Begin(), space->Capacity());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800148 region_space_bitmap_ = bitmap;
149 }
150 }
151}
152
153void ConcurrentCopying::InitializePhase() {
154 TimingLogger::ScopedTiming split("InitializePhase", GetTimings());
155 if (kVerboseMode) {
156 LOG(INFO) << "GC InitializePhase";
157 LOG(INFO) << "Region-space : " << reinterpret_cast<void*>(region_space_->Begin()) << "-"
158 << reinterpret_cast<void*>(region_space_->Limit());
159 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700160 CheckEmptyMarkStack();
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800161 if (kIsDebugBuild) {
162 MutexLock mu(Thread::Current(), mark_stack_lock_);
163 CHECK(false_gray_stack_.empty());
164 }
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800165 immune_spaces_.Reset();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800166 bytes_moved_.StoreRelaxed(0);
167 objects_moved_.StoreRelaxed(0);
168 if (GetCurrentIteration()->GetGcCause() == kGcCauseExplicit ||
169 GetCurrentIteration()->GetGcCause() == kGcCauseForNativeAlloc ||
170 GetCurrentIteration()->GetClearSoftReferences()) {
171 force_evacuate_all_ = true;
172 } else {
173 force_evacuate_all_ = false;
174 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700175 if (kUseBakerReadBarrier) {
176 updated_all_immune_objects_.StoreRelaxed(false);
177 // GC may gray immune objects in the thread flip.
178 gc_grays_immune_objects_ = true;
179 if (kIsDebugBuild) {
180 MutexLock mu(Thread::Current(), immune_gray_stack_lock_);
181 DCHECK(immune_gray_stack_.empty());
182 }
183 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800184 BindBitmaps();
185 if (kVerboseMode) {
186 LOG(INFO) << "force_evacuate_all=" << force_evacuate_all_;
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800187 LOG(INFO) << "Largest immune region: " << immune_spaces_.GetLargestImmuneRegion().Begin()
188 << "-" << immune_spaces_.GetLargestImmuneRegion().End();
189 for (space::ContinuousSpace* space : immune_spaces_.GetSpaces()) {
190 LOG(INFO) << "Immune space: " << *space;
191 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800192 LOG(INFO) << "GC end of InitializePhase";
193 }
194}
195
196// Used to switch the thread roots of a thread from from-space refs to to-space refs.
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700197class ConcurrentCopying::ThreadFlipVisitor : public Closure {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800198 public:
Roland Levillain3887c462015-08-12 18:15:42 +0100199 ThreadFlipVisitor(ConcurrentCopying* concurrent_copying, bool use_tlab)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800200 : concurrent_copying_(concurrent_copying), use_tlab_(use_tlab) {
201 }
202
Mathieu Chartier90443472015-07-16 20:32:27 -0700203 virtual void Run(Thread* thread) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800204 // Note: self is not necessarily equal to thread since thread may be suspended.
205 Thread* self = Thread::Current();
206 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
207 << thread->GetState() << " thread " << thread << " self " << self;
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700208 thread->SetIsGcMarking(true);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800209 if (use_tlab_ && thread->HasTlab()) {
210 if (ConcurrentCopying::kEnableFromSpaceAccountingCheck) {
211 // This must come before the revoke.
212 size_t thread_local_objects = thread->GetThreadLocalObjectsAllocated();
213 concurrent_copying_->region_space_->RevokeThreadLocalBuffers(thread);
214 reinterpret_cast<Atomic<size_t>*>(&concurrent_copying_->from_space_num_objects_at_first_pause_)->
215 FetchAndAddSequentiallyConsistent(thread_local_objects);
216 } else {
217 concurrent_copying_->region_space_->RevokeThreadLocalBuffers(thread);
218 }
219 }
220 if (kUseThreadLocalAllocationStack) {
221 thread->RevokeThreadLocalAllocationStack();
222 }
223 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700224 thread->VisitRoots(concurrent_copying_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800225 concurrent_copying_->GetBarrier().Pass(self);
226 }
227
228 private:
229 ConcurrentCopying* const concurrent_copying_;
230 const bool use_tlab_;
231};
232
233// Called back from Runtime::FlipThreadRoots() during a pause.
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700234class ConcurrentCopying::FlipCallback : public Closure {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800235 public:
236 explicit FlipCallback(ConcurrentCopying* concurrent_copying)
237 : concurrent_copying_(concurrent_copying) {
238 }
239
Mathieu Chartier90443472015-07-16 20:32:27 -0700240 virtual void Run(Thread* thread) OVERRIDE REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800241 ConcurrentCopying* cc = concurrent_copying_;
242 TimingLogger::ScopedTiming split("(Paused)FlipCallback", cc->GetTimings());
243 // Note: self is not necessarily equal to thread since thread may be suspended.
244 Thread* self = Thread::Current();
245 CHECK(thread == self);
246 Locks::mutator_lock_->AssertExclusiveHeld(self);
247 cc->region_space_->SetFromSpace(cc->rb_table_, cc->force_evacuate_all_);
Mathieu Chartiera4f6af92015-08-11 17:35:25 -0700248 cc->SwapStacks();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800249 if (ConcurrentCopying::kEnableFromSpaceAccountingCheck) {
250 cc->RecordLiveStackFreezeSize(self);
251 cc->from_space_num_objects_at_first_pause_ = cc->region_space_->GetObjectsAllocated();
252 cc->from_space_num_bytes_at_first_pause_ = cc->region_space_->GetBytesAllocated();
253 }
254 cc->is_marking_ = true;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700255 cc->mark_stack_mode_.StoreRelaxed(ConcurrentCopying::kMarkStackModeThreadLocal);
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800256 if (kIsDebugBuild) {
257 cc->region_space_->AssertAllRegionLiveBytesZeroOrCleared();
258 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800259 if (UNLIKELY(Runtime::Current()->IsActiveTransaction())) {
Mathieu Chartier184c9dc2015-03-05 13:20:54 -0800260 CHECK(Runtime::Current()->IsAotCompiler());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800261 TimingLogger::ScopedTiming split2("(Paused)VisitTransactionRoots", cc->GetTimings());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700262 Runtime::Current()->VisitTransactionRoots(cc);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800263 }
264 }
265
266 private:
267 ConcurrentCopying* const concurrent_copying_;
268};
269
270// Switch threads that from from-space to to-space refs. Forward/mark the thread roots.
271void ConcurrentCopying::FlipThreadRoots() {
272 TimingLogger::ScopedTiming split("FlipThreadRoots", GetTimings());
273 if (kVerboseMode) {
274 LOG(INFO) << "time=" << region_space_->Time();
275 region_space_->DumpNonFreeRegions(LOG(INFO));
276 }
277 Thread* self = Thread::Current();
278 Locks::mutator_lock_->AssertNotHeld(self);
279 gc_barrier_->Init(self, 0);
280 ThreadFlipVisitor thread_flip_visitor(this, heap_->use_tlab_);
281 FlipCallback flip_callback(this);
Hiroshi Yamauchi76f55b02015-08-21 16:10:39 -0700282 heap_->ThreadFlipBegin(self); // Sync with JNI critical calls.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800283 size_t barrier_count = Runtime::Current()->FlipThreadRoots(
284 &thread_flip_visitor, &flip_callback, this);
Hiroshi Yamauchi76f55b02015-08-21 16:10:39 -0700285 heap_->ThreadFlipEnd(self);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800286 {
287 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
288 gc_barrier_->Increment(self, barrier_count);
289 }
290 is_asserting_to_space_invariant_ = true;
291 QuasiAtomic::ThreadFenceForConstructor();
292 if (kVerboseMode) {
293 LOG(INFO) << "time=" << region_space_->Time();
294 region_space_->DumpNonFreeRegions(LOG(INFO));
295 LOG(INFO) << "GC end of FlipThreadRoots";
296 }
297}
298
Mathieu Chartiera4f6af92015-08-11 17:35:25 -0700299void ConcurrentCopying::SwapStacks() {
300 heap_->SwapStacks();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800301}
302
303void ConcurrentCopying::RecordLiveStackFreezeSize(Thread* self) {
304 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
305 live_stack_freeze_size_ = heap_->GetLiveStack()->Size();
306}
307
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800308class EmptyCheckpoint : public Closure {
309 public:
310 explicit EmptyCheckpoint(ConcurrentCopying* concurrent_copying)
311 : concurrent_copying_(concurrent_copying) {
312 }
313
314 virtual void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
315 // Note: self is not necessarily equal to thread since thread may be suspended.
316 Thread* self = Thread::Current();
317 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
318 << thread->GetState() << " thread " << thread << " self " << self;
Lei Lidd9943d2015-02-02 14:24:44 +0800319 // If thread is a running mutator, then act on behalf of the garbage collector.
320 // See the code in ThreadList::RunCheckpoint.
Mathieu Chartier10d25082015-10-28 18:36:09 -0700321 concurrent_copying_->GetBarrier().Pass(self);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800322 }
323
324 private:
325 ConcurrentCopying* const concurrent_copying_;
326};
327
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700328// Used to visit objects in the immune spaces.
329inline void ConcurrentCopying::ScanImmuneObject(mirror::Object* obj) {
330 DCHECK(obj != nullptr);
331 DCHECK(immune_spaces_.ContainsObject(obj));
332 // Update the fields without graying it or pushing it onto the mark stack.
333 Scan(obj);
334}
335
336class ConcurrentCopying::ImmuneSpaceScanObjVisitor {
337 public:
338 explicit ImmuneSpaceScanObjVisitor(ConcurrentCopying* cc)
339 : collector_(cc) {}
340
341 void operator()(mirror::Object* obj) const SHARED_REQUIRES(Locks::mutator_lock_) {
342 collector_->ScanImmuneObject(obj);
343 }
344
345 private:
346 ConcurrentCopying* const collector_;
347};
348
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800349// Concurrently mark roots that are guarded by read barriers and process the mark stack.
350void ConcurrentCopying::MarkingPhase() {
351 TimingLogger::ScopedTiming split("MarkingPhase", GetTimings());
352 if (kVerboseMode) {
353 LOG(INFO) << "GC MarkingPhase";
354 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700355 CHECK(weak_ref_access_enabled_);
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700356
357 // Scan immune spaces.
358 // Update all the fields in the immune spaces first without graying the objects so that we
359 // minimize dirty pages in the immune spaces. Note mutators can concurrently access and gray some
360 // of the objects.
361 if (kUseBakerReadBarrier) {
362 gc_grays_immune_objects_ = false;
Hiroshi Yamauchi16292fc2016-06-20 20:23:34 -0700363 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700364 for (auto& space : immune_spaces_.GetSpaces()) {
365 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
366 accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
367 ImmuneSpaceScanObjVisitor visitor(this);
368 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()),
369 reinterpret_cast<uintptr_t>(space->Limit()),
370 visitor);
371 }
372 if (kUseBakerReadBarrier) {
373 // This release fence makes the field updates in the above loop visible before allowing mutator
374 // getting access to immune objects without graying it first.
375 updated_all_immune_objects_.StoreRelease(true);
376 // Now whiten immune objects concurrently accessed and grayed by mutators. We can't do this in
377 // the above loop because we would incorrectly disable the read barrier by whitening an object
378 // which may point to an unscanned, white object, breaking the to-space invariant.
379 //
380 // Make sure no mutators are in the middle of marking an immune object before whitening immune
381 // objects.
382 IssueEmptyCheckpoint();
383 MutexLock mu(Thread::Current(), immune_gray_stack_lock_);
384 if (kVerboseMode) {
385 LOG(INFO) << "immune gray stack size=" << immune_gray_stack_.size();
386 }
387 for (mirror::Object* obj : immune_gray_stack_) {
388 DCHECK(obj->GetReadBarrierPointer() == ReadBarrier::GrayPtr());
389 bool success = obj->AtomicSetReadBarrierPointer(ReadBarrier::GrayPtr(),
390 ReadBarrier::WhitePtr());
391 DCHECK(success);
392 }
393 immune_gray_stack_.clear();
394 }
395
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800396 {
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -0700397 TimingLogger::ScopedTiming split2("VisitConcurrentRoots", GetTimings());
398 Runtime::Current()->VisitConcurrentRoots(this, kVisitRootFlagAllRoots);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800399 }
400 {
401 // TODO: don't visit the transaction roots if it's not active.
402 TimingLogger::ScopedTiming split5("VisitNonThreadRoots", GetTimings());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700403 Runtime::Current()->VisitNonThreadRoots(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800404 }
405
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800406 Thread* self = Thread::Current();
407 {
Mathieu Chartiera6b1ead2015-10-06 10:32:38 -0700408 TimingLogger::ScopedTiming split7("ProcessMarkStack", GetTimings());
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700409 // We transition through three mark stack modes (thread-local, shared, GC-exclusive). The
410 // primary reasons are the fact that we need to use a checkpoint to process thread-local mark
411 // stacks, but after we disable weak refs accesses, we can't use a checkpoint due to a deadlock
412 // issue because running threads potentially blocking at WaitHoldingLocks, and that once we
413 // reach the point where we process weak references, we can avoid using a lock when accessing
414 // the GC mark stack, which makes mark stack processing more efficient.
415
416 // Process the mark stack once in the thread local stack mode. This marks most of the live
417 // objects, aside from weak ref accesses with read barriers (Reference::GetReferent() and system
418 // weaks) that may happen concurrently while we processing the mark stack and newly mark/gray
419 // objects and push refs on the mark stack.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800420 ProcessMarkStack();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700421 // Switch to the shared mark stack mode. That is, revoke and process thread-local mark stacks
422 // for the last time before transitioning to the shared mark stack mode, which would process new
423 // refs that may have been concurrently pushed onto the mark stack during the ProcessMarkStack()
424 // call above. At the same time, disable weak ref accesses using a per-thread flag. It's
425 // important to do these together in a single checkpoint so that we can ensure that mutators
426 // won't newly gray objects and push new refs onto the mark stack due to weak ref accesses and
427 // mutators safely transition to the shared mark stack mode (without leaving unprocessed refs on
428 // the thread-local mark stacks), without a race. This is why we use a thread-local weak ref
429 // access flag Thread::tls32_.weak_ref_access_enabled_ instead of the global ones.
430 SwitchToSharedMarkStackMode();
431 CHECK(!self->GetWeakRefAccessEnabled());
432 // Now that weak refs accesses are disabled, once we exhaust the shared mark stack again here
433 // (which may be non-empty if there were refs found on thread-local mark stacks during the above
434 // SwitchToSharedMarkStackMode() call), we won't have new refs to process, that is, mutators
435 // (via read barriers) have no way to produce any more refs to process. Marking converges once
436 // before we process weak refs below.
437 ProcessMarkStack();
438 CheckEmptyMarkStack();
439 // Switch to the GC exclusive mark stack mode so that we can process the mark stack without a
440 // lock from this point on.
441 SwitchToGcExclusiveMarkStackMode();
442 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800443 if (kVerboseMode) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800444 LOG(INFO) << "ProcessReferences";
445 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700446 // Process weak references. This may produce new refs to process and have them processed via
Mathieu Chartier97509952015-07-13 14:35:43 -0700447 // ProcessMarkStack (in the GC exclusive mark stack mode).
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700448 ProcessReferences(self);
449 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800450 if (kVerboseMode) {
451 LOG(INFO) << "SweepSystemWeaks";
452 }
453 SweepSystemWeaks(self);
454 if (kVerboseMode) {
455 LOG(INFO) << "SweepSystemWeaks done";
456 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700457 // Process the mark stack here one last time because the above SweepSystemWeaks() call may have
458 // marked some objects (strings alive) as hash_set::Erase() can call the hash function for
459 // arbitrary elements in the weak intern table in InternTable::Table::SweepWeaks().
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800460 ProcessMarkStack();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700461 CheckEmptyMarkStack();
462 // Re-enable weak ref accesses.
463 ReenableWeakRefAccess(self);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -0700464 // Free data for class loaders that we unloaded.
465 Runtime::Current()->GetClassLinker()->CleanupClassLoaders();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700466 // Marking is done. Disable marking.
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700467 DisableMarking();
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800468 if (kUseBakerReadBarrier) {
469 ProcessFalseGrayStack();
470 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700471 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800472 }
473
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700474 CHECK(weak_ref_access_enabled_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800475 if (kVerboseMode) {
476 LOG(INFO) << "GC end of MarkingPhase";
477 }
478}
479
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700480void ConcurrentCopying::ReenableWeakRefAccess(Thread* self) {
481 if (kVerboseMode) {
482 LOG(INFO) << "ReenableWeakRefAccess";
483 }
484 weak_ref_access_enabled_.StoreRelaxed(true); // This is for new threads.
485 QuasiAtomic::ThreadFenceForConstructor();
486 // Iterate all threads (don't need to or can't use a checkpoint) and re-enable weak ref access.
487 {
488 MutexLock mu(self, *Locks::thread_list_lock_);
489 std::list<Thread*> thread_list = Runtime::Current()->GetThreadList()->GetList();
490 for (Thread* thread : thread_list) {
491 thread->SetWeakRefAccessEnabled(true);
492 }
493 }
494 // Unblock blocking threads.
495 GetHeap()->GetReferenceProcessor()->BroadcastForSlowPath(self);
496 Runtime::Current()->BroadcastForNewSystemWeaks();
497}
498
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700499class ConcurrentCopying::DisableMarkingCheckpoint : public Closure {
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700500 public:
501 explicit DisableMarkingCheckpoint(ConcurrentCopying* concurrent_copying)
502 : concurrent_copying_(concurrent_copying) {
503 }
504
505 void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
506 // Note: self is not necessarily equal to thread since thread may be suspended.
507 Thread* self = Thread::Current();
508 DCHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
509 << thread->GetState() << " thread " << thread << " self " << self;
510 // Disable the thread-local is_gc_marking flag.
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -0700511 // Note a thread that has just started right before this checkpoint may have already this flag
512 // set to false, which is ok.
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700513 thread->SetIsGcMarking(false);
514 // If thread is a running mutator, then act on behalf of the garbage collector.
515 // See the code in ThreadList::RunCheckpoint.
Mathieu Chartier10d25082015-10-28 18:36:09 -0700516 concurrent_copying_->GetBarrier().Pass(self);
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700517 }
518
519 private:
520 ConcurrentCopying* const concurrent_copying_;
521};
522
523void ConcurrentCopying::IssueDisableMarkingCheckpoint() {
524 Thread* self = Thread::Current();
525 DisableMarkingCheckpoint check_point(this);
526 ThreadList* thread_list = Runtime::Current()->GetThreadList();
527 gc_barrier_->Init(self, 0);
528 size_t barrier_count = thread_list->RunCheckpoint(&check_point);
529 // If there are no threads to wait which implies that all the checkpoint functions are finished,
530 // then no need to release the mutator lock.
531 if (barrier_count == 0) {
532 return;
533 }
534 // Release locks then wait for all mutator threads to pass the barrier.
535 Locks::mutator_lock_->SharedUnlock(self);
536 {
537 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
538 gc_barrier_->Increment(self, barrier_count);
539 }
540 Locks::mutator_lock_->SharedLock(self);
541}
542
543void ConcurrentCopying::DisableMarking() {
544 // Change the global is_marking flag to false. Do a fence before doing a checkpoint to update the
545 // thread-local flags so that a new thread starting up will get the correct is_marking flag.
546 is_marking_ = false;
547 QuasiAtomic::ThreadFenceForConstructor();
548 // Use a checkpoint to turn off the thread-local is_gc_marking flags and to ensure no threads are
549 // still in the middle of a read barrier which may have a from-space ref cached in a local
550 // variable.
551 IssueDisableMarkingCheckpoint();
552 if (kUseTableLookupReadBarrier) {
553 heap_->rb_table_->ClearAll();
554 DCHECK(heap_->rb_table_->IsAllCleared());
555 }
556 is_mark_stack_push_disallowed_.StoreSequentiallyConsistent(1);
557 mark_stack_mode_.StoreSequentiallyConsistent(kMarkStackModeOff);
558}
559
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800560void ConcurrentCopying::PushOntoFalseGrayStack(mirror::Object* ref) {
561 CHECK(kUseBakerReadBarrier);
562 DCHECK(ref != nullptr);
563 MutexLock mu(Thread::Current(), mark_stack_lock_);
564 false_gray_stack_.push_back(ref);
565}
566
567void ConcurrentCopying::ProcessFalseGrayStack() {
568 CHECK(kUseBakerReadBarrier);
569 // Change the objects on the false gray stack from gray to white.
570 MutexLock mu(Thread::Current(), mark_stack_lock_);
571 for (mirror::Object* obj : false_gray_stack_) {
572 DCHECK(IsMarked(obj));
573 // The object could be white here if a thread got preempted after a success at the
574 // AtomicSetReadBarrierPointer in Mark(), GC started marking through it (but not finished so
575 // still gray), and the thread ran to register it onto the false gray stack.
576 if (obj->GetReadBarrierPointer() == ReadBarrier::GrayPtr()) {
577 bool success = obj->AtomicSetReadBarrierPointer(ReadBarrier::GrayPtr(),
578 ReadBarrier::WhitePtr());
579 DCHECK(success);
580 }
581 }
582 false_gray_stack_.clear();
583}
584
585
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800586void ConcurrentCopying::IssueEmptyCheckpoint() {
587 Thread* self = Thread::Current();
588 EmptyCheckpoint check_point(this);
589 ThreadList* thread_list = Runtime::Current()->GetThreadList();
590 gc_barrier_->Init(self, 0);
591 size_t barrier_count = thread_list->RunCheckpoint(&check_point);
Lei Lidd9943d2015-02-02 14:24:44 +0800592 // If there are no threads to wait which implys that all the checkpoint functions are finished,
593 // then no need to release the mutator lock.
594 if (barrier_count == 0) {
595 return;
596 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800597 // Release locks then wait for all mutator threads to pass the barrier.
598 Locks::mutator_lock_->SharedUnlock(self);
599 {
600 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
601 gc_barrier_->Increment(self, barrier_count);
602 }
603 Locks::mutator_lock_->SharedLock(self);
604}
605
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -0700606void ConcurrentCopying::ExpandGcMarkStack() {
607 DCHECK(gc_mark_stack_->IsFull());
608 const size_t new_size = gc_mark_stack_->Capacity() * 2;
609 std::vector<StackReference<mirror::Object>> temp(gc_mark_stack_->Begin(),
610 gc_mark_stack_->End());
611 gc_mark_stack_->Resize(new_size);
612 for (auto& ref : temp) {
613 gc_mark_stack_->PushBack(ref.AsMirrorPtr());
614 }
615 DCHECK(!gc_mark_stack_->IsFull());
616}
617
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800618void ConcurrentCopying::PushOntoMarkStack(mirror::Object* to_ref) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700619 CHECK_EQ(is_mark_stack_push_disallowed_.LoadRelaxed(), 0)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800620 << " " << to_ref << " " << PrettyTypeOf(to_ref);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700621 Thread* self = Thread::Current(); // TODO: pass self as an argument from call sites?
622 CHECK(thread_running_gc_ != nullptr);
623 MarkStackMode mark_stack_mode = mark_stack_mode_.LoadRelaxed();
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -0700624 if (LIKELY(mark_stack_mode == kMarkStackModeThreadLocal)) {
625 if (LIKELY(self == thread_running_gc_)) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700626 // If GC-running thread, use the GC mark stack instead of a thread-local mark stack.
627 CHECK(self->GetThreadLocalMarkStack() == nullptr);
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -0700628 if (UNLIKELY(gc_mark_stack_->IsFull())) {
629 ExpandGcMarkStack();
630 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700631 gc_mark_stack_->PushBack(to_ref);
632 } else {
633 // Otherwise, use a thread-local mark stack.
634 accounting::AtomicStack<mirror::Object>* tl_mark_stack = self->GetThreadLocalMarkStack();
635 if (UNLIKELY(tl_mark_stack == nullptr || tl_mark_stack->IsFull())) {
636 MutexLock mu(self, mark_stack_lock_);
637 // Get a new thread local mark stack.
638 accounting::AtomicStack<mirror::Object>* new_tl_mark_stack;
639 if (!pooled_mark_stacks_.empty()) {
640 // Use a pooled mark stack.
641 new_tl_mark_stack = pooled_mark_stacks_.back();
642 pooled_mark_stacks_.pop_back();
643 } else {
644 // None pooled. Create a new one.
645 new_tl_mark_stack =
646 accounting::AtomicStack<mirror::Object>::Create(
647 "thread local mark stack", 4 * KB, 4 * KB);
648 }
649 DCHECK(new_tl_mark_stack != nullptr);
650 DCHECK(new_tl_mark_stack->IsEmpty());
651 new_tl_mark_stack->PushBack(to_ref);
652 self->SetThreadLocalMarkStack(new_tl_mark_stack);
653 if (tl_mark_stack != nullptr) {
654 // Store the old full stack into a vector.
655 revoked_mark_stacks_.push_back(tl_mark_stack);
656 }
657 } else {
658 tl_mark_stack->PushBack(to_ref);
659 }
660 }
661 } else if (mark_stack_mode == kMarkStackModeShared) {
662 // Access the shared GC mark stack with a lock.
663 MutexLock mu(self, mark_stack_lock_);
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -0700664 if (UNLIKELY(gc_mark_stack_->IsFull())) {
665 ExpandGcMarkStack();
666 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700667 gc_mark_stack_->PushBack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800668 } else {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700669 CHECK_EQ(static_cast<uint32_t>(mark_stack_mode),
Hiroshi Yamauchifa755182015-09-30 20:12:11 -0700670 static_cast<uint32_t>(kMarkStackModeGcExclusive))
671 << "ref=" << to_ref
672 << " self->gc_marking=" << self->GetIsGcMarking()
673 << " cc->is_marking=" << is_marking_;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700674 CHECK(self == thread_running_gc_)
675 << "Only GC-running thread should access the mark stack "
676 << "in the GC exclusive mark stack mode";
677 // Access the GC mark stack without a lock.
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -0700678 if (UNLIKELY(gc_mark_stack_->IsFull())) {
679 ExpandGcMarkStack();
680 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700681 gc_mark_stack_->PushBack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800682 }
683}
684
685accounting::ObjectStack* ConcurrentCopying::GetAllocationStack() {
686 return heap_->allocation_stack_.get();
687}
688
689accounting::ObjectStack* ConcurrentCopying::GetLiveStack() {
690 return heap_->live_stack_.get();
691}
692
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800693// The following visitors are used to verify that there's no references to the from-space left after
694// marking.
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700695class ConcurrentCopying::VerifyNoFromSpaceRefsVisitor : public SingleRootVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800696 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700697 explicit VerifyNoFromSpaceRefsVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800698 : collector_(collector) {}
699
700 void operator()(mirror::Object* ref) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700701 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800702 if (ref == nullptr) {
703 // OK.
704 return;
705 }
706 collector_->AssertToSpaceInvariant(nullptr, MemberOffset(0), ref);
707 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800708 CHECK(ref->GetReadBarrierPointer() == ReadBarrier::WhitePtr())
709 << "Ref " << ref << " " << PrettyTypeOf(ref)
710 << " has non-white rb_ptr " << ref->GetReadBarrierPointer();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800711 }
712 }
713
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700714 void VisitRoot(mirror::Object* root, const RootInfo& info ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -0700715 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800716 DCHECK(root != nullptr);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700717 operator()(root);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800718 }
719
720 private:
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700721 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800722};
723
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700724class ConcurrentCopying::VerifyNoFromSpaceRefsFieldVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800725 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700726 explicit VerifyNoFromSpaceRefsFieldVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800727 : collector_(collector) {}
728
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700729 void operator()(mirror::Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700730 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800731 mirror::Object* ref =
732 obj->GetFieldObject<mirror::Object, kDefaultVerifyFlags, kWithoutReadBarrier>(offset);
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700733 VerifyNoFromSpaceRefsVisitor visitor(collector_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800734 visitor(ref);
735 }
736 void operator()(mirror::Class* klass, mirror::Reference* ref) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700737 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800738 CHECK(klass->IsTypeOfReferenceClass());
739 this->operator()(ref, mirror::Reference::ReferentOffset(), false);
740 }
741
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700742 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
743 SHARED_REQUIRES(Locks::mutator_lock_) {
744 if (!root->IsNull()) {
745 VisitRoot(root);
746 }
747 }
748
749 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
750 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700751 VerifyNoFromSpaceRefsVisitor visitor(collector_);
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700752 visitor(root->AsMirrorPtr());
753 }
754
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800755 private:
Mathieu Chartier97509952015-07-13 14:35:43 -0700756 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800757};
758
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700759class ConcurrentCopying::VerifyNoFromSpaceRefsObjectVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800760 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700761 explicit VerifyNoFromSpaceRefsObjectVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800762 : collector_(collector) {}
763 void operator()(mirror::Object* obj) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700764 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800765 ObjectCallback(obj, collector_);
766 }
767 static void ObjectCallback(mirror::Object* obj, void *arg)
Mathieu Chartier90443472015-07-16 20:32:27 -0700768 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800769 CHECK(obj != nullptr);
770 ConcurrentCopying* collector = reinterpret_cast<ConcurrentCopying*>(arg);
771 space::RegionSpace* region_space = collector->RegionSpace();
772 CHECK(!region_space->IsInFromSpace(obj)) << "Scanning object " << obj << " in from space";
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700773 VerifyNoFromSpaceRefsFieldVisitor visitor(collector);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -0700774 obj->VisitReferences(visitor, visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800775 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800776 CHECK(obj->GetReadBarrierPointer() == ReadBarrier::WhitePtr())
777 << "obj=" << obj << " non-white rb_ptr " << obj->GetReadBarrierPointer();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800778 }
779 }
780
781 private:
782 ConcurrentCopying* const collector_;
783};
784
785// Verify there's no from-space references left after the marking phase.
786void ConcurrentCopying::VerifyNoFromSpaceReferences() {
787 Thread* self = Thread::Current();
788 DCHECK(Locks::mutator_lock_->IsExclusiveHeld(self));
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700789 // Verify all threads have is_gc_marking to be false
790 {
791 MutexLock mu(self, *Locks::thread_list_lock_);
792 std::list<Thread*> thread_list = Runtime::Current()->GetThreadList()->GetList();
793 for (Thread* thread : thread_list) {
794 CHECK(!thread->GetIsGcMarking());
795 }
796 }
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700797 VerifyNoFromSpaceRefsObjectVisitor visitor(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800798 // Roots.
799 {
800 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700801 VerifyNoFromSpaceRefsVisitor ref_visitor(this);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700802 Runtime::Current()->VisitRoots(&ref_visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800803 }
804 // The to-space.
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700805 region_space_->WalkToSpace(VerifyNoFromSpaceRefsObjectVisitor::ObjectCallback, this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800806 // Non-moving spaces.
807 {
808 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
809 heap_->GetMarkBitmap()->Visit(visitor);
810 }
811 // The alloc stack.
812 {
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700813 VerifyNoFromSpaceRefsVisitor ref_visitor(this);
Mathieu Chartiercb535da2015-01-23 13:50:03 -0800814 for (auto* it = heap_->allocation_stack_->Begin(), *end = heap_->allocation_stack_->End();
815 it < end; ++it) {
816 mirror::Object* const obj = it->AsMirrorPtr();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800817 if (obj != nullptr && obj->GetClass() != nullptr) {
818 // TODO: need to call this only if obj is alive?
819 ref_visitor(obj);
820 visitor(obj);
821 }
822 }
823 }
824 // TODO: LOS. But only refs in LOS are classes.
825}
826
827// The following visitors are used to assert the to-space invariant.
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700828class ConcurrentCopying::AssertToSpaceInvariantRefsVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800829 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700830 explicit AssertToSpaceInvariantRefsVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800831 : collector_(collector) {}
832
833 void operator()(mirror::Object* ref) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700834 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800835 if (ref == nullptr) {
836 // OK.
837 return;
838 }
839 collector_->AssertToSpaceInvariant(nullptr, MemberOffset(0), ref);
840 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800841
842 private:
Mathieu Chartier97509952015-07-13 14:35:43 -0700843 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800844};
845
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700846class ConcurrentCopying::AssertToSpaceInvariantFieldVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800847 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700848 explicit AssertToSpaceInvariantFieldVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800849 : collector_(collector) {}
850
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700851 void operator()(mirror::Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700852 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800853 mirror::Object* ref =
854 obj->GetFieldObject<mirror::Object, kDefaultVerifyFlags, kWithoutReadBarrier>(offset);
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700855 AssertToSpaceInvariantRefsVisitor visitor(collector_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800856 visitor(ref);
857 }
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700858 void operator()(mirror::Class* klass, mirror::Reference* ref ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700859 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800860 CHECK(klass->IsTypeOfReferenceClass());
861 }
862
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700863 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
864 SHARED_REQUIRES(Locks::mutator_lock_) {
865 if (!root->IsNull()) {
866 VisitRoot(root);
867 }
868 }
869
870 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
871 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700872 AssertToSpaceInvariantRefsVisitor visitor(collector_);
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700873 visitor(root->AsMirrorPtr());
874 }
875
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800876 private:
Mathieu Chartier97509952015-07-13 14:35:43 -0700877 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800878};
879
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700880class ConcurrentCopying::AssertToSpaceInvariantObjectVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800881 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700882 explicit AssertToSpaceInvariantObjectVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800883 : collector_(collector) {}
884 void operator()(mirror::Object* obj) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700885 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800886 ObjectCallback(obj, collector_);
887 }
888 static void ObjectCallback(mirror::Object* obj, void *arg)
Mathieu Chartier90443472015-07-16 20:32:27 -0700889 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800890 CHECK(obj != nullptr);
891 ConcurrentCopying* collector = reinterpret_cast<ConcurrentCopying*>(arg);
892 space::RegionSpace* region_space = collector->RegionSpace();
893 CHECK(!region_space->IsInFromSpace(obj)) << "Scanning object " << obj << " in from space";
894 collector->AssertToSpaceInvariant(nullptr, MemberOffset(0), obj);
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700895 AssertToSpaceInvariantFieldVisitor visitor(collector);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -0700896 obj->VisitReferences(visitor, visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800897 }
898
899 private:
Mathieu Chartier97509952015-07-13 14:35:43 -0700900 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800901};
902
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700903class ConcurrentCopying::RevokeThreadLocalMarkStackCheckpoint : public Closure {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700904 public:
Roland Levillain3887c462015-08-12 18:15:42 +0100905 RevokeThreadLocalMarkStackCheckpoint(ConcurrentCopying* concurrent_copying,
906 bool disable_weak_ref_access)
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700907 : concurrent_copying_(concurrent_copying),
908 disable_weak_ref_access_(disable_weak_ref_access) {
909 }
910
911 virtual void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
912 // Note: self is not necessarily equal to thread since thread may be suspended.
913 Thread* self = Thread::Current();
914 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
915 << thread->GetState() << " thread " << thread << " self " << self;
916 // Revoke thread local mark stacks.
917 accounting::AtomicStack<mirror::Object>* tl_mark_stack = thread->GetThreadLocalMarkStack();
918 if (tl_mark_stack != nullptr) {
919 MutexLock mu(self, concurrent_copying_->mark_stack_lock_);
920 concurrent_copying_->revoked_mark_stacks_.push_back(tl_mark_stack);
921 thread->SetThreadLocalMarkStack(nullptr);
922 }
923 // Disable weak ref access.
924 if (disable_weak_ref_access_) {
925 thread->SetWeakRefAccessEnabled(false);
926 }
927 // If thread is a running mutator, then act on behalf of the garbage collector.
928 // See the code in ThreadList::RunCheckpoint.
Mathieu Chartier10d25082015-10-28 18:36:09 -0700929 concurrent_copying_->GetBarrier().Pass(self);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700930 }
931
932 private:
933 ConcurrentCopying* const concurrent_copying_;
934 const bool disable_weak_ref_access_;
935};
936
937void ConcurrentCopying::RevokeThreadLocalMarkStacks(bool disable_weak_ref_access) {
938 Thread* self = Thread::Current();
939 RevokeThreadLocalMarkStackCheckpoint check_point(this, disable_weak_ref_access);
940 ThreadList* thread_list = Runtime::Current()->GetThreadList();
941 gc_barrier_->Init(self, 0);
942 size_t barrier_count = thread_list->RunCheckpoint(&check_point);
943 // If there are no threads to wait which implys that all the checkpoint functions are finished,
944 // then no need to release the mutator lock.
945 if (barrier_count == 0) {
946 return;
947 }
948 Locks::mutator_lock_->SharedUnlock(self);
949 {
950 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
951 gc_barrier_->Increment(self, barrier_count);
952 }
953 Locks::mutator_lock_->SharedLock(self);
954}
955
956void ConcurrentCopying::RevokeThreadLocalMarkStack(Thread* thread) {
957 Thread* self = Thread::Current();
958 CHECK_EQ(self, thread);
959 accounting::AtomicStack<mirror::Object>* tl_mark_stack = thread->GetThreadLocalMarkStack();
960 if (tl_mark_stack != nullptr) {
961 CHECK(is_marking_);
962 MutexLock mu(self, mark_stack_lock_);
963 revoked_mark_stacks_.push_back(tl_mark_stack);
964 thread->SetThreadLocalMarkStack(nullptr);
965 }
966}
967
968void ConcurrentCopying::ProcessMarkStack() {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800969 if (kVerboseMode) {
970 LOG(INFO) << "ProcessMarkStack. ";
971 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700972 bool empty_prev = false;
973 while (true) {
974 bool empty = ProcessMarkStackOnce();
975 if (empty_prev && empty) {
976 // Saw empty mark stack for a second time, done.
977 break;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800978 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700979 empty_prev = empty;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800980 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700981}
982
983bool ConcurrentCopying::ProcessMarkStackOnce() {
984 Thread* self = Thread::Current();
985 CHECK(thread_running_gc_ != nullptr);
986 CHECK(self == thread_running_gc_);
987 CHECK(self->GetThreadLocalMarkStack() == nullptr);
988 size_t count = 0;
989 MarkStackMode mark_stack_mode = mark_stack_mode_.LoadRelaxed();
990 if (mark_stack_mode == kMarkStackModeThreadLocal) {
991 // Process the thread-local mark stacks and the GC mark stack.
992 count += ProcessThreadLocalMarkStacks(false);
993 while (!gc_mark_stack_->IsEmpty()) {
994 mirror::Object* to_ref = gc_mark_stack_->PopBack();
995 ProcessMarkStackRef(to_ref);
996 ++count;
997 }
998 gc_mark_stack_->Reset();
999 } else if (mark_stack_mode == kMarkStackModeShared) {
1000 // Process the shared GC mark stack with a lock.
1001 {
1002 MutexLock mu(self, mark_stack_lock_);
1003 CHECK(revoked_mark_stacks_.empty());
1004 }
1005 while (true) {
1006 std::vector<mirror::Object*> refs;
1007 {
1008 // Copy refs with lock. Note the number of refs should be small.
1009 MutexLock mu(self, mark_stack_lock_);
1010 if (gc_mark_stack_->IsEmpty()) {
1011 break;
1012 }
1013 for (StackReference<mirror::Object>* p = gc_mark_stack_->Begin();
1014 p != gc_mark_stack_->End(); ++p) {
1015 refs.push_back(p->AsMirrorPtr());
1016 }
1017 gc_mark_stack_->Reset();
1018 }
1019 for (mirror::Object* ref : refs) {
1020 ProcessMarkStackRef(ref);
1021 ++count;
1022 }
1023 }
1024 } else {
1025 CHECK_EQ(static_cast<uint32_t>(mark_stack_mode),
1026 static_cast<uint32_t>(kMarkStackModeGcExclusive));
1027 {
1028 MutexLock mu(self, mark_stack_lock_);
1029 CHECK(revoked_mark_stacks_.empty());
1030 }
1031 // Process the GC mark stack in the exclusive mode. No need to take the lock.
1032 while (!gc_mark_stack_->IsEmpty()) {
1033 mirror::Object* to_ref = gc_mark_stack_->PopBack();
1034 ProcessMarkStackRef(to_ref);
1035 ++count;
1036 }
1037 gc_mark_stack_->Reset();
1038 }
1039
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001040 // Return true if the stack was empty.
1041 return count == 0;
1042}
1043
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001044size_t ConcurrentCopying::ProcessThreadLocalMarkStacks(bool disable_weak_ref_access) {
1045 // Run a checkpoint to collect all thread local mark stacks and iterate over them all.
1046 RevokeThreadLocalMarkStacks(disable_weak_ref_access);
1047 size_t count = 0;
1048 std::vector<accounting::AtomicStack<mirror::Object>*> mark_stacks;
1049 {
1050 MutexLock mu(Thread::Current(), mark_stack_lock_);
1051 // Make a copy of the mark stack vector.
1052 mark_stacks = revoked_mark_stacks_;
1053 revoked_mark_stacks_.clear();
1054 }
1055 for (accounting::AtomicStack<mirror::Object>* mark_stack : mark_stacks) {
1056 for (StackReference<mirror::Object>* p = mark_stack->Begin(); p != mark_stack->End(); ++p) {
1057 mirror::Object* to_ref = p->AsMirrorPtr();
1058 ProcessMarkStackRef(to_ref);
1059 ++count;
1060 }
1061 {
1062 MutexLock mu(Thread::Current(), mark_stack_lock_);
1063 if (pooled_mark_stacks_.size() >= kMarkStackPoolSize) {
1064 // The pool has enough. Delete it.
1065 delete mark_stack;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001066 } else {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001067 // Otherwise, put it into the pool for later reuse.
1068 mark_stack->Reset();
1069 pooled_mark_stacks_.push_back(mark_stack);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001070 }
1071 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001072 }
1073 return count;
1074}
1075
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001076inline void ConcurrentCopying::ProcessMarkStackRef(mirror::Object* to_ref) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001077 DCHECK(!region_space_->IsInFromSpace(to_ref));
1078 if (kUseBakerReadBarrier) {
1079 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr())
1080 << " " << to_ref << " " << to_ref->GetReadBarrierPointer()
1081 << " is_marked=" << IsMarked(to_ref);
1082 }
1083 // Scan ref fields.
1084 Scan(to_ref);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001085 if (kUseBakerReadBarrier) {
1086 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr())
1087 << " " << to_ref << " " << to_ref->GetReadBarrierPointer()
1088 << " is_marked=" << IsMarked(to_ref);
1089 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001090#ifdef USE_BAKER_OR_BROOKS_READ_BARRIER
1091 if (UNLIKELY((to_ref->GetClass<kVerifyNone, kWithoutReadBarrier>()->IsTypeOfReferenceClass() &&
1092 to_ref->AsReference()->GetReferent<kWithoutReadBarrier>() != nullptr &&
1093 !IsInToSpace(to_ref->AsReference()->GetReferent<kWithoutReadBarrier>())))) {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001094 // Leave this reference gray in the queue so that GetReferent() will trigger a read barrier. We
1095 // will change it to white later in ReferenceQueue::DequeuePendingReference().
Richard Uhlere3627402016-02-02 13:36:55 -08001096 DCHECK(to_ref->AsReference()->GetPendingNext() != nullptr) << "Left unenqueued ref gray " << to_ref;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001097 } else {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001098 // We may occasionally leave a reference white in the queue if its referent happens to be
1099 // concurrently marked after the Scan() call above has enqueued the Reference, in which case the
1100 // above IsInToSpace() evaluates to true and we change the color from gray to white here in this
1101 // else block.
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001102 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001103 bool success = to_ref->AtomicSetReadBarrierPointer</*kCasRelease*/true>(
1104 ReadBarrier::GrayPtr(),
1105 ReadBarrier::WhitePtr());
1106 DCHECK(success) << "Must succeed as we won the race.";
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001107 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001108 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001109#else
1110 DCHECK(!kUseBakerReadBarrier);
1111#endif
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001112
1113 if (region_space_->IsInUnevacFromSpace(to_ref)) {
1114 // Add to the live bytes per unevacuated from space. Note this code is always run by the
1115 // GC-running thread (no synchronization required).
1116 DCHECK(region_space_bitmap_->Test(to_ref));
1117 // Disable the read barrier in SizeOf for performance, which is safe.
1118 size_t obj_size = to_ref->SizeOf<kDefaultVerifyFlags, kWithoutReadBarrier>();
1119 size_t alloc_size = RoundUp(obj_size, space::RegionSpace::kAlignment);
1120 region_space_->AddLiveBytes(to_ref, alloc_size);
1121 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001122 if (ReadBarrier::kEnableToSpaceInvariantChecks || kIsDebugBuild) {
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001123 AssertToSpaceInvariantObjectVisitor visitor(this);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001124 visitor(to_ref);
1125 }
1126}
1127
1128void ConcurrentCopying::SwitchToSharedMarkStackMode() {
1129 Thread* self = Thread::Current();
1130 CHECK(thread_running_gc_ != nullptr);
1131 CHECK_EQ(self, thread_running_gc_);
1132 CHECK(self->GetThreadLocalMarkStack() == nullptr);
1133 MarkStackMode before_mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1134 CHECK_EQ(static_cast<uint32_t>(before_mark_stack_mode),
1135 static_cast<uint32_t>(kMarkStackModeThreadLocal));
1136 mark_stack_mode_.StoreRelaxed(kMarkStackModeShared);
1137 CHECK(weak_ref_access_enabled_.LoadRelaxed());
1138 weak_ref_access_enabled_.StoreRelaxed(false);
1139 QuasiAtomic::ThreadFenceForConstructor();
1140 // Process the thread local mark stacks one last time after switching to the shared mark stack
1141 // mode and disable weak ref accesses.
1142 ProcessThreadLocalMarkStacks(true);
1143 if (kVerboseMode) {
1144 LOG(INFO) << "Switched to shared mark stack mode and disabled weak ref access";
1145 }
1146}
1147
1148void ConcurrentCopying::SwitchToGcExclusiveMarkStackMode() {
1149 Thread* self = Thread::Current();
1150 CHECK(thread_running_gc_ != nullptr);
1151 CHECK_EQ(self, thread_running_gc_);
1152 CHECK(self->GetThreadLocalMarkStack() == nullptr);
1153 MarkStackMode before_mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1154 CHECK_EQ(static_cast<uint32_t>(before_mark_stack_mode),
1155 static_cast<uint32_t>(kMarkStackModeShared));
1156 mark_stack_mode_.StoreRelaxed(kMarkStackModeGcExclusive);
1157 QuasiAtomic::ThreadFenceForConstructor();
1158 if (kVerboseMode) {
1159 LOG(INFO) << "Switched to GC exclusive mark stack mode";
1160 }
1161}
1162
1163void ConcurrentCopying::CheckEmptyMarkStack() {
1164 Thread* self = Thread::Current();
1165 CHECK(thread_running_gc_ != nullptr);
1166 CHECK_EQ(self, thread_running_gc_);
1167 CHECK(self->GetThreadLocalMarkStack() == nullptr);
1168 MarkStackMode mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1169 if (mark_stack_mode == kMarkStackModeThreadLocal) {
1170 // Thread-local mark stack mode.
1171 RevokeThreadLocalMarkStacks(false);
1172 MutexLock mu(Thread::Current(), mark_stack_lock_);
1173 if (!revoked_mark_stacks_.empty()) {
1174 for (accounting::AtomicStack<mirror::Object>* mark_stack : revoked_mark_stacks_) {
1175 while (!mark_stack->IsEmpty()) {
1176 mirror::Object* obj = mark_stack->PopBack();
1177 if (kUseBakerReadBarrier) {
1178 mirror::Object* rb_ptr = obj->GetReadBarrierPointer();
1179 LOG(INFO) << "On mark queue : " << obj << " " << PrettyTypeOf(obj) << " rb_ptr=" << rb_ptr
1180 << " is_marked=" << IsMarked(obj);
1181 } else {
1182 LOG(INFO) << "On mark queue : " << obj << " " << PrettyTypeOf(obj)
1183 << " is_marked=" << IsMarked(obj);
1184 }
1185 }
1186 }
1187 LOG(FATAL) << "mark stack is not empty";
1188 }
1189 } else {
1190 // Shared, GC-exclusive, or off.
1191 MutexLock mu(Thread::Current(), mark_stack_lock_);
1192 CHECK(gc_mark_stack_->IsEmpty());
1193 CHECK(revoked_mark_stacks_.empty());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001194 }
1195}
1196
1197void ConcurrentCopying::SweepSystemWeaks(Thread* self) {
1198 TimingLogger::ScopedTiming split("SweepSystemWeaks", GetTimings());
1199 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier97509952015-07-13 14:35:43 -07001200 Runtime::Current()->SweepSystemWeaks(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001201}
1202
1203void ConcurrentCopying::Sweep(bool swap_bitmaps) {
1204 {
1205 TimingLogger::ScopedTiming t("MarkStackAsLive", GetTimings());
1206 accounting::ObjectStack* live_stack = heap_->GetLiveStack();
1207 if (kEnableFromSpaceAccountingCheck) {
1208 CHECK_GE(live_stack_freeze_size_, live_stack->Size());
1209 }
1210 heap_->MarkAllocStackAsLive(live_stack);
1211 live_stack->Reset();
1212 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001213 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001214 TimingLogger::ScopedTiming split("Sweep", GetTimings());
1215 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
1216 if (space->IsContinuousMemMapAllocSpace()) {
1217 space::ContinuousMemMapAllocSpace* alloc_space = space->AsContinuousMemMapAllocSpace();
Mathieu Chartier763a31e2015-11-16 16:05:55 -08001218 if (space == region_space_ || immune_spaces_.ContainsSpace(space)) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001219 continue;
1220 }
1221 TimingLogger::ScopedTiming split2(
1222 alloc_space->IsZygoteSpace() ? "SweepZygoteSpace" : "SweepAllocSpace", GetTimings());
1223 RecordFree(alloc_space->Sweep(swap_bitmaps));
1224 }
1225 }
1226 SweepLargeObjects(swap_bitmaps);
1227}
1228
1229void ConcurrentCopying::SweepLargeObjects(bool swap_bitmaps) {
1230 TimingLogger::ScopedTiming split("SweepLargeObjects", GetTimings());
1231 RecordFreeLOS(heap_->GetLargeObjectsSpace()->Sweep(swap_bitmaps));
1232}
1233
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001234void ConcurrentCopying::ReclaimPhase() {
1235 TimingLogger::ScopedTiming split("ReclaimPhase", GetTimings());
1236 if (kVerboseMode) {
1237 LOG(INFO) << "GC ReclaimPhase";
1238 }
1239 Thread* self = Thread::Current();
1240
1241 {
1242 // Double-check that the mark stack is empty.
1243 // Note: need to set this after VerifyNoFromSpaceRef().
1244 is_asserting_to_space_invariant_ = false;
1245 QuasiAtomic::ThreadFenceForConstructor();
1246 if (kVerboseMode) {
1247 LOG(INFO) << "Issue an empty check point. ";
1248 }
1249 IssueEmptyCheckpoint();
1250 // Disable the check.
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001251 is_mark_stack_push_disallowed_.StoreSequentiallyConsistent(0);
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001252 if (kUseBakerReadBarrier) {
1253 updated_all_immune_objects_.StoreSequentiallyConsistent(false);
1254 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001255 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001256 }
1257
1258 {
1259 // Record freed objects.
1260 TimingLogger::ScopedTiming split2("RecordFree", GetTimings());
1261 // Don't include thread-locals that are in the to-space.
1262 uint64_t from_bytes = region_space_->GetBytesAllocatedInFromSpace();
1263 uint64_t from_objects = region_space_->GetObjectsAllocatedInFromSpace();
1264 uint64_t unevac_from_bytes = region_space_->GetBytesAllocatedInUnevacFromSpace();
1265 uint64_t unevac_from_objects = region_space_->GetObjectsAllocatedInUnevacFromSpace();
1266 uint64_t to_bytes = bytes_moved_.LoadSequentiallyConsistent();
1267 uint64_t to_objects = objects_moved_.LoadSequentiallyConsistent();
1268 if (kEnableFromSpaceAccountingCheck) {
1269 CHECK_EQ(from_space_num_objects_at_first_pause_, from_objects + unevac_from_objects);
1270 CHECK_EQ(from_space_num_bytes_at_first_pause_, from_bytes + unevac_from_bytes);
1271 }
1272 CHECK_LE(to_objects, from_objects);
1273 CHECK_LE(to_bytes, from_bytes);
1274 int64_t freed_bytes = from_bytes - to_bytes;
1275 int64_t freed_objects = from_objects - to_objects;
1276 if (kVerboseMode) {
1277 LOG(INFO) << "RecordFree:"
1278 << " from_bytes=" << from_bytes << " from_objects=" << from_objects
1279 << " unevac_from_bytes=" << unevac_from_bytes << " unevac_from_objects=" << unevac_from_objects
1280 << " to_bytes=" << to_bytes << " to_objects=" << to_objects
1281 << " freed_bytes=" << freed_bytes << " freed_objects=" << freed_objects
1282 << " from_space size=" << region_space_->FromSpaceSize()
1283 << " unevac_from_space size=" << region_space_->UnevacFromSpaceSize()
1284 << " to_space size=" << region_space_->ToSpaceSize();
1285 LOG(INFO) << "(before) num_bytes_allocated=" << heap_->num_bytes_allocated_.LoadSequentiallyConsistent();
1286 }
1287 RecordFree(ObjectBytePair(freed_objects, freed_bytes));
1288 if (kVerboseMode) {
1289 LOG(INFO) << "(after) num_bytes_allocated=" << heap_->num_bytes_allocated_.LoadSequentiallyConsistent();
1290 }
1291 }
1292
1293 {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001294 TimingLogger::ScopedTiming split4("ClearFromSpace", GetTimings());
1295 region_space_->ClearFromSpace();
1296 }
1297
1298 {
1299 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001300 Sweep(false);
1301 SwapBitmaps();
1302 heap_->UnBindBitmaps();
1303
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001304 // Delete the region bitmap.
1305 DCHECK(region_space_bitmap_ != nullptr);
1306 delete region_space_bitmap_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001307 region_space_bitmap_ = nullptr;
1308 }
1309
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001310 CheckEmptyMarkStack();
1311
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001312 if (kVerboseMode) {
1313 LOG(INFO) << "GC end of ReclaimPhase";
1314 }
1315}
1316
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001317// Assert the to-space invariant.
1318void ConcurrentCopying::AssertToSpaceInvariant(mirror::Object* obj, MemberOffset offset,
1319 mirror::Object* ref) {
1320 CHECK(heap_->collector_type_ == kCollectorTypeCC) << static_cast<size_t>(heap_->collector_type_);
1321 if (is_asserting_to_space_invariant_) {
1322 if (region_space_->IsInToSpace(ref)) {
1323 // OK.
1324 return;
1325 } else if (region_space_->IsInUnevacFromSpace(ref)) {
1326 CHECK(region_space_bitmap_->Test(ref)) << ref;
1327 } else if (region_space_->IsInFromSpace(ref)) {
1328 // Not OK. Do extra logging.
1329 if (obj != nullptr) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001330 LogFromSpaceRefHolder(obj, offset);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001331 }
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001332 ref->GetLockWord(false).Dump(LOG(INTERNAL_FATAL));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001333 CHECK(false) << "Found from-space ref " << ref << " " << PrettyTypeOf(ref);
1334 } else {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001335 AssertToSpaceInvariantInNonMovingSpace(obj, ref);
1336 }
1337 }
1338}
1339
1340class RootPrinter {
1341 public:
1342 RootPrinter() { }
1343
1344 template <class MirrorType>
1345 ALWAYS_INLINE void VisitRootIfNonNull(mirror::CompressedReference<MirrorType>* root)
Mathieu Chartier90443472015-07-16 20:32:27 -07001346 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001347 if (!root->IsNull()) {
1348 VisitRoot(root);
1349 }
1350 }
1351
1352 template <class MirrorType>
1353 void VisitRoot(mirror::Object** root)
Mathieu Chartier90443472015-07-16 20:32:27 -07001354 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001355 LOG(INTERNAL_FATAL) << "root=" << root << " ref=" << *root;
1356 }
1357
1358 template <class MirrorType>
1359 void VisitRoot(mirror::CompressedReference<MirrorType>* root)
Mathieu Chartier90443472015-07-16 20:32:27 -07001360 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001361 LOG(INTERNAL_FATAL) << "root=" << root << " ref=" << root->AsMirrorPtr();
1362 }
1363};
1364
1365void ConcurrentCopying::AssertToSpaceInvariant(GcRootSource* gc_root_source,
1366 mirror::Object* ref) {
1367 CHECK(heap_->collector_type_ == kCollectorTypeCC) << static_cast<size_t>(heap_->collector_type_);
1368 if (is_asserting_to_space_invariant_) {
1369 if (region_space_->IsInToSpace(ref)) {
1370 // OK.
1371 return;
1372 } else if (region_space_->IsInUnevacFromSpace(ref)) {
1373 CHECK(region_space_bitmap_->Test(ref)) << ref;
1374 } else if (region_space_->IsInFromSpace(ref)) {
1375 // Not OK. Do extra logging.
1376 if (gc_root_source == nullptr) {
1377 // No info.
1378 } else if (gc_root_source->HasArtField()) {
1379 ArtField* field = gc_root_source->GetArtField();
1380 LOG(INTERNAL_FATAL) << "gc root in field " << field << " " << PrettyField(field);
1381 RootPrinter root_printer;
1382 field->VisitRoots(root_printer);
1383 } else if (gc_root_source->HasArtMethod()) {
1384 ArtMethod* method = gc_root_source->GetArtMethod();
1385 LOG(INTERNAL_FATAL) << "gc root in method " << method << " " << PrettyMethod(method);
1386 RootPrinter root_printer;
Mathieu Chartier1147b9b2015-09-14 18:50:08 -07001387 method->VisitRoots(root_printer, sizeof(void*));
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001388 }
1389 ref->GetLockWord(false).Dump(LOG(INTERNAL_FATAL));
1390 region_space_->DumpNonFreeRegions(LOG(INTERNAL_FATAL));
1391 PrintFileToLog("/proc/self/maps", LogSeverity::INTERNAL_FATAL);
1392 MemMap::DumpMaps(LOG(INTERNAL_FATAL), true);
1393 CHECK(false) << "Found from-space ref " << ref << " " << PrettyTypeOf(ref);
1394 } else {
1395 AssertToSpaceInvariantInNonMovingSpace(nullptr, ref);
1396 }
1397 }
1398}
1399
1400void ConcurrentCopying::LogFromSpaceRefHolder(mirror::Object* obj, MemberOffset offset) {
1401 if (kUseBakerReadBarrier) {
1402 LOG(INFO) << "holder=" << obj << " " << PrettyTypeOf(obj)
1403 << " holder rb_ptr=" << obj->GetReadBarrierPointer();
1404 } else {
1405 LOG(INFO) << "holder=" << obj << " " << PrettyTypeOf(obj);
1406 }
1407 if (region_space_->IsInFromSpace(obj)) {
1408 LOG(INFO) << "holder is in the from-space.";
1409 } else if (region_space_->IsInToSpace(obj)) {
1410 LOG(INFO) << "holder is in the to-space.";
1411 } else if (region_space_->IsInUnevacFromSpace(obj)) {
1412 LOG(INFO) << "holder is in the unevac from-space.";
1413 if (region_space_bitmap_->Test(obj)) {
1414 LOG(INFO) << "holder is marked in the region space bitmap.";
1415 } else {
1416 LOG(INFO) << "holder is not marked in the region space bitmap.";
1417 }
1418 } else {
1419 // In a non-moving space.
Mathieu Chartier763a31e2015-11-16 16:05:55 -08001420 if (immune_spaces_.ContainsObject(obj)) {
1421 LOG(INFO) << "holder is in an immune image or the zygote space.";
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001422 } else {
Mathieu Chartier763a31e2015-11-16 16:05:55 -08001423 LOG(INFO) << "holder is in a non-immune, non-moving (or main) space.";
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001424 accounting::ContinuousSpaceBitmap* mark_bitmap =
1425 heap_mark_bitmap_->GetContinuousSpaceBitmap(obj);
1426 accounting::LargeObjectBitmap* los_bitmap =
1427 heap_mark_bitmap_->GetLargeObjectBitmap(obj);
1428 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
1429 bool is_los = mark_bitmap == nullptr;
1430 if (!is_los && mark_bitmap->Test(obj)) {
1431 LOG(INFO) << "holder is marked in the mark bit map.";
1432 } else if (is_los && los_bitmap->Test(obj)) {
1433 LOG(INFO) << "holder is marked in the los bit map.";
1434 } else {
1435 // If ref is on the allocation stack, then it is considered
1436 // mark/alive (but not necessarily on the live stack.)
1437 if (IsOnAllocStack(obj)) {
1438 LOG(INFO) << "holder is on the alloc stack.";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001439 } else {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001440 LOG(INFO) << "holder is not marked or on the alloc stack.";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001441 }
1442 }
1443 }
1444 }
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001445 LOG(INFO) << "offset=" << offset.SizeValue();
1446}
1447
1448void ConcurrentCopying::AssertToSpaceInvariantInNonMovingSpace(mirror::Object* obj,
1449 mirror::Object* ref) {
1450 // In a non-moving spaces. Check that the ref is marked.
Mathieu Chartier763a31e2015-11-16 16:05:55 -08001451 if (immune_spaces_.ContainsObject(ref)) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001452 if (kUseBakerReadBarrier) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001453 // Immune object may not be gray if called from the GC.
1454 if (Thread::Current() == thread_running_gc_ && !gc_grays_immune_objects_) {
1455 return;
1456 }
1457 bool updated_all_immune_objects = updated_all_immune_objects_.LoadSequentiallyConsistent();
1458 CHECK(updated_all_immune_objects || ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr())
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001459 << "Unmarked immune space ref. obj=" << obj << " rb_ptr="
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001460 << (obj != nullptr ? obj->GetReadBarrierPointer() : nullptr)
1461 << " ref=" << ref << " ref rb_ptr=" << ref->GetReadBarrierPointer()
1462 << " updated_all_immune_objects=" << updated_all_immune_objects;
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001463 }
1464 } else {
1465 accounting::ContinuousSpaceBitmap* mark_bitmap =
1466 heap_mark_bitmap_->GetContinuousSpaceBitmap(ref);
1467 accounting::LargeObjectBitmap* los_bitmap =
1468 heap_mark_bitmap_->GetLargeObjectBitmap(ref);
1469 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
1470 bool is_los = mark_bitmap == nullptr;
1471 if ((!is_los && mark_bitmap->Test(ref)) ||
1472 (is_los && los_bitmap->Test(ref))) {
1473 // OK.
1474 } else {
1475 // If ref is on the allocation stack, then it may not be
1476 // marked live, but considered marked/alive (but not
1477 // necessarily on the live stack).
1478 CHECK(IsOnAllocStack(ref)) << "Unmarked ref that's not on the allocation stack. "
1479 << "obj=" << obj << " ref=" << ref;
1480 }
1481 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001482}
1483
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001484// Used to scan ref fields of an object.
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001485class ConcurrentCopying::RefFieldsVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001486 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001487 explicit RefFieldsVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001488 : collector_(collector) {}
1489
1490 void operator()(mirror::Object* obj, MemberOffset offset, bool /* is_static */)
Mathieu Chartier90443472015-07-16 20:32:27 -07001491 const ALWAYS_INLINE SHARED_REQUIRES(Locks::mutator_lock_)
1492 SHARED_REQUIRES(Locks::heap_bitmap_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001493 collector_->Process(obj, offset);
1494 }
1495
1496 void operator()(mirror::Class* klass, mirror::Reference* ref) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001497 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001498 CHECK(klass->IsTypeOfReferenceClass());
1499 collector_->DelayReferenceReferent(klass, ref);
1500 }
1501
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001502 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001503 ALWAYS_INLINE
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001504 SHARED_REQUIRES(Locks::mutator_lock_) {
1505 if (!root->IsNull()) {
1506 VisitRoot(root);
1507 }
1508 }
1509
1510 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001511 ALWAYS_INLINE
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001512 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001513 collector_->MarkRoot</*kGrayImmuneObject*/false>(root);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001514 }
1515
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001516 private:
1517 ConcurrentCopying* const collector_;
1518};
1519
1520// Scan ref fields of an object.
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001521inline void ConcurrentCopying::Scan(mirror::Object* to_ref) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001522 DCHECK(!region_space_->IsInFromSpace(to_ref));
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001523 DCHECK_EQ(Thread::Current(), thread_running_gc_);
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001524 RefFieldsVisitor visitor(this);
Hiroshi Yamauchi5496f692016-02-17 13:29:59 -08001525 // Disable the read barrier for a performance reason.
1526 to_ref->VisitReferences</*kVisitNativeRoots*/true, kDefaultVerifyFlags, kWithoutReadBarrier>(
1527 visitor, visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001528}
1529
1530// Process a field.
1531inline void ConcurrentCopying::Process(mirror::Object* obj, MemberOffset offset) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001532 DCHECK_EQ(Thread::Current(), thread_running_gc_);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001533 mirror::Object* ref = obj->GetFieldObject<
1534 mirror::Object, kVerifyNone, kWithoutReadBarrier, false>(offset);
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001535 mirror::Object* to_ref = Mark</*kGrayImmuneObject*/false>(ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001536 if (to_ref == ref) {
1537 return;
1538 }
1539 // This may fail if the mutator writes to the field at the same time. But it's ok.
1540 mirror::Object* expected_ref = ref;
1541 mirror::Object* new_ref = to_ref;
1542 do {
1543 if (expected_ref !=
1544 obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier, false>(offset)) {
1545 // It was updated by the mutator.
1546 break;
1547 }
Hiroshi Yamauchifed3e2f2015-10-20 11:11:56 -07001548 } while (!obj->CasFieldWeakRelaxedObjectWithoutWriteBarrier<
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001549 false, false, kVerifyNone>(offset, expected_ref, new_ref));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001550}
1551
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001552// Process some roots.
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001553inline void ConcurrentCopying::VisitRoots(
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001554 mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED) {
1555 for (size_t i = 0; i < count; ++i) {
1556 mirror::Object** root = roots[i];
1557 mirror::Object* ref = *root;
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001558 mirror::Object* to_ref = Mark(ref);
1559 if (to_ref == ref) {
Mathieu Chartier4809d0a2015-04-07 10:39:04 -07001560 continue;
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001561 }
1562 Atomic<mirror::Object*>* addr = reinterpret_cast<Atomic<mirror::Object*>*>(root);
1563 mirror::Object* expected_ref = ref;
1564 mirror::Object* new_ref = to_ref;
1565 do {
1566 if (expected_ref != addr->LoadRelaxed()) {
1567 // It was updated by the mutator.
1568 break;
1569 }
Hiroshi Yamauchifed3e2f2015-10-20 11:11:56 -07001570 } while (!addr->CompareExchangeWeakRelaxed(expected_ref, new_ref));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001571 }
1572}
1573
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001574template<bool kGrayImmuneObject>
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001575inline void ConcurrentCopying::MarkRoot(mirror::CompressedReference<mirror::Object>* root) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001576 DCHECK(!root->IsNull());
1577 mirror::Object* const ref = root->AsMirrorPtr();
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001578 mirror::Object* to_ref = Mark<kGrayImmuneObject>(ref);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001579 if (to_ref != ref) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001580 auto* addr = reinterpret_cast<Atomic<mirror::CompressedReference<mirror::Object>>*>(root);
1581 auto expected_ref = mirror::CompressedReference<mirror::Object>::FromMirrorPtr(ref);
1582 auto new_ref = mirror::CompressedReference<mirror::Object>::FromMirrorPtr(to_ref);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001583 // If the cas fails, then it was updated by the mutator.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001584 do {
1585 if (ref != addr->LoadRelaxed().AsMirrorPtr()) {
1586 // It was updated by the mutator.
1587 break;
1588 }
Hiroshi Yamauchifed3e2f2015-10-20 11:11:56 -07001589 } while (!addr->CompareExchangeWeakRelaxed(expected_ref, new_ref));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001590 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001591}
1592
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001593inline void ConcurrentCopying::VisitRoots(
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001594 mirror::CompressedReference<mirror::Object>** roots, size_t count,
1595 const RootInfo& info ATTRIBUTE_UNUSED) {
1596 for (size_t i = 0; i < count; ++i) {
1597 mirror::CompressedReference<mirror::Object>* const root = roots[i];
1598 if (!root->IsNull()) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001599 // kGrayImmuneObject is true because this is used for the thread flip.
1600 MarkRoot</*kGrayImmuneObject*/true>(root);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001601 }
1602 }
1603}
1604
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001605// Temporary set gc_grays_immune_objects_ to true in a scope if the current thread is GC.
1606class ConcurrentCopying::ScopedGcGraysImmuneObjects {
1607 public:
1608 explicit ScopedGcGraysImmuneObjects(ConcurrentCopying* collector)
1609 : collector_(collector), enabled_(false) {
1610 if (kUseBakerReadBarrier &&
1611 collector_->thread_running_gc_ == Thread::Current() &&
1612 !collector_->gc_grays_immune_objects_) {
1613 collector_->gc_grays_immune_objects_ = true;
1614 enabled_ = true;
1615 }
1616 }
1617
1618 ~ScopedGcGraysImmuneObjects() {
1619 if (kUseBakerReadBarrier &&
1620 collector_->thread_running_gc_ == Thread::Current() &&
1621 enabled_) {
1622 DCHECK(collector_->gc_grays_immune_objects_);
1623 collector_->gc_grays_immune_objects_ = false;
1624 }
1625 }
1626
1627 private:
1628 ConcurrentCopying* const collector_;
1629 bool enabled_;
1630};
1631
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001632// Fill the given memory block with a dummy object. Used to fill in a
1633// copy of objects that was lost in race.
1634void ConcurrentCopying::FillWithDummyObject(mirror::Object* dummy_obj, size_t byte_size) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001635 // GC doesn't gray immune objects while scanning immune objects. But we need to trigger the read
1636 // barriers here because we need the updated reference to the int array class, etc. Temporary set
1637 // gc_grays_immune_objects_ to true so that we won't cause a DCHECK failure in MarkImmuneSpace().
1638 ScopedGcGraysImmuneObjects scoped_gc_gray_immune_objects(this);
Roland Levillain14d90572015-07-16 10:52:26 +01001639 CHECK_ALIGNED(byte_size, kObjectAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001640 memset(dummy_obj, 0, byte_size);
1641 mirror::Class* int_array_class = mirror::IntArray::GetArrayClass();
1642 CHECK(int_array_class != nullptr);
1643 AssertToSpaceInvariant(nullptr, MemberOffset(0), int_array_class);
1644 size_t component_size = int_array_class->GetComponentSize();
1645 CHECK_EQ(component_size, sizeof(int32_t));
1646 size_t data_offset = mirror::Array::DataOffset(component_size).SizeValue();
1647 if (data_offset > byte_size) {
1648 // An int array is too big. Use java.lang.Object.
1649 mirror::Class* java_lang_Object = WellKnownClasses::ToClass(WellKnownClasses::java_lang_Object);
1650 AssertToSpaceInvariant(nullptr, MemberOffset(0), java_lang_Object);
1651 CHECK_EQ(byte_size, java_lang_Object->GetObjectSize());
1652 dummy_obj->SetClass(java_lang_Object);
1653 CHECK_EQ(byte_size, dummy_obj->SizeOf());
1654 } else {
1655 // Use an int array.
1656 dummy_obj->SetClass(int_array_class);
1657 CHECK(dummy_obj->IsArrayInstance());
1658 int32_t length = (byte_size - data_offset) / component_size;
1659 dummy_obj->AsArray()->SetLength(length);
1660 CHECK_EQ(dummy_obj->AsArray()->GetLength(), length)
1661 << "byte_size=" << byte_size << " length=" << length
1662 << " component_size=" << component_size << " data_offset=" << data_offset;
1663 CHECK_EQ(byte_size, dummy_obj->SizeOf())
1664 << "byte_size=" << byte_size << " length=" << length
1665 << " component_size=" << component_size << " data_offset=" << data_offset;
1666 }
1667}
1668
1669// Reuse the memory blocks that were copy of objects that were lost in race.
1670mirror::Object* ConcurrentCopying::AllocateInSkippedBlock(size_t alloc_size) {
1671 // Try to reuse the blocks that were unused due to CAS failures.
Roland Levillain14d90572015-07-16 10:52:26 +01001672 CHECK_ALIGNED(alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001673 Thread* self = Thread::Current();
1674 size_t min_object_size = RoundUp(sizeof(mirror::Object), space::RegionSpace::kAlignment);
1675 MutexLock mu(self, skipped_blocks_lock_);
1676 auto it = skipped_blocks_map_.lower_bound(alloc_size);
1677 if (it == skipped_blocks_map_.end()) {
1678 // Not found.
1679 return nullptr;
1680 }
1681 {
1682 size_t byte_size = it->first;
1683 CHECK_GE(byte_size, alloc_size);
1684 if (byte_size > alloc_size && byte_size - alloc_size < min_object_size) {
1685 // If remainder would be too small for a dummy object, retry with a larger request size.
1686 it = skipped_blocks_map_.lower_bound(alloc_size + min_object_size);
1687 if (it == skipped_blocks_map_.end()) {
1688 // Not found.
1689 return nullptr;
1690 }
Roland Levillain14d90572015-07-16 10:52:26 +01001691 CHECK_ALIGNED(it->first - alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001692 CHECK_GE(it->first - alloc_size, min_object_size)
1693 << "byte_size=" << byte_size << " it->first=" << it->first << " alloc_size=" << alloc_size;
1694 }
1695 }
1696 // Found a block.
1697 CHECK(it != skipped_blocks_map_.end());
1698 size_t byte_size = it->first;
1699 uint8_t* addr = it->second;
1700 CHECK_GE(byte_size, alloc_size);
1701 CHECK(region_space_->IsInToSpace(reinterpret_cast<mirror::Object*>(addr)));
Roland Levillain14d90572015-07-16 10:52:26 +01001702 CHECK_ALIGNED(byte_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001703 if (kVerboseMode) {
1704 LOG(INFO) << "Reusing skipped bytes : " << reinterpret_cast<void*>(addr) << ", " << byte_size;
1705 }
1706 skipped_blocks_map_.erase(it);
1707 memset(addr, 0, byte_size);
1708 if (byte_size > alloc_size) {
1709 // Return the remainder to the map.
Roland Levillain14d90572015-07-16 10:52:26 +01001710 CHECK_ALIGNED(byte_size - alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001711 CHECK_GE(byte_size - alloc_size, min_object_size);
1712 FillWithDummyObject(reinterpret_cast<mirror::Object*>(addr + alloc_size),
1713 byte_size - alloc_size);
1714 CHECK(region_space_->IsInToSpace(reinterpret_cast<mirror::Object*>(addr + alloc_size)));
1715 skipped_blocks_map_.insert(std::make_pair(byte_size - alloc_size, addr + alloc_size));
1716 }
1717 return reinterpret_cast<mirror::Object*>(addr);
1718}
1719
1720mirror::Object* ConcurrentCopying::Copy(mirror::Object* from_ref) {
1721 DCHECK(region_space_->IsInFromSpace(from_ref));
1722 // No read barrier to avoid nested RB that might violate the to-space
1723 // invariant. Note that from_ref is a from space ref so the SizeOf()
1724 // call will access the from-space meta objects, but it's ok and necessary.
1725 size_t obj_size = from_ref->SizeOf<kDefaultVerifyFlags, kWithoutReadBarrier>();
1726 size_t region_space_alloc_size = RoundUp(obj_size, space::RegionSpace::kAlignment);
1727 size_t region_space_bytes_allocated = 0U;
1728 size_t non_moving_space_bytes_allocated = 0U;
1729 size_t bytes_allocated = 0U;
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001730 size_t dummy;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001731 mirror::Object* to_ref = region_space_->AllocNonvirtual<true>(
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001732 region_space_alloc_size, &region_space_bytes_allocated, nullptr, &dummy);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001733 bytes_allocated = region_space_bytes_allocated;
1734 if (to_ref != nullptr) {
1735 DCHECK_EQ(region_space_alloc_size, region_space_bytes_allocated);
1736 }
1737 bool fall_back_to_non_moving = false;
1738 if (UNLIKELY(to_ref == nullptr)) {
1739 // Failed to allocate in the region space. Try the skipped blocks.
1740 to_ref = AllocateInSkippedBlock(region_space_alloc_size);
1741 if (to_ref != nullptr) {
1742 // Succeeded to allocate in a skipped block.
1743 if (heap_->use_tlab_) {
1744 // This is necessary for the tlab case as it's not accounted in the space.
1745 region_space_->RecordAlloc(to_ref);
1746 }
1747 bytes_allocated = region_space_alloc_size;
1748 } else {
1749 // Fall back to the non-moving space.
1750 fall_back_to_non_moving = true;
1751 if (kVerboseMode) {
1752 LOG(INFO) << "Out of memory in the to-space. Fall back to non-moving. skipped_bytes="
1753 << to_space_bytes_skipped_.LoadSequentiallyConsistent()
1754 << " skipped_objects=" << to_space_objects_skipped_.LoadSequentiallyConsistent();
1755 }
1756 fall_back_to_non_moving = true;
1757 to_ref = heap_->non_moving_space_->Alloc(Thread::Current(), obj_size,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001758 &non_moving_space_bytes_allocated, nullptr, &dummy);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001759 CHECK(to_ref != nullptr) << "Fall-back non-moving space allocation failed";
1760 bytes_allocated = non_moving_space_bytes_allocated;
1761 // Mark it in the mark bitmap.
1762 accounting::ContinuousSpaceBitmap* mark_bitmap =
1763 heap_mark_bitmap_->GetContinuousSpaceBitmap(to_ref);
1764 CHECK(mark_bitmap != nullptr);
1765 CHECK(!mark_bitmap->AtomicTestAndSet(to_ref));
1766 }
1767 }
1768 DCHECK(to_ref != nullptr);
1769
1770 // Attempt to install the forward pointer. This is in a loop as the
1771 // lock word atomic write can fail.
1772 while (true) {
1773 // Copy the object. TODO: copy only the lockword in the second iteration and on?
1774 memcpy(to_ref, from_ref, obj_size);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001775
1776 LockWord old_lock_word = to_ref->GetLockWord(false);
1777
1778 if (old_lock_word.GetState() == LockWord::kForwardingAddress) {
1779 // Lost the race. Another thread (either GC or mutator) stored
1780 // the forwarding pointer first. Make the lost copy (to_ref)
1781 // look like a valid but dead (dummy) object and keep it for
1782 // future reuse.
1783 FillWithDummyObject(to_ref, bytes_allocated);
1784 if (!fall_back_to_non_moving) {
1785 DCHECK(region_space_->IsInToSpace(to_ref));
1786 if (bytes_allocated > space::RegionSpace::kRegionSize) {
1787 // Free the large alloc.
1788 region_space_->FreeLarge(to_ref, bytes_allocated);
1789 } else {
1790 // Record the lost copy for later reuse.
1791 heap_->num_bytes_allocated_.FetchAndAddSequentiallyConsistent(bytes_allocated);
1792 to_space_bytes_skipped_.FetchAndAddSequentiallyConsistent(bytes_allocated);
1793 to_space_objects_skipped_.FetchAndAddSequentiallyConsistent(1);
1794 MutexLock mu(Thread::Current(), skipped_blocks_lock_);
1795 skipped_blocks_map_.insert(std::make_pair(bytes_allocated,
1796 reinterpret_cast<uint8_t*>(to_ref)));
1797 }
1798 } else {
1799 DCHECK(heap_->non_moving_space_->HasAddress(to_ref));
1800 DCHECK_EQ(bytes_allocated, non_moving_space_bytes_allocated);
1801 // Free the non-moving-space chunk.
1802 accounting::ContinuousSpaceBitmap* mark_bitmap =
1803 heap_mark_bitmap_->GetContinuousSpaceBitmap(to_ref);
1804 CHECK(mark_bitmap != nullptr);
1805 CHECK(mark_bitmap->Clear(to_ref));
1806 heap_->non_moving_space_->Free(Thread::Current(), to_ref);
1807 }
1808
1809 // Get the winner's forward ptr.
1810 mirror::Object* lost_fwd_ptr = to_ref;
1811 to_ref = reinterpret_cast<mirror::Object*>(old_lock_word.ForwardingAddress());
1812 CHECK(to_ref != nullptr);
1813 CHECK_NE(to_ref, lost_fwd_ptr);
1814 CHECK(region_space_->IsInToSpace(to_ref) || heap_->non_moving_space_->HasAddress(to_ref));
1815 CHECK_NE(to_ref->GetLockWord(false).GetState(), LockWord::kForwardingAddress);
1816 return to_ref;
1817 }
1818
Hiroshi Yamauchi60f63f52015-04-23 16:12:40 -07001819 // Set the gray ptr.
1820 if (kUseBakerReadBarrier) {
1821 to_ref->SetReadBarrierPointer(ReadBarrier::GrayPtr());
1822 }
1823
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001824 LockWord new_lock_word = LockWord::FromForwardingAddress(reinterpret_cast<size_t>(to_ref));
1825
1826 // Try to atomically write the fwd ptr.
1827 bool success = from_ref->CasLockWordWeakSequentiallyConsistent(old_lock_word, new_lock_word);
1828 if (LIKELY(success)) {
1829 // The CAS succeeded.
1830 objects_moved_.FetchAndAddSequentiallyConsistent(1);
1831 bytes_moved_.FetchAndAddSequentiallyConsistent(region_space_alloc_size);
1832 if (LIKELY(!fall_back_to_non_moving)) {
1833 DCHECK(region_space_->IsInToSpace(to_ref));
1834 } else {
1835 DCHECK(heap_->non_moving_space_->HasAddress(to_ref));
1836 DCHECK_EQ(bytes_allocated, non_moving_space_bytes_allocated);
1837 }
1838 if (kUseBakerReadBarrier) {
1839 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr());
1840 }
1841 DCHECK(GetFwdPtr(from_ref) == to_ref);
1842 CHECK_NE(to_ref->GetLockWord(false).GetState(), LockWord::kForwardingAddress);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001843 PushOntoMarkStack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001844 return to_ref;
1845 } else {
1846 // The CAS failed. It may have lost the race or may have failed
1847 // due to monitor/hashcode ops. Either way, retry.
1848 }
1849 }
1850}
1851
1852mirror::Object* ConcurrentCopying::IsMarked(mirror::Object* from_ref) {
1853 DCHECK(from_ref != nullptr);
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08001854 space::RegionSpace::RegionType rtype = region_space_->GetRegionType(from_ref);
1855 if (rtype == space::RegionSpace::RegionType::kRegionTypeToSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001856 // It's already marked.
1857 return from_ref;
1858 }
1859 mirror::Object* to_ref;
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08001860 if (rtype == space::RegionSpace::RegionType::kRegionTypeFromSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001861 to_ref = GetFwdPtr(from_ref);
1862 DCHECK(to_ref == nullptr || region_space_->IsInToSpace(to_ref) ||
1863 heap_->non_moving_space_->HasAddress(to_ref))
1864 << "from_ref=" << from_ref << " to_ref=" << to_ref;
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08001865 } else if (rtype == space::RegionSpace::RegionType::kRegionTypeUnevacFromSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001866 if (region_space_bitmap_->Test(from_ref)) {
1867 to_ref = from_ref;
1868 } else {
1869 to_ref = nullptr;
1870 }
1871 } else {
1872 // from_ref is in a non-moving space.
Mathieu Chartier763a31e2015-11-16 16:05:55 -08001873 if (immune_spaces_.ContainsObject(from_ref)) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001874 // An immune object is alive.
1875 to_ref = from_ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001876 } else {
1877 // Non-immune non-moving space. Use the mark bitmap.
1878 accounting::ContinuousSpaceBitmap* mark_bitmap =
1879 heap_mark_bitmap_->GetContinuousSpaceBitmap(from_ref);
1880 accounting::LargeObjectBitmap* los_bitmap =
1881 heap_mark_bitmap_->GetLargeObjectBitmap(from_ref);
1882 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
1883 bool is_los = mark_bitmap == nullptr;
1884 if (!is_los && mark_bitmap->Test(from_ref)) {
1885 // Already marked.
1886 to_ref = from_ref;
1887 } else if (is_los && los_bitmap->Test(from_ref)) {
1888 // Already marked in LOS.
1889 to_ref = from_ref;
1890 } else {
1891 // Not marked.
1892 if (IsOnAllocStack(from_ref)) {
1893 // If on the allocation stack, it's considered marked.
1894 to_ref = from_ref;
1895 } else {
1896 // Not marked.
1897 to_ref = nullptr;
1898 }
1899 }
1900 }
1901 }
1902 return to_ref;
1903}
1904
1905bool ConcurrentCopying::IsOnAllocStack(mirror::Object* ref) {
1906 QuasiAtomic::ThreadFenceAcquire();
1907 accounting::ObjectStack* alloc_stack = GetAllocationStack();
Mathieu Chartiercb535da2015-01-23 13:50:03 -08001908 return alloc_stack->Contains(ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001909}
1910
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001911mirror::Object* ConcurrentCopying::MarkNonMoving(mirror::Object* ref) {
1912 // ref is in a non-moving space (from_ref == to_ref).
1913 DCHECK(!region_space_->HasAddress(ref)) << ref;
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001914 DCHECK(!immune_spaces_.ContainsObject(ref));
1915 // Use the mark bitmap.
1916 accounting::ContinuousSpaceBitmap* mark_bitmap =
1917 heap_mark_bitmap_->GetContinuousSpaceBitmap(ref);
1918 accounting::LargeObjectBitmap* los_bitmap =
1919 heap_mark_bitmap_->GetLargeObjectBitmap(ref);
1920 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
1921 bool is_los = mark_bitmap == nullptr;
1922 if (!is_los && mark_bitmap->Test(ref)) {
1923 // Already marked.
1924 if (kUseBakerReadBarrier) {
1925 DCHECK(ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr() ||
1926 ref->GetReadBarrierPointer() == ReadBarrier::WhitePtr());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001927 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001928 } else if (is_los && los_bitmap->Test(ref)) {
1929 // Already marked in LOS.
1930 if (kUseBakerReadBarrier) {
1931 DCHECK(ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr() ||
1932 ref->GetReadBarrierPointer() == ReadBarrier::WhitePtr());
1933 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001934 } else {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001935 // Not marked.
1936 if (IsOnAllocStack(ref)) {
1937 // If it's on the allocation stack, it's considered marked. Keep it white.
1938 // Objects on the allocation stack need not be marked.
1939 if (!is_los) {
1940 DCHECK(!mark_bitmap->Test(ref));
1941 } else {
1942 DCHECK(!los_bitmap->Test(ref));
Nicolas Geoffrayddeb1722016-06-28 08:25:59 +00001943 }
Nicolas Geoffrayddeb1722016-06-28 08:25:59 +00001944 if (kUseBakerReadBarrier) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001945 DCHECK_EQ(ref->GetReadBarrierPointer(), ReadBarrier::WhitePtr());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001946 }
1947 } else {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001948 // For the baker-style RB, we need to handle 'false-gray' cases. See the
1949 // kRegionTypeUnevacFromSpace-case comment in Mark().
1950 if (kUseBakerReadBarrier) {
1951 // Test the bitmap first to reduce the chance of false gray cases.
1952 if ((!is_los && mark_bitmap->Test(ref)) ||
1953 (is_los && los_bitmap->Test(ref))) {
1954 return ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001955 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001956 }
1957 // Not marked or on the allocation stack. Try to mark it.
1958 // This may or may not succeed, which is ok.
1959 bool cas_success = false;
1960 if (kUseBakerReadBarrier) {
1961 cas_success = ref->AtomicSetReadBarrierPointer(ReadBarrier::WhitePtr(),
1962 ReadBarrier::GrayPtr());
1963 }
1964 if (!is_los && mark_bitmap->AtomicTestAndSet(ref)) {
1965 // Already marked.
1966 if (kUseBakerReadBarrier && cas_success &&
1967 ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr()) {
1968 PushOntoFalseGrayStack(ref);
1969 }
1970 } else if (is_los && los_bitmap->AtomicTestAndSet(ref)) {
1971 // Already marked in LOS.
1972 if (kUseBakerReadBarrier && cas_success &&
1973 ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr()) {
1974 PushOntoFalseGrayStack(ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001975 }
1976 } else {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001977 // Newly marked.
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001978 if (kUseBakerReadBarrier) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001979 DCHECK_EQ(ref->GetReadBarrierPointer(), ReadBarrier::GrayPtr());
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001980 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001981 PushOntoMarkStack(ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001982 }
1983 }
1984 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001985 return ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001986}
1987
1988void ConcurrentCopying::FinishPhase() {
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -08001989 Thread* const self = Thread::Current();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001990 {
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -08001991 MutexLock mu(self, mark_stack_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001992 CHECK_EQ(pooled_mark_stacks_.size(), kMarkStackPoolSize);
1993 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001994 region_space_ = nullptr;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001995 {
1996 MutexLock mu(Thread::Current(), skipped_blocks_lock_);
1997 skipped_blocks_map_.clear();
1998 }
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -08001999 ReaderMutexLock mu(self, *Locks::mutator_lock_);
2000 WriterMutexLock mu2(self, *Locks::heap_bitmap_lock_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002001 heap_->ClearMarkedObjects();
2002}
2003
Mathieu Chartier97509952015-07-13 14:35:43 -07002004bool ConcurrentCopying::IsMarkedHeapReference(mirror::HeapReference<mirror::Object>* field) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002005 mirror::Object* from_ref = field->AsMirrorPtr();
Mathieu Chartier97509952015-07-13 14:35:43 -07002006 mirror::Object* to_ref = IsMarked(from_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002007 if (to_ref == nullptr) {
2008 return false;
2009 }
2010 if (from_ref != to_ref) {
2011 QuasiAtomic::ThreadFenceRelease();
2012 field->Assign(to_ref);
2013 QuasiAtomic::ThreadFenceSequentiallyConsistent();
2014 }
2015 return true;
2016}
2017
Mathieu Chartier97509952015-07-13 14:35:43 -07002018mirror::Object* ConcurrentCopying::MarkObject(mirror::Object* from_ref) {
2019 return Mark(from_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002020}
2021
2022void ConcurrentCopying::DelayReferenceReferent(mirror::Class* klass, mirror::Reference* reference) {
Mathieu Chartier97509952015-07-13 14:35:43 -07002023 heap_->GetReferenceProcessor()->DelayReferenceReferent(klass, reference, this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002024}
2025
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002026void ConcurrentCopying::ProcessReferences(Thread* self) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002027 TimingLogger::ScopedTiming split("ProcessReferences", GetTimings());
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002028 // 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 -08002029 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
2030 GetHeap()->GetReferenceProcessor()->ProcessReferences(
Mathieu Chartier97509952015-07-13 14:35:43 -07002031 true /*concurrent*/, GetTimings(), GetCurrentIteration()->GetClearSoftReferences(), this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002032}
2033
2034void ConcurrentCopying::RevokeAllThreadLocalBuffers() {
2035 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
2036 region_space_->RevokeAllThreadLocalBuffers();
2037}
2038
Hiroshi Yamauchid5307ec2014-03-27 21:07:51 -07002039} // namespace collector
2040} // namespace gc
2041} // namespace art