blob: 78eed9ec25653c224171868a9a2bb2e29689ea92 [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.
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700197class ConcurrentCopying::ThreadFlipVisitor : public Closure, public RootVisitor {
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_);
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700224 // We can use the non-CAS VisitRoots functions below because we update thread-local GC roots
225 // only.
226 thread->VisitRoots(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800227 concurrent_copying_->GetBarrier().Pass(self);
228 }
229
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700230 void VisitRoots(mirror::Object*** roots,
231 size_t count,
232 const RootInfo& info ATTRIBUTE_UNUSED)
233 SHARED_REQUIRES(Locks::mutator_lock_) {
234 for (size_t i = 0; i < count; ++i) {
235 mirror::Object** root = roots[i];
236 mirror::Object* ref = *root;
237 if (ref != nullptr) {
238 mirror::Object* to_ref = concurrent_copying_->Mark(ref);
239 if (to_ref != ref) {
240 *root = to_ref;
241 }
242 }
243 }
244 }
245
246 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots,
247 size_t count,
248 const RootInfo& info ATTRIBUTE_UNUSED)
249 SHARED_REQUIRES(Locks::mutator_lock_) {
250 for (size_t i = 0; i < count; ++i) {
251 mirror::CompressedReference<mirror::Object>* const root = roots[i];
252 if (!root->IsNull()) {
253 mirror::Object* ref = root->AsMirrorPtr();
254 mirror::Object* to_ref = concurrent_copying_->Mark(ref);
255 if (to_ref != ref) {
256 root->Assign(to_ref);
257 }
258 }
259 }
260 }
261
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800262 private:
263 ConcurrentCopying* const concurrent_copying_;
264 const bool use_tlab_;
265};
266
267// Called back from Runtime::FlipThreadRoots() during a pause.
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700268class ConcurrentCopying::FlipCallback : public Closure {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800269 public:
270 explicit FlipCallback(ConcurrentCopying* concurrent_copying)
271 : concurrent_copying_(concurrent_copying) {
272 }
273
Mathieu Chartier90443472015-07-16 20:32:27 -0700274 virtual void Run(Thread* thread) OVERRIDE REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800275 ConcurrentCopying* cc = concurrent_copying_;
276 TimingLogger::ScopedTiming split("(Paused)FlipCallback", cc->GetTimings());
277 // Note: self is not necessarily equal to thread since thread may be suspended.
278 Thread* self = Thread::Current();
279 CHECK(thread == self);
280 Locks::mutator_lock_->AssertExclusiveHeld(self);
281 cc->region_space_->SetFromSpace(cc->rb_table_, cc->force_evacuate_all_);
Mathieu Chartiera4f6af92015-08-11 17:35:25 -0700282 cc->SwapStacks();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800283 if (ConcurrentCopying::kEnableFromSpaceAccountingCheck) {
284 cc->RecordLiveStackFreezeSize(self);
285 cc->from_space_num_objects_at_first_pause_ = cc->region_space_->GetObjectsAllocated();
286 cc->from_space_num_bytes_at_first_pause_ = cc->region_space_->GetBytesAllocated();
287 }
288 cc->is_marking_ = true;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700289 cc->mark_stack_mode_.StoreRelaxed(ConcurrentCopying::kMarkStackModeThreadLocal);
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800290 if (kIsDebugBuild) {
291 cc->region_space_->AssertAllRegionLiveBytesZeroOrCleared();
292 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800293 if (UNLIKELY(Runtime::Current()->IsActiveTransaction())) {
Mathieu Chartier184c9dc2015-03-05 13:20:54 -0800294 CHECK(Runtime::Current()->IsAotCompiler());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800295 TimingLogger::ScopedTiming split2("(Paused)VisitTransactionRoots", cc->GetTimings());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700296 Runtime::Current()->VisitTransactionRoots(cc);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800297 }
298 }
299
300 private:
301 ConcurrentCopying* const concurrent_copying_;
302};
303
304// Switch threads that from from-space to to-space refs. Forward/mark the thread roots.
305void ConcurrentCopying::FlipThreadRoots() {
306 TimingLogger::ScopedTiming split("FlipThreadRoots", GetTimings());
307 if (kVerboseMode) {
308 LOG(INFO) << "time=" << region_space_->Time();
309 region_space_->DumpNonFreeRegions(LOG(INFO));
310 }
311 Thread* self = Thread::Current();
312 Locks::mutator_lock_->AssertNotHeld(self);
313 gc_barrier_->Init(self, 0);
314 ThreadFlipVisitor thread_flip_visitor(this, heap_->use_tlab_);
315 FlipCallback flip_callback(this);
Hiroshi Yamauchi76f55b02015-08-21 16:10:39 -0700316 heap_->ThreadFlipBegin(self); // Sync with JNI critical calls.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800317 size_t barrier_count = Runtime::Current()->FlipThreadRoots(
318 &thread_flip_visitor, &flip_callback, this);
Hiroshi Yamauchi76f55b02015-08-21 16:10:39 -0700319 heap_->ThreadFlipEnd(self);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800320 {
321 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
322 gc_barrier_->Increment(self, barrier_count);
323 }
324 is_asserting_to_space_invariant_ = true;
325 QuasiAtomic::ThreadFenceForConstructor();
326 if (kVerboseMode) {
327 LOG(INFO) << "time=" << region_space_->Time();
328 region_space_->DumpNonFreeRegions(LOG(INFO));
329 LOG(INFO) << "GC end of FlipThreadRoots";
330 }
331}
332
Mathieu Chartiera4f6af92015-08-11 17:35:25 -0700333void ConcurrentCopying::SwapStacks() {
334 heap_->SwapStacks();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800335}
336
337void ConcurrentCopying::RecordLiveStackFreezeSize(Thread* self) {
338 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
339 live_stack_freeze_size_ = heap_->GetLiveStack()->Size();
340}
341
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800342class EmptyCheckpoint : public Closure {
343 public:
344 explicit EmptyCheckpoint(ConcurrentCopying* concurrent_copying)
345 : concurrent_copying_(concurrent_copying) {
346 }
347
348 virtual void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
349 // Note: self is not necessarily equal to thread since thread may be suspended.
350 Thread* self = Thread::Current();
351 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
352 << thread->GetState() << " thread " << thread << " self " << self;
Lei Lidd9943d2015-02-02 14:24:44 +0800353 // If thread is a running mutator, then act on behalf of the garbage collector.
354 // See the code in ThreadList::RunCheckpoint.
Mathieu Chartier10d25082015-10-28 18:36:09 -0700355 concurrent_copying_->GetBarrier().Pass(self);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800356 }
357
358 private:
359 ConcurrentCopying* const concurrent_copying_;
360};
361
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700362// Used to visit objects in the immune spaces.
363inline void ConcurrentCopying::ScanImmuneObject(mirror::Object* obj) {
364 DCHECK(obj != nullptr);
365 DCHECK(immune_spaces_.ContainsObject(obj));
366 // Update the fields without graying it or pushing it onto the mark stack.
367 Scan(obj);
368}
369
370class ConcurrentCopying::ImmuneSpaceScanObjVisitor {
371 public:
372 explicit ImmuneSpaceScanObjVisitor(ConcurrentCopying* cc)
373 : collector_(cc) {}
374
375 void operator()(mirror::Object* obj) const SHARED_REQUIRES(Locks::mutator_lock_) {
376 collector_->ScanImmuneObject(obj);
377 }
378
379 private:
380 ConcurrentCopying* const collector_;
381};
382
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800383// Concurrently mark roots that are guarded by read barriers and process the mark stack.
384void ConcurrentCopying::MarkingPhase() {
385 TimingLogger::ScopedTiming split("MarkingPhase", GetTimings());
386 if (kVerboseMode) {
387 LOG(INFO) << "GC MarkingPhase";
388 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700389 CHECK(weak_ref_access_enabled_);
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700390
391 // Scan immune spaces.
392 // Update all the fields in the immune spaces first without graying the objects so that we
393 // minimize dirty pages in the immune spaces. Note mutators can concurrently access and gray some
394 // of the objects.
395 if (kUseBakerReadBarrier) {
396 gc_grays_immune_objects_ = false;
Hiroshi Yamauchi16292fc2016-06-20 20:23:34 -0700397 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700398 for (auto& space : immune_spaces_.GetSpaces()) {
399 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
400 accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
401 ImmuneSpaceScanObjVisitor visitor(this);
402 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()),
403 reinterpret_cast<uintptr_t>(space->Limit()),
404 visitor);
405 }
406 if (kUseBakerReadBarrier) {
407 // This release fence makes the field updates in the above loop visible before allowing mutator
408 // getting access to immune objects without graying it first.
409 updated_all_immune_objects_.StoreRelease(true);
410 // Now whiten immune objects concurrently accessed and grayed by mutators. We can't do this in
411 // the above loop because we would incorrectly disable the read barrier by whitening an object
412 // which may point to an unscanned, white object, breaking the to-space invariant.
413 //
414 // Make sure no mutators are in the middle of marking an immune object before whitening immune
415 // objects.
416 IssueEmptyCheckpoint();
417 MutexLock mu(Thread::Current(), immune_gray_stack_lock_);
418 if (kVerboseMode) {
419 LOG(INFO) << "immune gray stack size=" << immune_gray_stack_.size();
420 }
421 for (mirror::Object* obj : immune_gray_stack_) {
422 DCHECK(obj->GetReadBarrierPointer() == ReadBarrier::GrayPtr());
423 bool success = obj->AtomicSetReadBarrierPointer(ReadBarrier::GrayPtr(),
424 ReadBarrier::WhitePtr());
425 DCHECK(success);
426 }
427 immune_gray_stack_.clear();
428 }
429
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800430 {
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -0700431 TimingLogger::ScopedTiming split2("VisitConcurrentRoots", GetTimings());
432 Runtime::Current()->VisitConcurrentRoots(this, kVisitRootFlagAllRoots);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800433 }
434 {
435 // TODO: don't visit the transaction roots if it's not active.
436 TimingLogger::ScopedTiming split5("VisitNonThreadRoots", GetTimings());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700437 Runtime::Current()->VisitNonThreadRoots(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800438 }
439
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800440 Thread* self = Thread::Current();
441 {
Mathieu Chartiera6b1ead2015-10-06 10:32:38 -0700442 TimingLogger::ScopedTiming split7("ProcessMarkStack", GetTimings());
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700443 // We transition through three mark stack modes (thread-local, shared, GC-exclusive). The
444 // primary reasons are the fact that we need to use a checkpoint to process thread-local mark
445 // stacks, but after we disable weak refs accesses, we can't use a checkpoint due to a deadlock
446 // issue because running threads potentially blocking at WaitHoldingLocks, and that once we
447 // reach the point where we process weak references, we can avoid using a lock when accessing
448 // the GC mark stack, which makes mark stack processing more efficient.
449
450 // Process the mark stack once in the thread local stack mode. This marks most of the live
451 // objects, aside from weak ref accesses with read barriers (Reference::GetReferent() and system
452 // weaks) that may happen concurrently while we processing the mark stack and newly mark/gray
453 // objects and push refs on the mark stack.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800454 ProcessMarkStack();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700455 // Switch to the shared mark stack mode. That is, revoke and process thread-local mark stacks
456 // for the last time before transitioning to the shared mark stack mode, which would process new
457 // refs that may have been concurrently pushed onto the mark stack during the ProcessMarkStack()
458 // call above. At the same time, disable weak ref accesses using a per-thread flag. It's
459 // important to do these together in a single checkpoint so that we can ensure that mutators
460 // won't newly gray objects and push new refs onto the mark stack due to weak ref accesses and
461 // mutators safely transition to the shared mark stack mode (without leaving unprocessed refs on
462 // the thread-local mark stacks), without a race. This is why we use a thread-local weak ref
463 // access flag Thread::tls32_.weak_ref_access_enabled_ instead of the global ones.
464 SwitchToSharedMarkStackMode();
465 CHECK(!self->GetWeakRefAccessEnabled());
466 // Now that weak refs accesses are disabled, once we exhaust the shared mark stack again here
467 // (which may be non-empty if there were refs found on thread-local mark stacks during the above
468 // SwitchToSharedMarkStackMode() call), we won't have new refs to process, that is, mutators
469 // (via read barriers) have no way to produce any more refs to process. Marking converges once
470 // before we process weak refs below.
471 ProcessMarkStack();
472 CheckEmptyMarkStack();
473 // Switch to the GC exclusive mark stack mode so that we can process the mark stack without a
474 // lock from this point on.
475 SwitchToGcExclusiveMarkStackMode();
476 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800477 if (kVerboseMode) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800478 LOG(INFO) << "ProcessReferences";
479 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700480 // Process weak references. This may produce new refs to process and have them processed via
Mathieu Chartier97509952015-07-13 14:35:43 -0700481 // ProcessMarkStack (in the GC exclusive mark stack mode).
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700482 ProcessReferences(self);
483 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800484 if (kVerboseMode) {
485 LOG(INFO) << "SweepSystemWeaks";
486 }
487 SweepSystemWeaks(self);
488 if (kVerboseMode) {
489 LOG(INFO) << "SweepSystemWeaks done";
490 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700491 // Process the mark stack here one last time because the above SweepSystemWeaks() call may have
492 // marked some objects (strings alive) as hash_set::Erase() can call the hash function for
493 // arbitrary elements in the weak intern table in InternTable::Table::SweepWeaks().
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800494 ProcessMarkStack();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700495 CheckEmptyMarkStack();
496 // Re-enable weak ref accesses.
497 ReenableWeakRefAccess(self);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -0700498 // Free data for class loaders that we unloaded.
499 Runtime::Current()->GetClassLinker()->CleanupClassLoaders();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700500 // Marking is done. Disable marking.
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700501 DisableMarking();
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800502 if (kUseBakerReadBarrier) {
503 ProcessFalseGrayStack();
504 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700505 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800506 }
507
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700508 CHECK(weak_ref_access_enabled_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800509 if (kVerboseMode) {
510 LOG(INFO) << "GC end of MarkingPhase";
511 }
512}
513
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700514void ConcurrentCopying::ReenableWeakRefAccess(Thread* self) {
515 if (kVerboseMode) {
516 LOG(INFO) << "ReenableWeakRefAccess";
517 }
518 weak_ref_access_enabled_.StoreRelaxed(true); // This is for new threads.
519 QuasiAtomic::ThreadFenceForConstructor();
520 // Iterate all threads (don't need to or can't use a checkpoint) and re-enable weak ref access.
521 {
522 MutexLock mu(self, *Locks::thread_list_lock_);
523 std::list<Thread*> thread_list = Runtime::Current()->GetThreadList()->GetList();
524 for (Thread* thread : thread_list) {
525 thread->SetWeakRefAccessEnabled(true);
526 }
527 }
528 // Unblock blocking threads.
529 GetHeap()->GetReferenceProcessor()->BroadcastForSlowPath(self);
530 Runtime::Current()->BroadcastForNewSystemWeaks();
531}
532
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700533class ConcurrentCopying::DisableMarkingCheckpoint : public Closure {
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700534 public:
535 explicit DisableMarkingCheckpoint(ConcurrentCopying* concurrent_copying)
536 : concurrent_copying_(concurrent_copying) {
537 }
538
539 void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
540 // Note: self is not necessarily equal to thread since thread may be suspended.
541 Thread* self = Thread::Current();
542 DCHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
543 << thread->GetState() << " thread " << thread << " self " << self;
544 // Disable the thread-local is_gc_marking flag.
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -0700545 // Note a thread that has just started right before this checkpoint may have already this flag
546 // set to false, which is ok.
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700547 thread->SetIsGcMarking(false);
548 // If thread is a running mutator, then act on behalf of the garbage collector.
549 // See the code in ThreadList::RunCheckpoint.
Mathieu Chartier10d25082015-10-28 18:36:09 -0700550 concurrent_copying_->GetBarrier().Pass(self);
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700551 }
552
553 private:
554 ConcurrentCopying* const concurrent_copying_;
555};
556
557void ConcurrentCopying::IssueDisableMarkingCheckpoint() {
558 Thread* self = Thread::Current();
559 DisableMarkingCheckpoint check_point(this);
560 ThreadList* thread_list = Runtime::Current()->GetThreadList();
561 gc_barrier_->Init(self, 0);
562 size_t barrier_count = thread_list->RunCheckpoint(&check_point);
563 // If there are no threads to wait which implies that all the checkpoint functions are finished,
564 // then no need to release the mutator lock.
565 if (barrier_count == 0) {
566 return;
567 }
568 // Release locks then wait for all mutator threads to pass the barrier.
569 Locks::mutator_lock_->SharedUnlock(self);
570 {
571 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
572 gc_barrier_->Increment(self, barrier_count);
573 }
574 Locks::mutator_lock_->SharedLock(self);
575}
576
577void ConcurrentCopying::DisableMarking() {
578 // Change the global is_marking flag to false. Do a fence before doing a checkpoint to update the
579 // thread-local flags so that a new thread starting up will get the correct is_marking flag.
580 is_marking_ = false;
581 QuasiAtomic::ThreadFenceForConstructor();
582 // Use a checkpoint to turn off the thread-local is_gc_marking flags and to ensure no threads are
583 // still in the middle of a read barrier which may have a from-space ref cached in a local
584 // variable.
585 IssueDisableMarkingCheckpoint();
586 if (kUseTableLookupReadBarrier) {
587 heap_->rb_table_->ClearAll();
588 DCHECK(heap_->rb_table_->IsAllCleared());
589 }
590 is_mark_stack_push_disallowed_.StoreSequentiallyConsistent(1);
591 mark_stack_mode_.StoreSequentiallyConsistent(kMarkStackModeOff);
592}
593
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800594void ConcurrentCopying::PushOntoFalseGrayStack(mirror::Object* ref) {
595 CHECK(kUseBakerReadBarrier);
596 DCHECK(ref != nullptr);
597 MutexLock mu(Thread::Current(), mark_stack_lock_);
598 false_gray_stack_.push_back(ref);
599}
600
601void ConcurrentCopying::ProcessFalseGrayStack() {
602 CHECK(kUseBakerReadBarrier);
603 // Change the objects on the false gray stack from gray to white.
604 MutexLock mu(Thread::Current(), mark_stack_lock_);
605 for (mirror::Object* obj : false_gray_stack_) {
606 DCHECK(IsMarked(obj));
607 // The object could be white here if a thread got preempted after a success at the
608 // AtomicSetReadBarrierPointer in Mark(), GC started marking through it (but not finished so
609 // still gray), and the thread ran to register it onto the false gray stack.
610 if (obj->GetReadBarrierPointer() == ReadBarrier::GrayPtr()) {
611 bool success = obj->AtomicSetReadBarrierPointer(ReadBarrier::GrayPtr(),
612 ReadBarrier::WhitePtr());
613 DCHECK(success);
614 }
615 }
616 false_gray_stack_.clear();
617}
618
619
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800620void ConcurrentCopying::IssueEmptyCheckpoint() {
621 Thread* self = Thread::Current();
622 EmptyCheckpoint check_point(this);
623 ThreadList* thread_list = Runtime::Current()->GetThreadList();
624 gc_barrier_->Init(self, 0);
625 size_t barrier_count = thread_list->RunCheckpoint(&check_point);
Lei Lidd9943d2015-02-02 14:24:44 +0800626 // If there are no threads to wait which implys that all the checkpoint functions are finished,
627 // then no need to release the mutator lock.
628 if (barrier_count == 0) {
629 return;
630 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800631 // Release locks then wait for all mutator threads to pass the barrier.
632 Locks::mutator_lock_->SharedUnlock(self);
633 {
634 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
635 gc_barrier_->Increment(self, barrier_count);
636 }
637 Locks::mutator_lock_->SharedLock(self);
638}
639
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -0700640void ConcurrentCopying::ExpandGcMarkStack() {
641 DCHECK(gc_mark_stack_->IsFull());
642 const size_t new_size = gc_mark_stack_->Capacity() * 2;
643 std::vector<StackReference<mirror::Object>> temp(gc_mark_stack_->Begin(),
644 gc_mark_stack_->End());
645 gc_mark_stack_->Resize(new_size);
646 for (auto& ref : temp) {
647 gc_mark_stack_->PushBack(ref.AsMirrorPtr());
648 }
649 DCHECK(!gc_mark_stack_->IsFull());
650}
651
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800652void ConcurrentCopying::PushOntoMarkStack(mirror::Object* to_ref) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700653 CHECK_EQ(is_mark_stack_push_disallowed_.LoadRelaxed(), 0)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800654 << " " << to_ref << " " << PrettyTypeOf(to_ref);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700655 Thread* self = Thread::Current(); // TODO: pass self as an argument from call sites?
656 CHECK(thread_running_gc_ != nullptr);
657 MarkStackMode mark_stack_mode = mark_stack_mode_.LoadRelaxed();
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -0700658 if (LIKELY(mark_stack_mode == kMarkStackModeThreadLocal)) {
659 if (LIKELY(self == thread_running_gc_)) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700660 // If GC-running thread, use the GC mark stack instead of a thread-local mark stack.
661 CHECK(self->GetThreadLocalMarkStack() == nullptr);
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -0700662 if (UNLIKELY(gc_mark_stack_->IsFull())) {
663 ExpandGcMarkStack();
664 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700665 gc_mark_stack_->PushBack(to_ref);
666 } else {
667 // Otherwise, use a thread-local mark stack.
668 accounting::AtomicStack<mirror::Object>* tl_mark_stack = self->GetThreadLocalMarkStack();
669 if (UNLIKELY(tl_mark_stack == nullptr || tl_mark_stack->IsFull())) {
670 MutexLock mu(self, mark_stack_lock_);
671 // Get a new thread local mark stack.
672 accounting::AtomicStack<mirror::Object>* new_tl_mark_stack;
673 if (!pooled_mark_stacks_.empty()) {
674 // Use a pooled mark stack.
675 new_tl_mark_stack = pooled_mark_stacks_.back();
676 pooled_mark_stacks_.pop_back();
677 } else {
678 // None pooled. Create a new one.
679 new_tl_mark_stack =
680 accounting::AtomicStack<mirror::Object>::Create(
681 "thread local mark stack", 4 * KB, 4 * KB);
682 }
683 DCHECK(new_tl_mark_stack != nullptr);
684 DCHECK(new_tl_mark_stack->IsEmpty());
685 new_tl_mark_stack->PushBack(to_ref);
686 self->SetThreadLocalMarkStack(new_tl_mark_stack);
687 if (tl_mark_stack != nullptr) {
688 // Store the old full stack into a vector.
689 revoked_mark_stacks_.push_back(tl_mark_stack);
690 }
691 } else {
692 tl_mark_stack->PushBack(to_ref);
693 }
694 }
695 } else if (mark_stack_mode == kMarkStackModeShared) {
696 // Access the shared GC mark stack with a lock.
697 MutexLock mu(self, mark_stack_lock_);
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -0700698 if (UNLIKELY(gc_mark_stack_->IsFull())) {
699 ExpandGcMarkStack();
700 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700701 gc_mark_stack_->PushBack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800702 } else {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700703 CHECK_EQ(static_cast<uint32_t>(mark_stack_mode),
Hiroshi Yamauchifa755182015-09-30 20:12:11 -0700704 static_cast<uint32_t>(kMarkStackModeGcExclusive))
705 << "ref=" << to_ref
706 << " self->gc_marking=" << self->GetIsGcMarking()
707 << " cc->is_marking=" << is_marking_;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700708 CHECK(self == thread_running_gc_)
709 << "Only GC-running thread should access the mark stack "
710 << "in the GC exclusive mark stack mode";
711 // Access the GC mark stack without a lock.
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -0700712 if (UNLIKELY(gc_mark_stack_->IsFull())) {
713 ExpandGcMarkStack();
714 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700715 gc_mark_stack_->PushBack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800716 }
717}
718
719accounting::ObjectStack* ConcurrentCopying::GetAllocationStack() {
720 return heap_->allocation_stack_.get();
721}
722
723accounting::ObjectStack* ConcurrentCopying::GetLiveStack() {
724 return heap_->live_stack_.get();
725}
726
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800727// The following visitors are used to verify that there's no references to the from-space left after
728// marking.
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700729class ConcurrentCopying::VerifyNoFromSpaceRefsVisitor : public SingleRootVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800730 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700731 explicit VerifyNoFromSpaceRefsVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800732 : collector_(collector) {}
733
734 void operator()(mirror::Object* ref) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700735 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800736 if (ref == nullptr) {
737 // OK.
738 return;
739 }
740 collector_->AssertToSpaceInvariant(nullptr, MemberOffset(0), ref);
741 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800742 CHECK(ref->GetReadBarrierPointer() == ReadBarrier::WhitePtr())
743 << "Ref " << ref << " " << PrettyTypeOf(ref)
744 << " has non-white rb_ptr " << ref->GetReadBarrierPointer();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800745 }
746 }
747
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700748 void VisitRoot(mirror::Object* root, const RootInfo& info ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -0700749 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800750 DCHECK(root != nullptr);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700751 operator()(root);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800752 }
753
754 private:
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700755 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800756};
757
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700758class ConcurrentCopying::VerifyNoFromSpaceRefsFieldVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800759 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700760 explicit VerifyNoFromSpaceRefsFieldVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800761 : collector_(collector) {}
762
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700763 void operator()(mirror::Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700764 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800765 mirror::Object* ref =
766 obj->GetFieldObject<mirror::Object, kDefaultVerifyFlags, kWithoutReadBarrier>(offset);
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700767 VerifyNoFromSpaceRefsVisitor visitor(collector_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800768 visitor(ref);
769 }
770 void operator()(mirror::Class* klass, mirror::Reference* ref) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700771 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800772 CHECK(klass->IsTypeOfReferenceClass());
773 this->operator()(ref, mirror::Reference::ReferentOffset(), false);
774 }
775
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700776 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
777 SHARED_REQUIRES(Locks::mutator_lock_) {
778 if (!root->IsNull()) {
779 VisitRoot(root);
780 }
781 }
782
783 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
784 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700785 VerifyNoFromSpaceRefsVisitor visitor(collector_);
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700786 visitor(root->AsMirrorPtr());
787 }
788
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800789 private:
Mathieu Chartier97509952015-07-13 14:35:43 -0700790 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800791};
792
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700793class ConcurrentCopying::VerifyNoFromSpaceRefsObjectVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800794 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700795 explicit VerifyNoFromSpaceRefsObjectVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800796 : collector_(collector) {}
797 void operator()(mirror::Object* obj) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700798 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800799 ObjectCallback(obj, collector_);
800 }
801 static void ObjectCallback(mirror::Object* obj, void *arg)
Mathieu Chartier90443472015-07-16 20:32:27 -0700802 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800803 CHECK(obj != nullptr);
804 ConcurrentCopying* collector = reinterpret_cast<ConcurrentCopying*>(arg);
805 space::RegionSpace* region_space = collector->RegionSpace();
806 CHECK(!region_space->IsInFromSpace(obj)) << "Scanning object " << obj << " in from space";
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700807 VerifyNoFromSpaceRefsFieldVisitor visitor(collector);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -0700808 obj->VisitReferences(visitor, visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800809 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800810 CHECK(obj->GetReadBarrierPointer() == ReadBarrier::WhitePtr())
811 << "obj=" << obj << " non-white rb_ptr " << obj->GetReadBarrierPointer();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800812 }
813 }
814
815 private:
816 ConcurrentCopying* const collector_;
817};
818
819// Verify there's no from-space references left after the marking phase.
820void ConcurrentCopying::VerifyNoFromSpaceReferences() {
821 Thread* self = Thread::Current();
822 DCHECK(Locks::mutator_lock_->IsExclusiveHeld(self));
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700823 // Verify all threads have is_gc_marking to be false
824 {
825 MutexLock mu(self, *Locks::thread_list_lock_);
826 std::list<Thread*> thread_list = Runtime::Current()->GetThreadList()->GetList();
827 for (Thread* thread : thread_list) {
828 CHECK(!thread->GetIsGcMarking());
829 }
830 }
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700831 VerifyNoFromSpaceRefsObjectVisitor visitor(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800832 // Roots.
833 {
834 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700835 VerifyNoFromSpaceRefsVisitor ref_visitor(this);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700836 Runtime::Current()->VisitRoots(&ref_visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800837 }
838 // The to-space.
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700839 region_space_->WalkToSpace(VerifyNoFromSpaceRefsObjectVisitor::ObjectCallback, this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800840 // Non-moving spaces.
841 {
842 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
843 heap_->GetMarkBitmap()->Visit(visitor);
844 }
845 // The alloc stack.
846 {
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700847 VerifyNoFromSpaceRefsVisitor ref_visitor(this);
Mathieu Chartiercb535da2015-01-23 13:50:03 -0800848 for (auto* it = heap_->allocation_stack_->Begin(), *end = heap_->allocation_stack_->End();
849 it < end; ++it) {
850 mirror::Object* const obj = it->AsMirrorPtr();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800851 if (obj != nullptr && obj->GetClass() != nullptr) {
852 // TODO: need to call this only if obj is alive?
853 ref_visitor(obj);
854 visitor(obj);
855 }
856 }
857 }
858 // TODO: LOS. But only refs in LOS are classes.
859}
860
861// The following visitors are used to assert the to-space invariant.
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700862class ConcurrentCopying::AssertToSpaceInvariantRefsVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800863 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700864 explicit AssertToSpaceInvariantRefsVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800865 : collector_(collector) {}
866
867 void operator()(mirror::Object* ref) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700868 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800869 if (ref == nullptr) {
870 // OK.
871 return;
872 }
873 collector_->AssertToSpaceInvariant(nullptr, MemberOffset(0), ref);
874 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800875
876 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::AssertToSpaceInvariantFieldVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800881 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700882 explicit AssertToSpaceInvariantFieldVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800883 : collector_(collector) {}
884
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700885 void operator()(mirror::Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700886 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800887 mirror::Object* ref =
888 obj->GetFieldObject<mirror::Object, kDefaultVerifyFlags, kWithoutReadBarrier>(offset);
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700889 AssertToSpaceInvariantRefsVisitor visitor(collector_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800890 visitor(ref);
891 }
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700892 void operator()(mirror::Class* klass, mirror::Reference* ref ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700893 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800894 CHECK(klass->IsTypeOfReferenceClass());
895 }
896
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700897 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
898 SHARED_REQUIRES(Locks::mutator_lock_) {
899 if (!root->IsNull()) {
900 VisitRoot(root);
901 }
902 }
903
904 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
905 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700906 AssertToSpaceInvariantRefsVisitor visitor(collector_);
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700907 visitor(root->AsMirrorPtr());
908 }
909
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800910 private:
Mathieu Chartier97509952015-07-13 14:35:43 -0700911 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800912};
913
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700914class ConcurrentCopying::AssertToSpaceInvariantObjectVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800915 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700916 explicit AssertToSpaceInvariantObjectVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800917 : collector_(collector) {}
918 void operator()(mirror::Object* obj) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700919 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800920 ObjectCallback(obj, collector_);
921 }
922 static void ObjectCallback(mirror::Object* obj, void *arg)
Mathieu Chartier90443472015-07-16 20:32:27 -0700923 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800924 CHECK(obj != nullptr);
925 ConcurrentCopying* collector = reinterpret_cast<ConcurrentCopying*>(arg);
926 space::RegionSpace* region_space = collector->RegionSpace();
927 CHECK(!region_space->IsInFromSpace(obj)) << "Scanning object " << obj << " in from space";
928 collector->AssertToSpaceInvariant(nullptr, MemberOffset(0), obj);
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700929 AssertToSpaceInvariantFieldVisitor visitor(collector);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -0700930 obj->VisitReferences(visitor, visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800931 }
932
933 private:
Mathieu Chartier97509952015-07-13 14:35:43 -0700934 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800935};
936
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700937class ConcurrentCopying::RevokeThreadLocalMarkStackCheckpoint : public Closure {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700938 public:
Roland Levillain3887c462015-08-12 18:15:42 +0100939 RevokeThreadLocalMarkStackCheckpoint(ConcurrentCopying* concurrent_copying,
940 bool disable_weak_ref_access)
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700941 : concurrent_copying_(concurrent_copying),
942 disable_weak_ref_access_(disable_weak_ref_access) {
943 }
944
945 virtual void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
946 // Note: self is not necessarily equal to thread since thread may be suspended.
947 Thread* self = Thread::Current();
948 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
949 << thread->GetState() << " thread " << thread << " self " << self;
950 // Revoke thread local mark stacks.
951 accounting::AtomicStack<mirror::Object>* tl_mark_stack = thread->GetThreadLocalMarkStack();
952 if (tl_mark_stack != nullptr) {
953 MutexLock mu(self, concurrent_copying_->mark_stack_lock_);
954 concurrent_copying_->revoked_mark_stacks_.push_back(tl_mark_stack);
955 thread->SetThreadLocalMarkStack(nullptr);
956 }
957 // Disable weak ref access.
958 if (disable_weak_ref_access_) {
959 thread->SetWeakRefAccessEnabled(false);
960 }
961 // If thread is a running mutator, then act on behalf of the garbage collector.
962 // See the code in ThreadList::RunCheckpoint.
Mathieu Chartier10d25082015-10-28 18:36:09 -0700963 concurrent_copying_->GetBarrier().Pass(self);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700964 }
965
966 private:
967 ConcurrentCopying* const concurrent_copying_;
968 const bool disable_weak_ref_access_;
969};
970
971void ConcurrentCopying::RevokeThreadLocalMarkStacks(bool disable_weak_ref_access) {
972 Thread* self = Thread::Current();
973 RevokeThreadLocalMarkStackCheckpoint check_point(this, disable_weak_ref_access);
974 ThreadList* thread_list = Runtime::Current()->GetThreadList();
975 gc_barrier_->Init(self, 0);
976 size_t barrier_count = thread_list->RunCheckpoint(&check_point);
977 // If there are no threads to wait which implys that all the checkpoint functions are finished,
978 // then no need to release the mutator lock.
979 if (barrier_count == 0) {
980 return;
981 }
982 Locks::mutator_lock_->SharedUnlock(self);
983 {
984 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
985 gc_barrier_->Increment(self, barrier_count);
986 }
987 Locks::mutator_lock_->SharedLock(self);
988}
989
990void ConcurrentCopying::RevokeThreadLocalMarkStack(Thread* thread) {
991 Thread* self = Thread::Current();
992 CHECK_EQ(self, thread);
993 accounting::AtomicStack<mirror::Object>* tl_mark_stack = thread->GetThreadLocalMarkStack();
994 if (tl_mark_stack != nullptr) {
995 CHECK(is_marking_);
996 MutexLock mu(self, mark_stack_lock_);
997 revoked_mark_stacks_.push_back(tl_mark_stack);
998 thread->SetThreadLocalMarkStack(nullptr);
999 }
1000}
1001
1002void ConcurrentCopying::ProcessMarkStack() {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001003 if (kVerboseMode) {
1004 LOG(INFO) << "ProcessMarkStack. ";
1005 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001006 bool empty_prev = false;
1007 while (true) {
1008 bool empty = ProcessMarkStackOnce();
1009 if (empty_prev && empty) {
1010 // Saw empty mark stack for a second time, done.
1011 break;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001012 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001013 empty_prev = empty;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001014 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001015}
1016
1017bool ConcurrentCopying::ProcessMarkStackOnce() {
1018 Thread* self = Thread::Current();
1019 CHECK(thread_running_gc_ != nullptr);
1020 CHECK(self == thread_running_gc_);
1021 CHECK(self->GetThreadLocalMarkStack() == nullptr);
1022 size_t count = 0;
1023 MarkStackMode mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1024 if (mark_stack_mode == kMarkStackModeThreadLocal) {
1025 // Process the thread-local mark stacks and the GC mark stack.
1026 count += ProcessThreadLocalMarkStacks(false);
1027 while (!gc_mark_stack_->IsEmpty()) {
1028 mirror::Object* to_ref = gc_mark_stack_->PopBack();
1029 ProcessMarkStackRef(to_ref);
1030 ++count;
1031 }
1032 gc_mark_stack_->Reset();
1033 } else if (mark_stack_mode == kMarkStackModeShared) {
1034 // Process the shared GC mark stack with a lock.
1035 {
1036 MutexLock mu(self, mark_stack_lock_);
1037 CHECK(revoked_mark_stacks_.empty());
1038 }
1039 while (true) {
1040 std::vector<mirror::Object*> refs;
1041 {
1042 // Copy refs with lock. Note the number of refs should be small.
1043 MutexLock mu(self, mark_stack_lock_);
1044 if (gc_mark_stack_->IsEmpty()) {
1045 break;
1046 }
1047 for (StackReference<mirror::Object>* p = gc_mark_stack_->Begin();
1048 p != gc_mark_stack_->End(); ++p) {
1049 refs.push_back(p->AsMirrorPtr());
1050 }
1051 gc_mark_stack_->Reset();
1052 }
1053 for (mirror::Object* ref : refs) {
1054 ProcessMarkStackRef(ref);
1055 ++count;
1056 }
1057 }
1058 } else {
1059 CHECK_EQ(static_cast<uint32_t>(mark_stack_mode),
1060 static_cast<uint32_t>(kMarkStackModeGcExclusive));
1061 {
1062 MutexLock mu(self, mark_stack_lock_);
1063 CHECK(revoked_mark_stacks_.empty());
1064 }
1065 // Process the GC mark stack in the exclusive mode. No need to take the lock.
1066 while (!gc_mark_stack_->IsEmpty()) {
1067 mirror::Object* to_ref = gc_mark_stack_->PopBack();
1068 ProcessMarkStackRef(to_ref);
1069 ++count;
1070 }
1071 gc_mark_stack_->Reset();
1072 }
1073
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001074 // Return true if the stack was empty.
1075 return count == 0;
1076}
1077
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001078size_t ConcurrentCopying::ProcessThreadLocalMarkStacks(bool disable_weak_ref_access) {
1079 // Run a checkpoint to collect all thread local mark stacks and iterate over them all.
1080 RevokeThreadLocalMarkStacks(disable_weak_ref_access);
1081 size_t count = 0;
1082 std::vector<accounting::AtomicStack<mirror::Object>*> mark_stacks;
1083 {
1084 MutexLock mu(Thread::Current(), mark_stack_lock_);
1085 // Make a copy of the mark stack vector.
1086 mark_stacks = revoked_mark_stacks_;
1087 revoked_mark_stacks_.clear();
1088 }
1089 for (accounting::AtomicStack<mirror::Object>* mark_stack : mark_stacks) {
1090 for (StackReference<mirror::Object>* p = mark_stack->Begin(); p != mark_stack->End(); ++p) {
1091 mirror::Object* to_ref = p->AsMirrorPtr();
1092 ProcessMarkStackRef(to_ref);
1093 ++count;
1094 }
1095 {
1096 MutexLock mu(Thread::Current(), mark_stack_lock_);
1097 if (pooled_mark_stacks_.size() >= kMarkStackPoolSize) {
1098 // The pool has enough. Delete it.
1099 delete mark_stack;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001100 } else {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001101 // Otherwise, put it into the pool for later reuse.
1102 mark_stack->Reset();
1103 pooled_mark_stacks_.push_back(mark_stack);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001104 }
1105 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001106 }
1107 return count;
1108}
1109
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001110inline void ConcurrentCopying::ProcessMarkStackRef(mirror::Object* to_ref) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001111 DCHECK(!region_space_->IsInFromSpace(to_ref));
1112 if (kUseBakerReadBarrier) {
1113 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr())
1114 << " " << to_ref << " " << to_ref->GetReadBarrierPointer()
1115 << " is_marked=" << IsMarked(to_ref);
1116 }
1117 // Scan ref fields.
1118 Scan(to_ref);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001119 if (kUseBakerReadBarrier) {
1120 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr())
1121 << " " << to_ref << " " << to_ref->GetReadBarrierPointer()
1122 << " is_marked=" << IsMarked(to_ref);
1123 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001124#ifdef USE_BAKER_OR_BROOKS_READ_BARRIER
1125 if (UNLIKELY((to_ref->GetClass<kVerifyNone, kWithoutReadBarrier>()->IsTypeOfReferenceClass() &&
1126 to_ref->AsReference()->GetReferent<kWithoutReadBarrier>() != nullptr &&
1127 !IsInToSpace(to_ref->AsReference()->GetReferent<kWithoutReadBarrier>())))) {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001128 // Leave this reference gray in the queue so that GetReferent() will trigger a read barrier. We
1129 // will change it to white later in ReferenceQueue::DequeuePendingReference().
Richard Uhlere3627402016-02-02 13:36:55 -08001130 DCHECK(to_ref->AsReference()->GetPendingNext() != nullptr) << "Left unenqueued ref gray " << to_ref;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001131 } else {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001132 // We may occasionally leave a reference white in the queue if its referent happens to be
1133 // concurrently marked after the Scan() call above has enqueued the Reference, in which case the
1134 // above IsInToSpace() evaluates to true and we change the color from gray to white here in this
1135 // else block.
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001136 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001137 bool success = to_ref->AtomicSetReadBarrierPointer</*kCasRelease*/true>(
1138 ReadBarrier::GrayPtr(),
1139 ReadBarrier::WhitePtr());
1140 DCHECK(success) << "Must succeed as we won the race.";
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001141 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001142 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001143#else
1144 DCHECK(!kUseBakerReadBarrier);
1145#endif
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001146
1147 if (region_space_->IsInUnevacFromSpace(to_ref)) {
1148 // Add to the live bytes per unevacuated from space. Note this code is always run by the
1149 // GC-running thread (no synchronization required).
1150 DCHECK(region_space_bitmap_->Test(to_ref));
1151 // Disable the read barrier in SizeOf for performance, which is safe.
1152 size_t obj_size = to_ref->SizeOf<kDefaultVerifyFlags, kWithoutReadBarrier>();
1153 size_t alloc_size = RoundUp(obj_size, space::RegionSpace::kAlignment);
1154 region_space_->AddLiveBytes(to_ref, alloc_size);
1155 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001156 if (ReadBarrier::kEnableToSpaceInvariantChecks || kIsDebugBuild) {
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001157 AssertToSpaceInvariantObjectVisitor visitor(this);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001158 visitor(to_ref);
1159 }
1160}
1161
1162void ConcurrentCopying::SwitchToSharedMarkStackMode() {
1163 Thread* self = Thread::Current();
1164 CHECK(thread_running_gc_ != nullptr);
1165 CHECK_EQ(self, thread_running_gc_);
1166 CHECK(self->GetThreadLocalMarkStack() == nullptr);
1167 MarkStackMode before_mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1168 CHECK_EQ(static_cast<uint32_t>(before_mark_stack_mode),
1169 static_cast<uint32_t>(kMarkStackModeThreadLocal));
1170 mark_stack_mode_.StoreRelaxed(kMarkStackModeShared);
1171 CHECK(weak_ref_access_enabled_.LoadRelaxed());
1172 weak_ref_access_enabled_.StoreRelaxed(false);
1173 QuasiAtomic::ThreadFenceForConstructor();
1174 // Process the thread local mark stacks one last time after switching to the shared mark stack
1175 // mode and disable weak ref accesses.
1176 ProcessThreadLocalMarkStacks(true);
1177 if (kVerboseMode) {
1178 LOG(INFO) << "Switched to shared mark stack mode and disabled weak ref access";
1179 }
1180}
1181
1182void ConcurrentCopying::SwitchToGcExclusiveMarkStackMode() {
1183 Thread* self = Thread::Current();
1184 CHECK(thread_running_gc_ != nullptr);
1185 CHECK_EQ(self, thread_running_gc_);
1186 CHECK(self->GetThreadLocalMarkStack() == nullptr);
1187 MarkStackMode before_mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1188 CHECK_EQ(static_cast<uint32_t>(before_mark_stack_mode),
1189 static_cast<uint32_t>(kMarkStackModeShared));
1190 mark_stack_mode_.StoreRelaxed(kMarkStackModeGcExclusive);
1191 QuasiAtomic::ThreadFenceForConstructor();
1192 if (kVerboseMode) {
1193 LOG(INFO) << "Switched to GC exclusive mark stack mode";
1194 }
1195}
1196
1197void ConcurrentCopying::CheckEmptyMarkStack() {
1198 Thread* self = Thread::Current();
1199 CHECK(thread_running_gc_ != nullptr);
1200 CHECK_EQ(self, thread_running_gc_);
1201 CHECK(self->GetThreadLocalMarkStack() == nullptr);
1202 MarkStackMode mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1203 if (mark_stack_mode == kMarkStackModeThreadLocal) {
1204 // Thread-local mark stack mode.
1205 RevokeThreadLocalMarkStacks(false);
1206 MutexLock mu(Thread::Current(), mark_stack_lock_);
1207 if (!revoked_mark_stacks_.empty()) {
1208 for (accounting::AtomicStack<mirror::Object>* mark_stack : revoked_mark_stacks_) {
1209 while (!mark_stack->IsEmpty()) {
1210 mirror::Object* obj = mark_stack->PopBack();
1211 if (kUseBakerReadBarrier) {
1212 mirror::Object* rb_ptr = obj->GetReadBarrierPointer();
1213 LOG(INFO) << "On mark queue : " << obj << " " << PrettyTypeOf(obj) << " rb_ptr=" << rb_ptr
1214 << " is_marked=" << IsMarked(obj);
1215 } else {
1216 LOG(INFO) << "On mark queue : " << obj << " " << PrettyTypeOf(obj)
1217 << " is_marked=" << IsMarked(obj);
1218 }
1219 }
1220 }
1221 LOG(FATAL) << "mark stack is not empty";
1222 }
1223 } else {
1224 // Shared, GC-exclusive, or off.
1225 MutexLock mu(Thread::Current(), mark_stack_lock_);
1226 CHECK(gc_mark_stack_->IsEmpty());
1227 CHECK(revoked_mark_stacks_.empty());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001228 }
1229}
1230
1231void ConcurrentCopying::SweepSystemWeaks(Thread* self) {
1232 TimingLogger::ScopedTiming split("SweepSystemWeaks", GetTimings());
1233 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier97509952015-07-13 14:35:43 -07001234 Runtime::Current()->SweepSystemWeaks(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001235}
1236
1237void ConcurrentCopying::Sweep(bool swap_bitmaps) {
1238 {
1239 TimingLogger::ScopedTiming t("MarkStackAsLive", GetTimings());
1240 accounting::ObjectStack* live_stack = heap_->GetLiveStack();
1241 if (kEnableFromSpaceAccountingCheck) {
1242 CHECK_GE(live_stack_freeze_size_, live_stack->Size());
1243 }
1244 heap_->MarkAllocStackAsLive(live_stack);
1245 live_stack->Reset();
1246 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001247 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001248 TimingLogger::ScopedTiming split("Sweep", GetTimings());
1249 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
1250 if (space->IsContinuousMemMapAllocSpace()) {
1251 space::ContinuousMemMapAllocSpace* alloc_space = space->AsContinuousMemMapAllocSpace();
Mathieu Chartier763a31e2015-11-16 16:05:55 -08001252 if (space == region_space_ || immune_spaces_.ContainsSpace(space)) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001253 continue;
1254 }
1255 TimingLogger::ScopedTiming split2(
1256 alloc_space->IsZygoteSpace() ? "SweepZygoteSpace" : "SweepAllocSpace", GetTimings());
1257 RecordFree(alloc_space->Sweep(swap_bitmaps));
1258 }
1259 }
1260 SweepLargeObjects(swap_bitmaps);
1261}
1262
1263void ConcurrentCopying::SweepLargeObjects(bool swap_bitmaps) {
1264 TimingLogger::ScopedTiming split("SweepLargeObjects", GetTimings());
1265 RecordFreeLOS(heap_->GetLargeObjectsSpace()->Sweep(swap_bitmaps));
1266}
1267
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001268void ConcurrentCopying::ReclaimPhase() {
1269 TimingLogger::ScopedTiming split("ReclaimPhase", GetTimings());
1270 if (kVerboseMode) {
1271 LOG(INFO) << "GC ReclaimPhase";
1272 }
1273 Thread* self = Thread::Current();
1274
1275 {
1276 // Double-check that the mark stack is empty.
1277 // Note: need to set this after VerifyNoFromSpaceRef().
1278 is_asserting_to_space_invariant_ = false;
1279 QuasiAtomic::ThreadFenceForConstructor();
1280 if (kVerboseMode) {
1281 LOG(INFO) << "Issue an empty check point. ";
1282 }
1283 IssueEmptyCheckpoint();
1284 // Disable the check.
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001285 is_mark_stack_push_disallowed_.StoreSequentiallyConsistent(0);
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001286 if (kUseBakerReadBarrier) {
1287 updated_all_immune_objects_.StoreSequentiallyConsistent(false);
1288 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001289 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001290 }
1291
1292 {
1293 // Record freed objects.
1294 TimingLogger::ScopedTiming split2("RecordFree", GetTimings());
1295 // Don't include thread-locals that are in the to-space.
1296 uint64_t from_bytes = region_space_->GetBytesAllocatedInFromSpace();
1297 uint64_t from_objects = region_space_->GetObjectsAllocatedInFromSpace();
1298 uint64_t unevac_from_bytes = region_space_->GetBytesAllocatedInUnevacFromSpace();
1299 uint64_t unevac_from_objects = region_space_->GetObjectsAllocatedInUnevacFromSpace();
1300 uint64_t to_bytes = bytes_moved_.LoadSequentiallyConsistent();
1301 uint64_t to_objects = objects_moved_.LoadSequentiallyConsistent();
1302 if (kEnableFromSpaceAccountingCheck) {
1303 CHECK_EQ(from_space_num_objects_at_first_pause_, from_objects + unevac_from_objects);
1304 CHECK_EQ(from_space_num_bytes_at_first_pause_, from_bytes + unevac_from_bytes);
1305 }
1306 CHECK_LE(to_objects, from_objects);
1307 CHECK_LE(to_bytes, from_bytes);
1308 int64_t freed_bytes = from_bytes - to_bytes;
1309 int64_t freed_objects = from_objects - to_objects;
1310 if (kVerboseMode) {
1311 LOG(INFO) << "RecordFree:"
1312 << " from_bytes=" << from_bytes << " from_objects=" << from_objects
1313 << " unevac_from_bytes=" << unevac_from_bytes << " unevac_from_objects=" << unevac_from_objects
1314 << " to_bytes=" << to_bytes << " to_objects=" << to_objects
1315 << " freed_bytes=" << freed_bytes << " freed_objects=" << freed_objects
1316 << " from_space size=" << region_space_->FromSpaceSize()
1317 << " unevac_from_space size=" << region_space_->UnevacFromSpaceSize()
1318 << " to_space size=" << region_space_->ToSpaceSize();
1319 LOG(INFO) << "(before) num_bytes_allocated=" << heap_->num_bytes_allocated_.LoadSequentiallyConsistent();
1320 }
1321 RecordFree(ObjectBytePair(freed_objects, freed_bytes));
1322 if (kVerboseMode) {
1323 LOG(INFO) << "(after) num_bytes_allocated=" << heap_->num_bytes_allocated_.LoadSequentiallyConsistent();
1324 }
1325 }
1326
1327 {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001328 TimingLogger::ScopedTiming split4("ClearFromSpace", GetTimings());
1329 region_space_->ClearFromSpace();
1330 }
1331
1332 {
1333 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001334 Sweep(false);
1335 SwapBitmaps();
1336 heap_->UnBindBitmaps();
1337
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001338 // Delete the region bitmap.
1339 DCHECK(region_space_bitmap_ != nullptr);
1340 delete region_space_bitmap_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001341 region_space_bitmap_ = nullptr;
1342 }
1343
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001344 CheckEmptyMarkStack();
1345
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001346 if (kVerboseMode) {
1347 LOG(INFO) << "GC end of ReclaimPhase";
1348 }
1349}
1350
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001351// Assert the to-space invariant.
1352void ConcurrentCopying::AssertToSpaceInvariant(mirror::Object* obj, MemberOffset offset,
1353 mirror::Object* ref) {
1354 CHECK(heap_->collector_type_ == kCollectorTypeCC) << static_cast<size_t>(heap_->collector_type_);
1355 if (is_asserting_to_space_invariant_) {
1356 if (region_space_->IsInToSpace(ref)) {
1357 // OK.
1358 return;
1359 } else if (region_space_->IsInUnevacFromSpace(ref)) {
1360 CHECK(region_space_bitmap_->Test(ref)) << ref;
1361 } else if (region_space_->IsInFromSpace(ref)) {
1362 // Not OK. Do extra logging.
1363 if (obj != nullptr) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001364 LogFromSpaceRefHolder(obj, offset);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001365 }
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001366 ref->GetLockWord(false).Dump(LOG(INTERNAL_FATAL));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001367 CHECK(false) << "Found from-space ref " << ref << " " << PrettyTypeOf(ref);
1368 } else {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001369 AssertToSpaceInvariantInNonMovingSpace(obj, ref);
1370 }
1371 }
1372}
1373
1374class RootPrinter {
1375 public:
1376 RootPrinter() { }
1377
1378 template <class MirrorType>
1379 ALWAYS_INLINE void VisitRootIfNonNull(mirror::CompressedReference<MirrorType>* root)
Mathieu Chartier90443472015-07-16 20:32:27 -07001380 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001381 if (!root->IsNull()) {
1382 VisitRoot(root);
1383 }
1384 }
1385
1386 template <class MirrorType>
1387 void VisitRoot(mirror::Object** root)
Mathieu Chartier90443472015-07-16 20:32:27 -07001388 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001389 LOG(INTERNAL_FATAL) << "root=" << root << " ref=" << *root;
1390 }
1391
1392 template <class MirrorType>
1393 void VisitRoot(mirror::CompressedReference<MirrorType>* root)
Mathieu Chartier90443472015-07-16 20:32:27 -07001394 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001395 LOG(INTERNAL_FATAL) << "root=" << root << " ref=" << root->AsMirrorPtr();
1396 }
1397};
1398
1399void ConcurrentCopying::AssertToSpaceInvariant(GcRootSource* gc_root_source,
1400 mirror::Object* ref) {
1401 CHECK(heap_->collector_type_ == kCollectorTypeCC) << static_cast<size_t>(heap_->collector_type_);
1402 if (is_asserting_to_space_invariant_) {
1403 if (region_space_->IsInToSpace(ref)) {
1404 // OK.
1405 return;
1406 } else if (region_space_->IsInUnevacFromSpace(ref)) {
1407 CHECK(region_space_bitmap_->Test(ref)) << ref;
1408 } else if (region_space_->IsInFromSpace(ref)) {
1409 // Not OK. Do extra logging.
1410 if (gc_root_source == nullptr) {
1411 // No info.
1412 } else if (gc_root_source->HasArtField()) {
1413 ArtField* field = gc_root_source->GetArtField();
1414 LOG(INTERNAL_FATAL) << "gc root in field " << field << " " << PrettyField(field);
1415 RootPrinter root_printer;
1416 field->VisitRoots(root_printer);
1417 } else if (gc_root_source->HasArtMethod()) {
1418 ArtMethod* method = gc_root_source->GetArtMethod();
1419 LOG(INTERNAL_FATAL) << "gc root in method " << method << " " << PrettyMethod(method);
1420 RootPrinter root_printer;
Mathieu Chartier1147b9b2015-09-14 18:50:08 -07001421 method->VisitRoots(root_printer, sizeof(void*));
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001422 }
1423 ref->GetLockWord(false).Dump(LOG(INTERNAL_FATAL));
1424 region_space_->DumpNonFreeRegions(LOG(INTERNAL_FATAL));
1425 PrintFileToLog("/proc/self/maps", LogSeverity::INTERNAL_FATAL);
1426 MemMap::DumpMaps(LOG(INTERNAL_FATAL), true);
1427 CHECK(false) << "Found from-space ref " << ref << " " << PrettyTypeOf(ref);
1428 } else {
1429 AssertToSpaceInvariantInNonMovingSpace(nullptr, ref);
1430 }
1431 }
1432}
1433
1434void ConcurrentCopying::LogFromSpaceRefHolder(mirror::Object* obj, MemberOffset offset) {
1435 if (kUseBakerReadBarrier) {
1436 LOG(INFO) << "holder=" << obj << " " << PrettyTypeOf(obj)
1437 << " holder rb_ptr=" << obj->GetReadBarrierPointer();
1438 } else {
1439 LOG(INFO) << "holder=" << obj << " " << PrettyTypeOf(obj);
1440 }
1441 if (region_space_->IsInFromSpace(obj)) {
1442 LOG(INFO) << "holder is in the from-space.";
1443 } else if (region_space_->IsInToSpace(obj)) {
1444 LOG(INFO) << "holder is in the to-space.";
1445 } else if (region_space_->IsInUnevacFromSpace(obj)) {
1446 LOG(INFO) << "holder is in the unevac from-space.";
1447 if (region_space_bitmap_->Test(obj)) {
1448 LOG(INFO) << "holder is marked in the region space bitmap.";
1449 } else {
1450 LOG(INFO) << "holder is not marked in the region space bitmap.";
1451 }
1452 } else {
1453 // In a non-moving space.
Mathieu Chartier763a31e2015-11-16 16:05:55 -08001454 if (immune_spaces_.ContainsObject(obj)) {
1455 LOG(INFO) << "holder is in an immune image or the zygote space.";
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001456 } else {
Mathieu Chartier763a31e2015-11-16 16:05:55 -08001457 LOG(INFO) << "holder is in a non-immune, non-moving (or main) space.";
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001458 accounting::ContinuousSpaceBitmap* mark_bitmap =
1459 heap_mark_bitmap_->GetContinuousSpaceBitmap(obj);
1460 accounting::LargeObjectBitmap* los_bitmap =
1461 heap_mark_bitmap_->GetLargeObjectBitmap(obj);
1462 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
1463 bool is_los = mark_bitmap == nullptr;
1464 if (!is_los && mark_bitmap->Test(obj)) {
1465 LOG(INFO) << "holder is marked in the mark bit map.";
1466 } else if (is_los && los_bitmap->Test(obj)) {
1467 LOG(INFO) << "holder is marked in the los bit map.";
1468 } else {
1469 // If ref is on the allocation stack, then it is considered
1470 // mark/alive (but not necessarily on the live stack.)
1471 if (IsOnAllocStack(obj)) {
1472 LOG(INFO) << "holder is on the alloc stack.";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001473 } else {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001474 LOG(INFO) << "holder is not marked or on the alloc stack.";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001475 }
1476 }
1477 }
1478 }
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001479 LOG(INFO) << "offset=" << offset.SizeValue();
1480}
1481
1482void ConcurrentCopying::AssertToSpaceInvariantInNonMovingSpace(mirror::Object* obj,
1483 mirror::Object* ref) {
1484 // In a non-moving spaces. Check that the ref is marked.
Mathieu Chartier763a31e2015-11-16 16:05:55 -08001485 if (immune_spaces_.ContainsObject(ref)) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001486 if (kUseBakerReadBarrier) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001487 // Immune object may not be gray if called from the GC.
1488 if (Thread::Current() == thread_running_gc_ && !gc_grays_immune_objects_) {
1489 return;
1490 }
1491 bool updated_all_immune_objects = updated_all_immune_objects_.LoadSequentiallyConsistent();
1492 CHECK(updated_all_immune_objects || ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr())
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001493 << "Unmarked immune space ref. obj=" << obj << " rb_ptr="
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001494 << (obj != nullptr ? obj->GetReadBarrierPointer() : nullptr)
1495 << " ref=" << ref << " ref rb_ptr=" << ref->GetReadBarrierPointer()
1496 << " updated_all_immune_objects=" << updated_all_immune_objects;
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001497 }
1498 } else {
1499 accounting::ContinuousSpaceBitmap* mark_bitmap =
1500 heap_mark_bitmap_->GetContinuousSpaceBitmap(ref);
1501 accounting::LargeObjectBitmap* los_bitmap =
1502 heap_mark_bitmap_->GetLargeObjectBitmap(ref);
1503 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
1504 bool is_los = mark_bitmap == nullptr;
1505 if ((!is_los && mark_bitmap->Test(ref)) ||
1506 (is_los && los_bitmap->Test(ref))) {
1507 // OK.
1508 } else {
1509 // If ref is on the allocation stack, then it may not be
1510 // marked live, but considered marked/alive (but not
1511 // necessarily on the live stack).
1512 CHECK(IsOnAllocStack(ref)) << "Unmarked ref that's not on the allocation stack. "
1513 << "obj=" << obj << " ref=" << ref;
1514 }
1515 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001516}
1517
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001518// Used to scan ref fields of an object.
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001519class ConcurrentCopying::RefFieldsVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001520 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001521 explicit RefFieldsVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001522 : collector_(collector) {}
1523
1524 void operator()(mirror::Object* obj, MemberOffset offset, bool /* is_static */)
Mathieu Chartier90443472015-07-16 20:32:27 -07001525 const ALWAYS_INLINE SHARED_REQUIRES(Locks::mutator_lock_)
1526 SHARED_REQUIRES(Locks::heap_bitmap_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001527 collector_->Process(obj, offset);
1528 }
1529
1530 void operator()(mirror::Class* klass, mirror::Reference* ref) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001531 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001532 CHECK(klass->IsTypeOfReferenceClass());
1533 collector_->DelayReferenceReferent(klass, ref);
1534 }
1535
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001536 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001537 ALWAYS_INLINE
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001538 SHARED_REQUIRES(Locks::mutator_lock_) {
1539 if (!root->IsNull()) {
1540 VisitRoot(root);
1541 }
1542 }
1543
1544 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001545 ALWAYS_INLINE
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001546 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001547 collector_->MarkRoot</*kGrayImmuneObject*/false>(root);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001548 }
1549
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001550 private:
1551 ConcurrentCopying* const collector_;
1552};
1553
1554// Scan ref fields of an object.
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001555inline void ConcurrentCopying::Scan(mirror::Object* to_ref) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001556 DCHECK(!region_space_->IsInFromSpace(to_ref));
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001557 DCHECK_EQ(Thread::Current(), thread_running_gc_);
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001558 RefFieldsVisitor visitor(this);
Hiroshi Yamauchi5496f692016-02-17 13:29:59 -08001559 // Disable the read barrier for a performance reason.
1560 to_ref->VisitReferences</*kVisitNativeRoots*/true, kDefaultVerifyFlags, kWithoutReadBarrier>(
1561 visitor, visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001562}
1563
1564// Process a field.
1565inline void ConcurrentCopying::Process(mirror::Object* obj, MemberOffset offset) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001566 DCHECK_EQ(Thread::Current(), thread_running_gc_);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001567 mirror::Object* ref = obj->GetFieldObject<
1568 mirror::Object, kVerifyNone, kWithoutReadBarrier, false>(offset);
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001569 mirror::Object* to_ref = Mark</*kGrayImmuneObject*/false>(ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001570 if (to_ref == ref) {
1571 return;
1572 }
1573 // This may fail if the mutator writes to the field at the same time. But it's ok.
1574 mirror::Object* expected_ref = ref;
1575 mirror::Object* new_ref = to_ref;
1576 do {
1577 if (expected_ref !=
1578 obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier, false>(offset)) {
1579 // It was updated by the mutator.
1580 break;
1581 }
Hiroshi Yamauchifed3e2f2015-10-20 11:11:56 -07001582 } while (!obj->CasFieldWeakRelaxedObjectWithoutWriteBarrier<
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001583 false, false, kVerifyNone>(offset, expected_ref, new_ref));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001584}
1585
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001586// Process some roots.
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001587inline void ConcurrentCopying::VisitRoots(
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001588 mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED) {
1589 for (size_t i = 0; i < count; ++i) {
1590 mirror::Object** root = roots[i];
1591 mirror::Object* ref = *root;
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001592 mirror::Object* to_ref = Mark(ref);
1593 if (to_ref == ref) {
Mathieu Chartier4809d0a2015-04-07 10:39:04 -07001594 continue;
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001595 }
1596 Atomic<mirror::Object*>* addr = reinterpret_cast<Atomic<mirror::Object*>*>(root);
1597 mirror::Object* expected_ref = ref;
1598 mirror::Object* new_ref = to_ref;
1599 do {
1600 if (expected_ref != addr->LoadRelaxed()) {
1601 // It was updated by the mutator.
1602 break;
1603 }
Hiroshi Yamauchifed3e2f2015-10-20 11:11:56 -07001604 } while (!addr->CompareExchangeWeakRelaxed(expected_ref, new_ref));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001605 }
1606}
1607
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001608template<bool kGrayImmuneObject>
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001609inline void ConcurrentCopying::MarkRoot(mirror::CompressedReference<mirror::Object>* root) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001610 DCHECK(!root->IsNull());
1611 mirror::Object* const ref = root->AsMirrorPtr();
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001612 mirror::Object* to_ref = Mark<kGrayImmuneObject>(ref);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001613 if (to_ref != ref) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001614 auto* addr = reinterpret_cast<Atomic<mirror::CompressedReference<mirror::Object>>*>(root);
1615 auto expected_ref = mirror::CompressedReference<mirror::Object>::FromMirrorPtr(ref);
1616 auto new_ref = mirror::CompressedReference<mirror::Object>::FromMirrorPtr(to_ref);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001617 // If the cas fails, then it was updated by the mutator.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001618 do {
1619 if (ref != addr->LoadRelaxed().AsMirrorPtr()) {
1620 // It was updated by the mutator.
1621 break;
1622 }
Hiroshi Yamauchifed3e2f2015-10-20 11:11:56 -07001623 } while (!addr->CompareExchangeWeakRelaxed(expected_ref, new_ref));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001624 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001625}
1626
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001627inline void ConcurrentCopying::VisitRoots(
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001628 mirror::CompressedReference<mirror::Object>** roots, size_t count,
1629 const RootInfo& info ATTRIBUTE_UNUSED) {
1630 for (size_t i = 0; i < count; ++i) {
1631 mirror::CompressedReference<mirror::Object>* const root = roots[i];
1632 if (!root->IsNull()) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001633 // kGrayImmuneObject is true because this is used for the thread flip.
1634 MarkRoot</*kGrayImmuneObject*/true>(root);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001635 }
1636 }
1637}
1638
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001639// Temporary set gc_grays_immune_objects_ to true in a scope if the current thread is GC.
1640class ConcurrentCopying::ScopedGcGraysImmuneObjects {
1641 public:
1642 explicit ScopedGcGraysImmuneObjects(ConcurrentCopying* collector)
1643 : collector_(collector), enabled_(false) {
1644 if (kUseBakerReadBarrier &&
1645 collector_->thread_running_gc_ == Thread::Current() &&
1646 !collector_->gc_grays_immune_objects_) {
1647 collector_->gc_grays_immune_objects_ = true;
1648 enabled_ = true;
1649 }
1650 }
1651
1652 ~ScopedGcGraysImmuneObjects() {
1653 if (kUseBakerReadBarrier &&
1654 collector_->thread_running_gc_ == Thread::Current() &&
1655 enabled_) {
1656 DCHECK(collector_->gc_grays_immune_objects_);
1657 collector_->gc_grays_immune_objects_ = false;
1658 }
1659 }
1660
1661 private:
1662 ConcurrentCopying* const collector_;
1663 bool enabled_;
1664};
1665
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001666// Fill the given memory block with a dummy object. Used to fill in a
1667// copy of objects that was lost in race.
1668void ConcurrentCopying::FillWithDummyObject(mirror::Object* dummy_obj, size_t byte_size) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001669 // GC doesn't gray immune objects while scanning immune objects. But we need to trigger the read
1670 // barriers here because we need the updated reference to the int array class, etc. Temporary set
1671 // gc_grays_immune_objects_ to true so that we won't cause a DCHECK failure in MarkImmuneSpace().
1672 ScopedGcGraysImmuneObjects scoped_gc_gray_immune_objects(this);
Roland Levillain14d90572015-07-16 10:52:26 +01001673 CHECK_ALIGNED(byte_size, kObjectAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001674 memset(dummy_obj, 0, byte_size);
1675 mirror::Class* int_array_class = mirror::IntArray::GetArrayClass();
1676 CHECK(int_array_class != nullptr);
1677 AssertToSpaceInvariant(nullptr, MemberOffset(0), int_array_class);
1678 size_t component_size = int_array_class->GetComponentSize();
1679 CHECK_EQ(component_size, sizeof(int32_t));
1680 size_t data_offset = mirror::Array::DataOffset(component_size).SizeValue();
1681 if (data_offset > byte_size) {
1682 // An int array is too big. Use java.lang.Object.
1683 mirror::Class* java_lang_Object = WellKnownClasses::ToClass(WellKnownClasses::java_lang_Object);
1684 AssertToSpaceInvariant(nullptr, MemberOffset(0), java_lang_Object);
1685 CHECK_EQ(byte_size, java_lang_Object->GetObjectSize());
1686 dummy_obj->SetClass(java_lang_Object);
1687 CHECK_EQ(byte_size, dummy_obj->SizeOf());
1688 } else {
1689 // Use an int array.
1690 dummy_obj->SetClass(int_array_class);
1691 CHECK(dummy_obj->IsArrayInstance());
1692 int32_t length = (byte_size - data_offset) / component_size;
1693 dummy_obj->AsArray()->SetLength(length);
1694 CHECK_EQ(dummy_obj->AsArray()->GetLength(), length)
1695 << "byte_size=" << byte_size << " length=" << length
1696 << " component_size=" << component_size << " data_offset=" << data_offset;
1697 CHECK_EQ(byte_size, dummy_obj->SizeOf())
1698 << "byte_size=" << byte_size << " length=" << length
1699 << " component_size=" << component_size << " data_offset=" << data_offset;
1700 }
1701}
1702
1703// Reuse the memory blocks that were copy of objects that were lost in race.
1704mirror::Object* ConcurrentCopying::AllocateInSkippedBlock(size_t alloc_size) {
1705 // Try to reuse the blocks that were unused due to CAS failures.
Roland Levillain14d90572015-07-16 10:52:26 +01001706 CHECK_ALIGNED(alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001707 Thread* self = Thread::Current();
1708 size_t min_object_size = RoundUp(sizeof(mirror::Object), space::RegionSpace::kAlignment);
1709 MutexLock mu(self, skipped_blocks_lock_);
1710 auto it = skipped_blocks_map_.lower_bound(alloc_size);
1711 if (it == skipped_blocks_map_.end()) {
1712 // Not found.
1713 return nullptr;
1714 }
1715 {
1716 size_t byte_size = it->first;
1717 CHECK_GE(byte_size, alloc_size);
1718 if (byte_size > alloc_size && byte_size - alloc_size < min_object_size) {
1719 // If remainder would be too small for a dummy object, retry with a larger request size.
1720 it = skipped_blocks_map_.lower_bound(alloc_size + min_object_size);
1721 if (it == skipped_blocks_map_.end()) {
1722 // Not found.
1723 return nullptr;
1724 }
Roland Levillain14d90572015-07-16 10:52:26 +01001725 CHECK_ALIGNED(it->first - alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001726 CHECK_GE(it->first - alloc_size, min_object_size)
1727 << "byte_size=" << byte_size << " it->first=" << it->first << " alloc_size=" << alloc_size;
1728 }
1729 }
1730 // Found a block.
1731 CHECK(it != skipped_blocks_map_.end());
1732 size_t byte_size = it->first;
1733 uint8_t* addr = it->second;
1734 CHECK_GE(byte_size, alloc_size);
1735 CHECK(region_space_->IsInToSpace(reinterpret_cast<mirror::Object*>(addr)));
Roland Levillain14d90572015-07-16 10:52:26 +01001736 CHECK_ALIGNED(byte_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001737 if (kVerboseMode) {
1738 LOG(INFO) << "Reusing skipped bytes : " << reinterpret_cast<void*>(addr) << ", " << byte_size;
1739 }
1740 skipped_blocks_map_.erase(it);
1741 memset(addr, 0, byte_size);
1742 if (byte_size > alloc_size) {
1743 // Return the remainder to the map.
Roland Levillain14d90572015-07-16 10:52:26 +01001744 CHECK_ALIGNED(byte_size - alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001745 CHECK_GE(byte_size - alloc_size, min_object_size);
1746 FillWithDummyObject(reinterpret_cast<mirror::Object*>(addr + alloc_size),
1747 byte_size - alloc_size);
1748 CHECK(region_space_->IsInToSpace(reinterpret_cast<mirror::Object*>(addr + alloc_size)));
1749 skipped_blocks_map_.insert(std::make_pair(byte_size - alloc_size, addr + alloc_size));
1750 }
1751 return reinterpret_cast<mirror::Object*>(addr);
1752}
1753
1754mirror::Object* ConcurrentCopying::Copy(mirror::Object* from_ref) {
1755 DCHECK(region_space_->IsInFromSpace(from_ref));
1756 // No read barrier to avoid nested RB that might violate the to-space
1757 // invariant. Note that from_ref is a from space ref so the SizeOf()
1758 // call will access the from-space meta objects, but it's ok and necessary.
1759 size_t obj_size = from_ref->SizeOf<kDefaultVerifyFlags, kWithoutReadBarrier>();
1760 size_t region_space_alloc_size = RoundUp(obj_size, space::RegionSpace::kAlignment);
1761 size_t region_space_bytes_allocated = 0U;
1762 size_t non_moving_space_bytes_allocated = 0U;
1763 size_t bytes_allocated = 0U;
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001764 size_t dummy;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001765 mirror::Object* to_ref = region_space_->AllocNonvirtual<true>(
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001766 region_space_alloc_size, &region_space_bytes_allocated, nullptr, &dummy);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001767 bytes_allocated = region_space_bytes_allocated;
1768 if (to_ref != nullptr) {
1769 DCHECK_EQ(region_space_alloc_size, region_space_bytes_allocated);
1770 }
1771 bool fall_back_to_non_moving = false;
1772 if (UNLIKELY(to_ref == nullptr)) {
1773 // Failed to allocate in the region space. Try the skipped blocks.
1774 to_ref = AllocateInSkippedBlock(region_space_alloc_size);
1775 if (to_ref != nullptr) {
1776 // Succeeded to allocate in a skipped block.
1777 if (heap_->use_tlab_) {
1778 // This is necessary for the tlab case as it's not accounted in the space.
1779 region_space_->RecordAlloc(to_ref);
1780 }
1781 bytes_allocated = region_space_alloc_size;
1782 } else {
1783 // Fall back to the non-moving space.
1784 fall_back_to_non_moving = true;
1785 if (kVerboseMode) {
1786 LOG(INFO) << "Out of memory in the to-space. Fall back to non-moving. skipped_bytes="
1787 << to_space_bytes_skipped_.LoadSequentiallyConsistent()
1788 << " skipped_objects=" << to_space_objects_skipped_.LoadSequentiallyConsistent();
1789 }
1790 fall_back_to_non_moving = true;
1791 to_ref = heap_->non_moving_space_->Alloc(Thread::Current(), obj_size,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001792 &non_moving_space_bytes_allocated, nullptr, &dummy);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001793 CHECK(to_ref != nullptr) << "Fall-back non-moving space allocation failed";
1794 bytes_allocated = non_moving_space_bytes_allocated;
1795 // Mark it in the mark bitmap.
1796 accounting::ContinuousSpaceBitmap* mark_bitmap =
1797 heap_mark_bitmap_->GetContinuousSpaceBitmap(to_ref);
1798 CHECK(mark_bitmap != nullptr);
1799 CHECK(!mark_bitmap->AtomicTestAndSet(to_ref));
1800 }
1801 }
1802 DCHECK(to_ref != nullptr);
1803
1804 // Attempt to install the forward pointer. This is in a loop as the
1805 // lock word atomic write can fail.
1806 while (true) {
1807 // Copy the object. TODO: copy only the lockword in the second iteration and on?
1808 memcpy(to_ref, from_ref, obj_size);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001809
1810 LockWord old_lock_word = to_ref->GetLockWord(false);
1811
1812 if (old_lock_word.GetState() == LockWord::kForwardingAddress) {
1813 // Lost the race. Another thread (either GC or mutator) stored
1814 // the forwarding pointer first. Make the lost copy (to_ref)
1815 // look like a valid but dead (dummy) object and keep it for
1816 // future reuse.
1817 FillWithDummyObject(to_ref, bytes_allocated);
1818 if (!fall_back_to_non_moving) {
1819 DCHECK(region_space_->IsInToSpace(to_ref));
1820 if (bytes_allocated > space::RegionSpace::kRegionSize) {
1821 // Free the large alloc.
1822 region_space_->FreeLarge(to_ref, bytes_allocated);
1823 } else {
1824 // Record the lost copy for later reuse.
1825 heap_->num_bytes_allocated_.FetchAndAddSequentiallyConsistent(bytes_allocated);
1826 to_space_bytes_skipped_.FetchAndAddSequentiallyConsistent(bytes_allocated);
1827 to_space_objects_skipped_.FetchAndAddSequentiallyConsistent(1);
1828 MutexLock mu(Thread::Current(), skipped_blocks_lock_);
1829 skipped_blocks_map_.insert(std::make_pair(bytes_allocated,
1830 reinterpret_cast<uint8_t*>(to_ref)));
1831 }
1832 } else {
1833 DCHECK(heap_->non_moving_space_->HasAddress(to_ref));
1834 DCHECK_EQ(bytes_allocated, non_moving_space_bytes_allocated);
1835 // Free the non-moving-space chunk.
1836 accounting::ContinuousSpaceBitmap* mark_bitmap =
1837 heap_mark_bitmap_->GetContinuousSpaceBitmap(to_ref);
1838 CHECK(mark_bitmap != nullptr);
1839 CHECK(mark_bitmap->Clear(to_ref));
1840 heap_->non_moving_space_->Free(Thread::Current(), to_ref);
1841 }
1842
1843 // Get the winner's forward ptr.
1844 mirror::Object* lost_fwd_ptr = to_ref;
1845 to_ref = reinterpret_cast<mirror::Object*>(old_lock_word.ForwardingAddress());
1846 CHECK(to_ref != nullptr);
1847 CHECK_NE(to_ref, lost_fwd_ptr);
1848 CHECK(region_space_->IsInToSpace(to_ref) || heap_->non_moving_space_->HasAddress(to_ref));
1849 CHECK_NE(to_ref->GetLockWord(false).GetState(), LockWord::kForwardingAddress);
1850 return to_ref;
1851 }
1852
Hiroshi Yamauchi60f63f52015-04-23 16:12:40 -07001853 // Set the gray ptr.
1854 if (kUseBakerReadBarrier) {
1855 to_ref->SetReadBarrierPointer(ReadBarrier::GrayPtr());
1856 }
1857
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001858 LockWord new_lock_word = LockWord::FromForwardingAddress(reinterpret_cast<size_t>(to_ref));
1859
1860 // Try to atomically write the fwd ptr.
1861 bool success = from_ref->CasLockWordWeakSequentiallyConsistent(old_lock_word, new_lock_word);
1862 if (LIKELY(success)) {
1863 // The CAS succeeded.
1864 objects_moved_.FetchAndAddSequentiallyConsistent(1);
1865 bytes_moved_.FetchAndAddSequentiallyConsistent(region_space_alloc_size);
1866 if (LIKELY(!fall_back_to_non_moving)) {
1867 DCHECK(region_space_->IsInToSpace(to_ref));
1868 } else {
1869 DCHECK(heap_->non_moving_space_->HasAddress(to_ref));
1870 DCHECK_EQ(bytes_allocated, non_moving_space_bytes_allocated);
1871 }
1872 if (kUseBakerReadBarrier) {
1873 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr());
1874 }
1875 DCHECK(GetFwdPtr(from_ref) == to_ref);
1876 CHECK_NE(to_ref->GetLockWord(false).GetState(), LockWord::kForwardingAddress);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001877 PushOntoMarkStack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001878 return to_ref;
1879 } else {
1880 // The CAS failed. It may have lost the race or may have failed
1881 // due to monitor/hashcode ops. Either way, retry.
1882 }
1883 }
1884}
1885
1886mirror::Object* ConcurrentCopying::IsMarked(mirror::Object* from_ref) {
1887 DCHECK(from_ref != nullptr);
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08001888 space::RegionSpace::RegionType rtype = region_space_->GetRegionType(from_ref);
1889 if (rtype == space::RegionSpace::RegionType::kRegionTypeToSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001890 // It's already marked.
1891 return from_ref;
1892 }
1893 mirror::Object* to_ref;
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08001894 if (rtype == space::RegionSpace::RegionType::kRegionTypeFromSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001895 to_ref = GetFwdPtr(from_ref);
1896 DCHECK(to_ref == nullptr || region_space_->IsInToSpace(to_ref) ||
1897 heap_->non_moving_space_->HasAddress(to_ref))
1898 << "from_ref=" << from_ref << " to_ref=" << to_ref;
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08001899 } else if (rtype == space::RegionSpace::RegionType::kRegionTypeUnevacFromSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001900 if (region_space_bitmap_->Test(from_ref)) {
1901 to_ref = from_ref;
1902 } else {
1903 to_ref = nullptr;
1904 }
1905 } else {
1906 // from_ref is in a non-moving space.
Mathieu Chartier763a31e2015-11-16 16:05:55 -08001907 if (immune_spaces_.ContainsObject(from_ref)) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001908 // An immune object is alive.
1909 to_ref = from_ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001910 } else {
1911 // Non-immune non-moving space. Use the mark bitmap.
1912 accounting::ContinuousSpaceBitmap* mark_bitmap =
1913 heap_mark_bitmap_->GetContinuousSpaceBitmap(from_ref);
1914 accounting::LargeObjectBitmap* los_bitmap =
1915 heap_mark_bitmap_->GetLargeObjectBitmap(from_ref);
1916 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
1917 bool is_los = mark_bitmap == nullptr;
1918 if (!is_los && mark_bitmap->Test(from_ref)) {
1919 // Already marked.
1920 to_ref = from_ref;
1921 } else if (is_los && los_bitmap->Test(from_ref)) {
1922 // Already marked in LOS.
1923 to_ref = from_ref;
1924 } else {
1925 // Not marked.
1926 if (IsOnAllocStack(from_ref)) {
1927 // If on the allocation stack, it's considered marked.
1928 to_ref = from_ref;
1929 } else {
1930 // Not marked.
1931 to_ref = nullptr;
1932 }
1933 }
1934 }
1935 }
1936 return to_ref;
1937}
1938
1939bool ConcurrentCopying::IsOnAllocStack(mirror::Object* ref) {
1940 QuasiAtomic::ThreadFenceAcquire();
1941 accounting::ObjectStack* alloc_stack = GetAllocationStack();
Mathieu Chartiercb535da2015-01-23 13:50:03 -08001942 return alloc_stack->Contains(ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001943}
1944
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001945mirror::Object* ConcurrentCopying::MarkNonMoving(mirror::Object* ref) {
1946 // ref is in a non-moving space (from_ref == to_ref).
1947 DCHECK(!region_space_->HasAddress(ref)) << ref;
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001948 DCHECK(!immune_spaces_.ContainsObject(ref));
1949 // Use the mark bitmap.
1950 accounting::ContinuousSpaceBitmap* mark_bitmap =
1951 heap_mark_bitmap_->GetContinuousSpaceBitmap(ref);
1952 accounting::LargeObjectBitmap* los_bitmap =
1953 heap_mark_bitmap_->GetLargeObjectBitmap(ref);
1954 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
1955 bool is_los = mark_bitmap == nullptr;
1956 if (!is_los && mark_bitmap->Test(ref)) {
1957 // Already marked.
1958 if (kUseBakerReadBarrier) {
1959 DCHECK(ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr() ||
1960 ref->GetReadBarrierPointer() == ReadBarrier::WhitePtr());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001961 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001962 } else if (is_los && los_bitmap->Test(ref)) {
1963 // Already marked in LOS.
1964 if (kUseBakerReadBarrier) {
1965 DCHECK(ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr() ||
1966 ref->GetReadBarrierPointer() == ReadBarrier::WhitePtr());
1967 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001968 } else {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001969 // Not marked.
1970 if (IsOnAllocStack(ref)) {
1971 // If it's on the allocation stack, it's considered marked. Keep it white.
1972 // Objects on the allocation stack need not be marked.
1973 if (!is_los) {
1974 DCHECK(!mark_bitmap->Test(ref));
1975 } else {
1976 DCHECK(!los_bitmap->Test(ref));
Nicolas Geoffrayddeb1722016-06-28 08:25:59 +00001977 }
Nicolas Geoffrayddeb1722016-06-28 08:25:59 +00001978 if (kUseBakerReadBarrier) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001979 DCHECK_EQ(ref->GetReadBarrierPointer(), ReadBarrier::WhitePtr());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001980 }
1981 } else {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001982 // For the baker-style RB, we need to handle 'false-gray' cases. See the
1983 // kRegionTypeUnevacFromSpace-case comment in Mark().
1984 if (kUseBakerReadBarrier) {
1985 // Test the bitmap first to reduce the chance of false gray cases.
1986 if ((!is_los && mark_bitmap->Test(ref)) ||
1987 (is_los && los_bitmap->Test(ref))) {
1988 return ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001989 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001990 }
1991 // Not marked or on the allocation stack. Try to mark it.
1992 // This may or may not succeed, which is ok.
1993 bool cas_success = false;
1994 if (kUseBakerReadBarrier) {
1995 cas_success = ref->AtomicSetReadBarrierPointer(ReadBarrier::WhitePtr(),
1996 ReadBarrier::GrayPtr());
1997 }
1998 if (!is_los && mark_bitmap->AtomicTestAndSet(ref)) {
1999 // Already marked.
2000 if (kUseBakerReadBarrier && cas_success &&
2001 ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr()) {
2002 PushOntoFalseGrayStack(ref);
2003 }
2004 } else if (is_los && los_bitmap->AtomicTestAndSet(ref)) {
2005 // Already marked in LOS.
2006 if (kUseBakerReadBarrier && cas_success &&
2007 ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr()) {
2008 PushOntoFalseGrayStack(ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002009 }
2010 } else {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002011 // Newly marked.
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08002012 if (kUseBakerReadBarrier) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002013 DCHECK_EQ(ref->GetReadBarrierPointer(), ReadBarrier::GrayPtr());
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08002014 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002015 PushOntoMarkStack(ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002016 }
2017 }
2018 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002019 return ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002020}
2021
2022void ConcurrentCopying::FinishPhase() {
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -08002023 Thread* const self = Thread::Current();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002024 {
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -08002025 MutexLock mu(self, mark_stack_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002026 CHECK_EQ(pooled_mark_stacks_.size(), kMarkStackPoolSize);
2027 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002028 region_space_ = nullptr;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002029 {
2030 MutexLock mu(Thread::Current(), skipped_blocks_lock_);
2031 skipped_blocks_map_.clear();
2032 }
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -08002033 ReaderMutexLock mu(self, *Locks::mutator_lock_);
2034 WriterMutexLock mu2(self, *Locks::heap_bitmap_lock_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002035 heap_->ClearMarkedObjects();
2036}
2037
Mathieu Chartier97509952015-07-13 14:35:43 -07002038bool ConcurrentCopying::IsMarkedHeapReference(mirror::HeapReference<mirror::Object>* field) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002039 mirror::Object* from_ref = field->AsMirrorPtr();
Mathieu Chartier97509952015-07-13 14:35:43 -07002040 mirror::Object* to_ref = IsMarked(from_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002041 if (to_ref == nullptr) {
2042 return false;
2043 }
2044 if (from_ref != to_ref) {
2045 QuasiAtomic::ThreadFenceRelease();
2046 field->Assign(to_ref);
2047 QuasiAtomic::ThreadFenceSequentiallyConsistent();
2048 }
2049 return true;
2050}
2051
Mathieu Chartier97509952015-07-13 14:35:43 -07002052mirror::Object* ConcurrentCopying::MarkObject(mirror::Object* from_ref) {
2053 return Mark(from_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002054}
2055
2056void ConcurrentCopying::DelayReferenceReferent(mirror::Class* klass, mirror::Reference* reference) {
Mathieu Chartier97509952015-07-13 14:35:43 -07002057 heap_->GetReferenceProcessor()->DelayReferenceReferent(klass, reference, this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002058}
2059
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002060void ConcurrentCopying::ProcessReferences(Thread* self) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002061 TimingLogger::ScopedTiming split("ProcessReferences", GetTimings());
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002062 // 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 -08002063 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
2064 GetHeap()->GetReferenceProcessor()->ProcessReferences(
Mathieu Chartier97509952015-07-13 14:35:43 -07002065 true /*concurrent*/, GetTimings(), GetCurrentIteration()->GetClearSoftReferences(), this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002066}
2067
2068void ConcurrentCopying::RevokeAllThreadLocalBuffers() {
2069 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
2070 region_space_->RevokeAllThreadLocalBuffers();
2071}
2072
Hiroshi Yamauchid5307ec2014-03-27 21:07:51 -07002073} // namespace collector
2074} // namespace gc
2075} // namespace art