blob: 3f8f6284c05b6226af30e5bd9bcda4e45ed9f660 [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 Yamauchi0b713572015-06-16 18:29:23 -070053 heap_mark_bitmap_(nullptr), live_stack_freeze_size_(0), mark_stack_mode_(kMarkStackModeOff),
54 weak_ref_access_enabled_(true),
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080055 skipped_blocks_lock_("concurrent copying bytes blocks lock", kMarkSweepMarkStackLock),
56 rb_table_(heap_->GetReadBarrierTable()),
57 force_evacuate_all_(false) {
58 static_assert(space::RegionSpace::kRegionSize == accounting::ReadBarrierTable::kRegionSize,
59 "The region space size and the read barrier table region size must match");
60 cc_heap_bitmap_.reset(new accounting::HeapBitmap(heap));
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070061 Thread* self = Thread::Current();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080062 {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080063 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
64 // Cache this so that we won't have to lock heap_bitmap_lock_ in
65 // Mark() which could cause a nested lock on heap_bitmap_lock_
66 // when GC causes a RB while doing GC or a lock order violation
67 // (class_linker_lock_ and heap_bitmap_lock_).
68 heap_mark_bitmap_ = heap->GetMarkBitmap();
69 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070070 {
71 MutexLock mu(self, mark_stack_lock_);
72 for (size_t i = 0; i < kMarkStackPoolSize; ++i) {
73 accounting::AtomicStack<mirror::Object>* mark_stack =
74 accounting::AtomicStack<mirror::Object>::Create(
75 "thread local mark stack", kMarkStackSize, kMarkStackSize);
76 pooled_mark_stacks_.push_back(mark_stack);
77 }
78 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080079}
80
Mathieu Chartierb19ccb12015-07-15 10:24:16 -070081void ConcurrentCopying::MarkHeapReference(mirror::HeapReference<mirror::Object>* from_ref) {
82 // Used for preserving soft references, should be OK to not have a CAS here since there should be
83 // no other threads which can trigger read barriers on the same referent during reference
84 // processing.
85 from_ref->Assign(Mark(from_ref->AsMirrorPtr()));
Mathieu Chartier81187812015-07-15 14:24:07 -070086 DCHECK(!from_ref->IsNull());
Mathieu Chartier97509952015-07-13 14:35:43 -070087}
88
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080089ConcurrentCopying::~ConcurrentCopying() {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070090 STLDeleteElements(&pooled_mark_stacks_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080091}
92
93void ConcurrentCopying::RunPhases() {
94 CHECK(kUseBakerReadBarrier || kUseTableLookupReadBarrier);
95 CHECK(!is_active_);
96 is_active_ = true;
97 Thread* self = Thread::Current();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070098 thread_running_gc_ = self;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080099 Locks::mutator_lock_->AssertNotHeld(self);
100 {
101 ReaderMutexLock mu(self, *Locks::mutator_lock_);
102 InitializePhase();
103 }
104 FlipThreadRoots();
105 {
106 ReaderMutexLock mu(self, *Locks::mutator_lock_);
107 MarkingPhase();
108 }
109 // Verify no from space refs. This causes a pause.
110 if (kEnableNoFromSpaceRefsVerification || kIsDebugBuild) {
111 TimingLogger::ScopedTiming split("(Paused)VerifyNoFromSpaceReferences", GetTimings());
112 ScopedPause pause(this);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700113 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800114 if (kVerboseMode) {
115 LOG(INFO) << "Verifying no from-space refs";
116 }
117 VerifyNoFromSpaceReferences();
Mathieu Chartier720e71a2015-04-06 17:10:58 -0700118 if (kVerboseMode) {
119 LOG(INFO) << "Done verifying no from-space refs";
120 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700121 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800122 }
123 {
124 ReaderMutexLock mu(self, *Locks::mutator_lock_);
125 ReclaimPhase();
126 }
127 FinishPhase();
128 CHECK(is_active_);
129 is_active_ = false;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700130 thread_running_gc_ = nullptr;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800131}
132
133void ConcurrentCopying::BindBitmaps() {
134 Thread* self = Thread::Current();
135 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
136 // Mark all of the spaces we never collect as immune.
137 for (const auto& space : heap_->GetContinuousSpaces()) {
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800138 if (space->GetGcRetentionPolicy() == space::kGcRetentionPolicyNeverCollect ||
139 space->GetGcRetentionPolicy() == space::kGcRetentionPolicyFullCollect) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800140 CHECK(space->IsZygoteSpace() || space->IsImageSpace());
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800141 immune_spaces_.AddSpace(space);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800142 const char* bitmap_name = space->IsImageSpace() ? "cc image space bitmap" :
143 "cc zygote space bitmap";
144 // TODO: try avoiding using bitmaps for image/zygote to save space.
145 accounting::ContinuousSpaceBitmap* bitmap =
146 accounting::ContinuousSpaceBitmap::Create(bitmap_name, space->Begin(), space->Capacity());
147 cc_heap_bitmap_->AddContinuousSpaceBitmap(bitmap);
148 cc_bitmaps_.push_back(bitmap);
149 } else if (space == region_space_) {
150 accounting::ContinuousSpaceBitmap* bitmap =
151 accounting::ContinuousSpaceBitmap::Create("cc region space bitmap",
152 space->Begin(), space->Capacity());
153 cc_heap_bitmap_->AddContinuousSpaceBitmap(bitmap);
154 cc_bitmaps_.push_back(bitmap);
155 region_space_bitmap_ = bitmap;
156 }
157 }
158}
159
160void ConcurrentCopying::InitializePhase() {
161 TimingLogger::ScopedTiming split("InitializePhase", GetTimings());
162 if (kVerboseMode) {
163 LOG(INFO) << "GC InitializePhase";
164 LOG(INFO) << "Region-space : " << reinterpret_cast<void*>(region_space_->Begin()) << "-"
165 << reinterpret_cast<void*>(region_space_->Limit());
166 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700167 CheckEmptyMarkStack();
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800168 if (kIsDebugBuild) {
169 MutexLock mu(Thread::Current(), mark_stack_lock_);
170 CHECK(false_gray_stack_.empty());
171 }
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800172 immune_spaces_.Reset();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800173 bytes_moved_.StoreRelaxed(0);
174 objects_moved_.StoreRelaxed(0);
175 if (GetCurrentIteration()->GetGcCause() == kGcCauseExplicit ||
176 GetCurrentIteration()->GetGcCause() == kGcCauseForNativeAlloc ||
177 GetCurrentIteration()->GetClearSoftReferences()) {
178 force_evacuate_all_ = true;
179 } else {
180 force_evacuate_all_ = false;
181 }
182 BindBitmaps();
183 if (kVerboseMode) {
184 LOG(INFO) << "force_evacuate_all=" << force_evacuate_all_;
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800185 LOG(INFO) << "Largest immune region: " << immune_spaces_.GetLargestImmuneRegion().Begin()
186 << "-" << immune_spaces_.GetLargestImmuneRegion().End();
187 for (space::ContinuousSpace* space : immune_spaces_.GetSpaces()) {
188 LOG(INFO) << "Immune space: " << *space;
189 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800190 LOG(INFO) << "GC end of InitializePhase";
191 }
192}
193
194// Used to switch the thread roots of a thread from from-space refs to to-space refs.
195class ThreadFlipVisitor : public Closure {
196 public:
Roland Levillain3887c462015-08-12 18:15:42 +0100197 ThreadFlipVisitor(ConcurrentCopying* concurrent_copying, bool use_tlab)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800198 : concurrent_copying_(concurrent_copying), use_tlab_(use_tlab) {
199 }
200
Mathieu Chartier90443472015-07-16 20:32:27 -0700201 virtual void Run(Thread* thread) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800202 // Note: self is not necessarily equal to thread since thread may be suspended.
203 Thread* self = Thread::Current();
204 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
205 << thread->GetState() << " thread " << thread << " self " << self;
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700206 thread->SetIsGcMarking(true);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800207 if (use_tlab_ && thread->HasTlab()) {
208 if (ConcurrentCopying::kEnableFromSpaceAccountingCheck) {
209 // This must come before the revoke.
210 size_t thread_local_objects = thread->GetThreadLocalObjectsAllocated();
211 concurrent_copying_->region_space_->RevokeThreadLocalBuffers(thread);
212 reinterpret_cast<Atomic<size_t>*>(&concurrent_copying_->from_space_num_objects_at_first_pause_)->
213 FetchAndAddSequentiallyConsistent(thread_local_objects);
214 } else {
215 concurrent_copying_->region_space_->RevokeThreadLocalBuffers(thread);
216 }
217 }
218 if (kUseThreadLocalAllocationStack) {
219 thread->RevokeThreadLocalAllocationStack();
220 }
221 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700222 thread->VisitRoots(concurrent_copying_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800223 concurrent_copying_->GetBarrier().Pass(self);
224 }
225
226 private:
227 ConcurrentCopying* const concurrent_copying_;
228 const bool use_tlab_;
229};
230
231// Called back from Runtime::FlipThreadRoots() during a pause.
232class FlipCallback : public Closure {
233 public:
234 explicit FlipCallback(ConcurrentCopying* concurrent_copying)
235 : concurrent_copying_(concurrent_copying) {
236 }
237
Mathieu Chartier90443472015-07-16 20:32:27 -0700238 virtual void Run(Thread* thread) OVERRIDE REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800239 ConcurrentCopying* cc = concurrent_copying_;
240 TimingLogger::ScopedTiming split("(Paused)FlipCallback", cc->GetTimings());
241 // Note: self is not necessarily equal to thread since thread may be suspended.
242 Thread* self = Thread::Current();
243 CHECK(thread == self);
244 Locks::mutator_lock_->AssertExclusiveHeld(self);
245 cc->region_space_->SetFromSpace(cc->rb_table_, cc->force_evacuate_all_);
Mathieu Chartiera4f6af92015-08-11 17:35:25 -0700246 cc->SwapStacks();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800247 if (ConcurrentCopying::kEnableFromSpaceAccountingCheck) {
248 cc->RecordLiveStackFreezeSize(self);
249 cc->from_space_num_objects_at_first_pause_ = cc->region_space_->GetObjectsAllocated();
250 cc->from_space_num_bytes_at_first_pause_ = cc->region_space_->GetBytesAllocated();
251 }
252 cc->is_marking_ = true;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700253 cc->mark_stack_mode_.StoreRelaxed(ConcurrentCopying::kMarkStackModeThreadLocal);
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800254 if (kIsDebugBuild) {
255 cc->region_space_->AssertAllRegionLiveBytesZeroOrCleared();
256 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800257 if (UNLIKELY(Runtime::Current()->IsActiveTransaction())) {
Mathieu Chartier184c9dc2015-03-05 13:20:54 -0800258 CHECK(Runtime::Current()->IsAotCompiler());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800259 TimingLogger::ScopedTiming split2("(Paused)VisitTransactionRoots", cc->GetTimings());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700260 Runtime::Current()->VisitTransactionRoots(cc);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800261 }
262 }
263
264 private:
265 ConcurrentCopying* const concurrent_copying_;
266};
267
268// Switch threads that from from-space to to-space refs. Forward/mark the thread roots.
269void ConcurrentCopying::FlipThreadRoots() {
270 TimingLogger::ScopedTiming split("FlipThreadRoots", GetTimings());
271 if (kVerboseMode) {
272 LOG(INFO) << "time=" << region_space_->Time();
273 region_space_->DumpNonFreeRegions(LOG(INFO));
274 }
275 Thread* self = Thread::Current();
276 Locks::mutator_lock_->AssertNotHeld(self);
277 gc_barrier_->Init(self, 0);
278 ThreadFlipVisitor thread_flip_visitor(this, heap_->use_tlab_);
279 FlipCallback flip_callback(this);
Hiroshi Yamauchi76f55b02015-08-21 16:10:39 -0700280 heap_->ThreadFlipBegin(self); // Sync with JNI critical calls.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800281 size_t barrier_count = Runtime::Current()->FlipThreadRoots(
282 &thread_flip_visitor, &flip_callback, this);
Hiroshi Yamauchi76f55b02015-08-21 16:10:39 -0700283 heap_->ThreadFlipEnd(self);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800284 {
285 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
286 gc_barrier_->Increment(self, barrier_count);
287 }
288 is_asserting_to_space_invariant_ = true;
289 QuasiAtomic::ThreadFenceForConstructor();
290 if (kVerboseMode) {
291 LOG(INFO) << "time=" << region_space_->Time();
292 region_space_->DumpNonFreeRegions(LOG(INFO));
293 LOG(INFO) << "GC end of FlipThreadRoots";
294 }
295}
296
Mathieu Chartiera4f6af92015-08-11 17:35:25 -0700297void ConcurrentCopying::SwapStacks() {
298 heap_->SwapStacks();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800299}
300
301void ConcurrentCopying::RecordLiveStackFreezeSize(Thread* self) {
302 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
303 live_stack_freeze_size_ = heap_->GetLiveStack()->Size();
304}
305
306// Used to visit objects in the immune spaces.
307class ConcurrentCopyingImmuneSpaceObjVisitor {
308 public:
309 explicit ConcurrentCopyingImmuneSpaceObjVisitor(ConcurrentCopying* cc)
310 : collector_(cc) {}
311
Mathieu Chartier90443472015-07-16 20:32:27 -0700312 void operator()(mirror::Object* obj) const SHARED_REQUIRES(Locks::mutator_lock_)
313 SHARED_REQUIRES(Locks::heap_bitmap_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800314 DCHECK(obj != nullptr);
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800315 DCHECK(collector_->immune_spaces_.ContainsObject(obj));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800316 accounting::ContinuousSpaceBitmap* cc_bitmap =
317 collector_->cc_heap_bitmap_->GetContinuousSpaceBitmap(obj);
318 DCHECK(cc_bitmap != nullptr)
319 << "An immune space object must have a bitmap";
320 if (kIsDebugBuild) {
321 DCHECK(collector_->heap_->GetMarkBitmap()->Test(obj))
322 << "Immune space object must be already marked";
323 }
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800324 collector_->MarkUnevacFromSpaceRegionOrImmuneSpace(obj, cc_bitmap);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800325 }
326
327 private:
Mathieu Chartier97509952015-07-13 14:35:43 -0700328 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800329};
330
331class EmptyCheckpoint : public Closure {
332 public:
333 explicit EmptyCheckpoint(ConcurrentCopying* concurrent_copying)
334 : concurrent_copying_(concurrent_copying) {
335 }
336
337 virtual void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
338 // Note: self is not necessarily equal to thread since thread may be suspended.
339 Thread* self = Thread::Current();
340 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
341 << thread->GetState() << " thread " << thread << " self " << self;
Lei Lidd9943d2015-02-02 14:24:44 +0800342 // If thread is a running mutator, then act on behalf of the garbage collector.
343 // See the code in ThreadList::RunCheckpoint.
Mathieu Chartier10d25082015-10-28 18:36:09 -0700344 concurrent_copying_->GetBarrier().Pass(self);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800345 }
346
347 private:
348 ConcurrentCopying* const concurrent_copying_;
349};
350
351// Concurrently mark roots that are guarded by read barriers and process the mark stack.
352void ConcurrentCopying::MarkingPhase() {
353 TimingLogger::ScopedTiming split("MarkingPhase", GetTimings());
354 if (kVerboseMode) {
355 LOG(INFO) << "GC MarkingPhase";
356 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700357 CHECK(weak_ref_access_enabled_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800358 {
359 // Mark the image root. The WB-based collectors do not need to
360 // scan the image objects from roots by relying on the card table,
361 // but it's necessary for the RB to-space invariant to hold.
362 TimingLogger::ScopedTiming split1("VisitImageRoots", GetTimings());
Mathieu Chartier073b16c2015-11-10 14:13:23 -0800363 for (space::ContinuousSpace* space : heap_->GetContinuousSpaces()) {
364 if (space->IsImageSpace()) {
365 gc::space::ImageSpace* image = space->AsImageSpace();
366 if (image != nullptr) {
367 mirror::ObjectArray<mirror::Object>* image_root = image->GetImageHeader().GetImageRoots();
368 mirror::Object* marked_image_root = Mark(image_root);
369 CHECK_EQ(image_root, marked_image_root) << "An image object does not move";
370 if (ReadBarrier::kEnableToSpaceInvariantChecks) {
371 AssertToSpaceInvariant(nullptr, MemberOffset(0), marked_image_root);
372 }
373 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800374 }
375 }
376 }
377 {
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -0700378 TimingLogger::ScopedTiming split2("VisitConcurrentRoots", GetTimings());
379 Runtime::Current()->VisitConcurrentRoots(this, kVisitRootFlagAllRoots);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800380 }
381 {
382 // TODO: don't visit the transaction roots if it's not active.
383 TimingLogger::ScopedTiming split5("VisitNonThreadRoots", GetTimings());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700384 Runtime::Current()->VisitNonThreadRoots(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800385 }
386
387 // Immune spaces.
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800388 for (auto& space : immune_spaces_.GetSpaces()) {
389 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
390 accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
391 ConcurrentCopyingImmuneSpaceObjVisitor visitor(this);
392 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()),
393 reinterpret_cast<uintptr_t>(space->Limit()),
394 visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800395 }
396
397 Thread* self = Thread::Current();
398 {
Mathieu Chartiera6b1ead2015-10-06 10:32:38 -0700399 TimingLogger::ScopedTiming split7("ProcessMarkStack", GetTimings());
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700400 // We transition through three mark stack modes (thread-local, shared, GC-exclusive). The
401 // primary reasons are the fact that we need to use a checkpoint to process thread-local mark
402 // stacks, but after we disable weak refs accesses, we can't use a checkpoint due to a deadlock
403 // issue because running threads potentially blocking at WaitHoldingLocks, and that once we
404 // reach the point where we process weak references, we can avoid using a lock when accessing
405 // the GC mark stack, which makes mark stack processing more efficient.
406
407 // Process the mark stack once in the thread local stack mode. This marks most of the live
408 // objects, aside from weak ref accesses with read barriers (Reference::GetReferent() and system
409 // weaks) that may happen concurrently while we processing the mark stack and newly mark/gray
410 // objects and push refs on the mark stack.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800411 ProcessMarkStack();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700412 // Switch to the shared mark stack mode. That is, revoke and process thread-local mark stacks
413 // for the last time before transitioning to the shared mark stack mode, which would process new
414 // refs that may have been concurrently pushed onto the mark stack during the ProcessMarkStack()
415 // call above. At the same time, disable weak ref accesses using a per-thread flag. It's
416 // important to do these together in a single checkpoint so that we can ensure that mutators
417 // won't newly gray objects and push new refs onto the mark stack due to weak ref accesses and
418 // mutators safely transition to the shared mark stack mode (without leaving unprocessed refs on
419 // the thread-local mark stacks), without a race. This is why we use a thread-local weak ref
420 // access flag Thread::tls32_.weak_ref_access_enabled_ instead of the global ones.
421 SwitchToSharedMarkStackMode();
422 CHECK(!self->GetWeakRefAccessEnabled());
423 // Now that weak refs accesses are disabled, once we exhaust the shared mark stack again here
424 // (which may be non-empty if there were refs found on thread-local mark stacks during the above
425 // SwitchToSharedMarkStackMode() call), we won't have new refs to process, that is, mutators
426 // (via read barriers) have no way to produce any more refs to process. Marking converges once
427 // before we process weak refs below.
428 ProcessMarkStack();
429 CheckEmptyMarkStack();
430 // Switch to the GC exclusive mark stack mode so that we can process the mark stack without a
431 // lock from this point on.
432 SwitchToGcExclusiveMarkStackMode();
433 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800434 if (kVerboseMode) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800435 LOG(INFO) << "ProcessReferences";
436 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700437 // Process weak references. This may produce new refs to process and have them processed via
Mathieu Chartier97509952015-07-13 14:35:43 -0700438 // ProcessMarkStack (in the GC exclusive mark stack mode).
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700439 ProcessReferences(self);
440 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800441 if (kVerboseMode) {
442 LOG(INFO) << "SweepSystemWeaks";
443 }
444 SweepSystemWeaks(self);
445 if (kVerboseMode) {
446 LOG(INFO) << "SweepSystemWeaks done";
447 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700448 // Process the mark stack here one last time because the above SweepSystemWeaks() call may have
449 // marked some objects (strings alive) as hash_set::Erase() can call the hash function for
450 // arbitrary elements in the weak intern table in InternTable::Table::SweepWeaks().
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800451 ProcessMarkStack();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700452 CheckEmptyMarkStack();
453 // Re-enable weak ref accesses.
454 ReenableWeakRefAccess(self);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -0700455 // Free data for class loaders that we unloaded.
456 Runtime::Current()->GetClassLinker()->CleanupClassLoaders();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700457 // Marking is done. Disable marking.
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700458 DisableMarking();
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800459 if (kUseBakerReadBarrier) {
460 ProcessFalseGrayStack();
461 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700462 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800463 }
464
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700465 CHECK(weak_ref_access_enabled_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800466 if (kVerboseMode) {
467 LOG(INFO) << "GC end of MarkingPhase";
468 }
469}
470
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700471void ConcurrentCopying::ReenableWeakRefAccess(Thread* self) {
472 if (kVerboseMode) {
473 LOG(INFO) << "ReenableWeakRefAccess";
474 }
475 weak_ref_access_enabled_.StoreRelaxed(true); // This is for new threads.
476 QuasiAtomic::ThreadFenceForConstructor();
477 // Iterate all threads (don't need to or can't use a checkpoint) and re-enable weak ref access.
478 {
479 MutexLock mu(self, *Locks::thread_list_lock_);
480 std::list<Thread*> thread_list = Runtime::Current()->GetThreadList()->GetList();
481 for (Thread* thread : thread_list) {
482 thread->SetWeakRefAccessEnabled(true);
483 }
484 }
485 // Unblock blocking threads.
486 GetHeap()->GetReferenceProcessor()->BroadcastForSlowPath(self);
487 Runtime::Current()->BroadcastForNewSystemWeaks();
488}
489
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700490class DisableMarkingCheckpoint : public Closure {
491 public:
492 explicit DisableMarkingCheckpoint(ConcurrentCopying* concurrent_copying)
493 : concurrent_copying_(concurrent_copying) {
494 }
495
496 void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
497 // Note: self is not necessarily equal to thread since thread may be suspended.
498 Thread* self = Thread::Current();
499 DCHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
500 << thread->GetState() << " thread " << thread << " self " << self;
501 // Disable the thread-local is_gc_marking flag.
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -0700502 // Note a thread that has just started right before this checkpoint may have already this flag
503 // set to false, which is ok.
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700504 thread->SetIsGcMarking(false);
505 // If thread is a running mutator, then act on behalf of the garbage collector.
506 // See the code in ThreadList::RunCheckpoint.
Mathieu Chartier10d25082015-10-28 18:36:09 -0700507 concurrent_copying_->GetBarrier().Pass(self);
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700508 }
509
510 private:
511 ConcurrentCopying* const concurrent_copying_;
512};
513
514void ConcurrentCopying::IssueDisableMarkingCheckpoint() {
515 Thread* self = Thread::Current();
516 DisableMarkingCheckpoint check_point(this);
517 ThreadList* thread_list = Runtime::Current()->GetThreadList();
518 gc_barrier_->Init(self, 0);
519 size_t barrier_count = thread_list->RunCheckpoint(&check_point);
520 // If there are no threads to wait which implies that all the checkpoint functions are finished,
521 // then no need to release the mutator lock.
522 if (barrier_count == 0) {
523 return;
524 }
525 // Release locks then wait for all mutator threads to pass the barrier.
526 Locks::mutator_lock_->SharedUnlock(self);
527 {
528 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
529 gc_barrier_->Increment(self, barrier_count);
530 }
531 Locks::mutator_lock_->SharedLock(self);
532}
533
534void ConcurrentCopying::DisableMarking() {
535 // Change the global is_marking flag to false. Do a fence before doing a checkpoint to update the
536 // thread-local flags so that a new thread starting up will get the correct is_marking flag.
537 is_marking_ = false;
538 QuasiAtomic::ThreadFenceForConstructor();
539 // Use a checkpoint to turn off the thread-local is_gc_marking flags and to ensure no threads are
540 // still in the middle of a read barrier which may have a from-space ref cached in a local
541 // variable.
542 IssueDisableMarkingCheckpoint();
543 if (kUseTableLookupReadBarrier) {
544 heap_->rb_table_->ClearAll();
545 DCHECK(heap_->rb_table_->IsAllCleared());
546 }
547 is_mark_stack_push_disallowed_.StoreSequentiallyConsistent(1);
548 mark_stack_mode_.StoreSequentiallyConsistent(kMarkStackModeOff);
549}
550
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800551void ConcurrentCopying::PushOntoFalseGrayStack(mirror::Object* ref) {
552 CHECK(kUseBakerReadBarrier);
553 DCHECK(ref != nullptr);
554 MutexLock mu(Thread::Current(), mark_stack_lock_);
555 false_gray_stack_.push_back(ref);
556}
557
558void ConcurrentCopying::ProcessFalseGrayStack() {
559 CHECK(kUseBakerReadBarrier);
560 // Change the objects on the false gray stack from gray to white.
561 MutexLock mu(Thread::Current(), mark_stack_lock_);
562 for (mirror::Object* obj : false_gray_stack_) {
563 DCHECK(IsMarked(obj));
564 // The object could be white here if a thread got preempted after a success at the
565 // AtomicSetReadBarrierPointer in Mark(), GC started marking through it (but not finished so
566 // still gray), and the thread ran to register it onto the false gray stack.
567 if (obj->GetReadBarrierPointer() == ReadBarrier::GrayPtr()) {
568 bool success = obj->AtomicSetReadBarrierPointer(ReadBarrier::GrayPtr(),
569 ReadBarrier::WhitePtr());
570 DCHECK(success);
571 }
572 }
573 false_gray_stack_.clear();
574}
575
576
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800577void ConcurrentCopying::IssueEmptyCheckpoint() {
578 Thread* self = Thread::Current();
579 EmptyCheckpoint check_point(this);
580 ThreadList* thread_list = Runtime::Current()->GetThreadList();
581 gc_barrier_->Init(self, 0);
582 size_t barrier_count = thread_list->RunCheckpoint(&check_point);
Lei Lidd9943d2015-02-02 14:24:44 +0800583 // If there are no threads to wait which implys that all the checkpoint functions are finished,
584 // then no need to release the mutator lock.
585 if (barrier_count == 0) {
586 return;
587 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800588 // Release locks then wait for all mutator threads to pass the barrier.
589 Locks::mutator_lock_->SharedUnlock(self);
590 {
591 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
592 gc_barrier_->Increment(self, barrier_count);
593 }
594 Locks::mutator_lock_->SharedLock(self);
595}
596
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -0700597void ConcurrentCopying::ExpandGcMarkStack() {
598 DCHECK(gc_mark_stack_->IsFull());
599 const size_t new_size = gc_mark_stack_->Capacity() * 2;
600 std::vector<StackReference<mirror::Object>> temp(gc_mark_stack_->Begin(),
601 gc_mark_stack_->End());
602 gc_mark_stack_->Resize(new_size);
603 for (auto& ref : temp) {
604 gc_mark_stack_->PushBack(ref.AsMirrorPtr());
605 }
606 DCHECK(!gc_mark_stack_->IsFull());
607}
608
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800609void ConcurrentCopying::PushOntoMarkStack(mirror::Object* to_ref) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700610 CHECK_EQ(is_mark_stack_push_disallowed_.LoadRelaxed(), 0)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800611 << " " << to_ref << " " << PrettyTypeOf(to_ref);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700612 Thread* self = Thread::Current(); // TODO: pass self as an argument from call sites?
613 CHECK(thread_running_gc_ != nullptr);
614 MarkStackMode mark_stack_mode = mark_stack_mode_.LoadRelaxed();
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -0700615 if (LIKELY(mark_stack_mode == kMarkStackModeThreadLocal)) {
616 if (LIKELY(self == thread_running_gc_)) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700617 // If GC-running thread, use the GC mark stack instead of a thread-local mark stack.
618 CHECK(self->GetThreadLocalMarkStack() == nullptr);
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -0700619 if (UNLIKELY(gc_mark_stack_->IsFull())) {
620 ExpandGcMarkStack();
621 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700622 gc_mark_stack_->PushBack(to_ref);
623 } else {
624 // Otherwise, use a thread-local mark stack.
625 accounting::AtomicStack<mirror::Object>* tl_mark_stack = self->GetThreadLocalMarkStack();
626 if (UNLIKELY(tl_mark_stack == nullptr || tl_mark_stack->IsFull())) {
627 MutexLock mu(self, mark_stack_lock_);
628 // Get a new thread local mark stack.
629 accounting::AtomicStack<mirror::Object>* new_tl_mark_stack;
630 if (!pooled_mark_stacks_.empty()) {
631 // Use a pooled mark stack.
632 new_tl_mark_stack = pooled_mark_stacks_.back();
633 pooled_mark_stacks_.pop_back();
634 } else {
635 // None pooled. Create a new one.
636 new_tl_mark_stack =
637 accounting::AtomicStack<mirror::Object>::Create(
638 "thread local mark stack", 4 * KB, 4 * KB);
639 }
640 DCHECK(new_tl_mark_stack != nullptr);
641 DCHECK(new_tl_mark_stack->IsEmpty());
642 new_tl_mark_stack->PushBack(to_ref);
643 self->SetThreadLocalMarkStack(new_tl_mark_stack);
644 if (tl_mark_stack != nullptr) {
645 // Store the old full stack into a vector.
646 revoked_mark_stacks_.push_back(tl_mark_stack);
647 }
648 } else {
649 tl_mark_stack->PushBack(to_ref);
650 }
651 }
652 } else if (mark_stack_mode == kMarkStackModeShared) {
653 // Access the shared GC mark stack with a lock.
654 MutexLock mu(self, mark_stack_lock_);
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -0700655 if (UNLIKELY(gc_mark_stack_->IsFull())) {
656 ExpandGcMarkStack();
657 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700658 gc_mark_stack_->PushBack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800659 } else {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700660 CHECK_EQ(static_cast<uint32_t>(mark_stack_mode),
Hiroshi Yamauchifa755182015-09-30 20:12:11 -0700661 static_cast<uint32_t>(kMarkStackModeGcExclusive))
662 << "ref=" << to_ref
663 << " self->gc_marking=" << self->GetIsGcMarking()
664 << " cc->is_marking=" << is_marking_;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700665 CHECK(self == thread_running_gc_)
666 << "Only GC-running thread should access the mark stack "
667 << "in the GC exclusive mark stack mode";
668 // Access the GC mark stack without a lock.
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -0700669 if (UNLIKELY(gc_mark_stack_->IsFull())) {
670 ExpandGcMarkStack();
671 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700672 gc_mark_stack_->PushBack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800673 }
674}
675
676accounting::ObjectStack* ConcurrentCopying::GetAllocationStack() {
677 return heap_->allocation_stack_.get();
678}
679
680accounting::ObjectStack* ConcurrentCopying::GetLiveStack() {
681 return heap_->live_stack_.get();
682}
683
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800684// The following visitors are used to verify that there's no references to the from-space left after
685// marking.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700686class ConcurrentCopyingVerifyNoFromSpaceRefsVisitor : public SingleRootVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800687 public:
688 explicit ConcurrentCopyingVerifyNoFromSpaceRefsVisitor(ConcurrentCopying* collector)
689 : collector_(collector) {}
690
691 void operator()(mirror::Object* ref) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700692 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800693 if (ref == nullptr) {
694 // OK.
695 return;
696 }
697 collector_->AssertToSpaceInvariant(nullptr, MemberOffset(0), ref);
698 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800699 CHECK(ref->GetReadBarrierPointer() == ReadBarrier::WhitePtr())
700 << "Ref " << ref << " " << PrettyTypeOf(ref)
701 << " has non-white rb_ptr " << ref->GetReadBarrierPointer();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800702 }
703 }
704
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700705 void VisitRoot(mirror::Object* root, const RootInfo& info ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -0700706 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800707 DCHECK(root != nullptr);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700708 operator()(root);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800709 }
710
711 private:
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700712 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800713};
714
715class ConcurrentCopyingVerifyNoFromSpaceRefsFieldVisitor {
716 public:
717 explicit ConcurrentCopyingVerifyNoFromSpaceRefsFieldVisitor(ConcurrentCopying* collector)
718 : collector_(collector) {}
719
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700720 void operator()(mirror::Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700721 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800722 mirror::Object* ref =
723 obj->GetFieldObject<mirror::Object, kDefaultVerifyFlags, kWithoutReadBarrier>(offset);
724 ConcurrentCopyingVerifyNoFromSpaceRefsVisitor visitor(collector_);
725 visitor(ref);
726 }
727 void operator()(mirror::Class* klass, mirror::Reference* ref) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700728 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800729 CHECK(klass->IsTypeOfReferenceClass());
730 this->operator()(ref, mirror::Reference::ReferentOffset(), false);
731 }
732
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700733 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
734 SHARED_REQUIRES(Locks::mutator_lock_) {
735 if (!root->IsNull()) {
736 VisitRoot(root);
737 }
738 }
739
740 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
741 SHARED_REQUIRES(Locks::mutator_lock_) {
742 ConcurrentCopyingVerifyNoFromSpaceRefsVisitor visitor(collector_);
743 visitor(root->AsMirrorPtr());
744 }
745
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800746 private:
Mathieu Chartier97509952015-07-13 14:35:43 -0700747 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800748};
749
750class ConcurrentCopyingVerifyNoFromSpaceRefsObjectVisitor {
751 public:
752 explicit ConcurrentCopyingVerifyNoFromSpaceRefsObjectVisitor(ConcurrentCopying* collector)
753 : collector_(collector) {}
754 void operator()(mirror::Object* obj) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700755 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800756 ObjectCallback(obj, collector_);
757 }
758 static void ObjectCallback(mirror::Object* obj, void *arg)
Mathieu Chartier90443472015-07-16 20:32:27 -0700759 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800760 CHECK(obj != nullptr);
761 ConcurrentCopying* collector = reinterpret_cast<ConcurrentCopying*>(arg);
762 space::RegionSpace* region_space = collector->RegionSpace();
763 CHECK(!region_space->IsInFromSpace(obj)) << "Scanning object " << obj << " in from space";
764 ConcurrentCopyingVerifyNoFromSpaceRefsFieldVisitor visitor(collector);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -0700765 obj->VisitReferences(visitor, visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800766 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800767 CHECK(obj->GetReadBarrierPointer() == ReadBarrier::WhitePtr())
768 << "obj=" << obj << " non-white rb_ptr " << obj->GetReadBarrierPointer();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800769 }
770 }
771
772 private:
773 ConcurrentCopying* const collector_;
774};
775
776// Verify there's no from-space references left after the marking phase.
777void ConcurrentCopying::VerifyNoFromSpaceReferences() {
778 Thread* self = Thread::Current();
779 DCHECK(Locks::mutator_lock_->IsExclusiveHeld(self));
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700780 // Verify all threads have is_gc_marking to be false
781 {
782 MutexLock mu(self, *Locks::thread_list_lock_);
783 std::list<Thread*> thread_list = Runtime::Current()->GetThreadList()->GetList();
784 for (Thread* thread : thread_list) {
785 CHECK(!thread->GetIsGcMarking());
786 }
787 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800788 ConcurrentCopyingVerifyNoFromSpaceRefsObjectVisitor visitor(this);
789 // Roots.
790 {
791 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700792 ConcurrentCopyingVerifyNoFromSpaceRefsVisitor ref_visitor(this);
793 Runtime::Current()->VisitRoots(&ref_visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800794 }
795 // The to-space.
796 region_space_->WalkToSpace(ConcurrentCopyingVerifyNoFromSpaceRefsObjectVisitor::ObjectCallback,
797 this);
798 // Non-moving spaces.
799 {
800 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
801 heap_->GetMarkBitmap()->Visit(visitor);
802 }
803 // The alloc stack.
804 {
805 ConcurrentCopyingVerifyNoFromSpaceRefsVisitor ref_visitor(this);
Mathieu Chartiercb535da2015-01-23 13:50:03 -0800806 for (auto* it = heap_->allocation_stack_->Begin(), *end = heap_->allocation_stack_->End();
807 it < end; ++it) {
808 mirror::Object* const obj = it->AsMirrorPtr();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800809 if (obj != nullptr && obj->GetClass() != nullptr) {
810 // TODO: need to call this only if obj is alive?
811 ref_visitor(obj);
812 visitor(obj);
813 }
814 }
815 }
816 // TODO: LOS. But only refs in LOS are classes.
817}
818
819// The following visitors are used to assert the to-space invariant.
820class ConcurrentCopyingAssertToSpaceInvariantRefsVisitor {
821 public:
822 explicit ConcurrentCopyingAssertToSpaceInvariantRefsVisitor(ConcurrentCopying* collector)
823 : collector_(collector) {}
824
825 void operator()(mirror::Object* ref) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700826 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800827 if (ref == nullptr) {
828 // OK.
829 return;
830 }
831 collector_->AssertToSpaceInvariant(nullptr, MemberOffset(0), ref);
832 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800833
834 private:
Mathieu Chartier97509952015-07-13 14:35:43 -0700835 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800836};
837
838class ConcurrentCopyingAssertToSpaceInvariantFieldVisitor {
839 public:
840 explicit ConcurrentCopyingAssertToSpaceInvariantFieldVisitor(ConcurrentCopying* collector)
841 : collector_(collector) {}
842
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700843 void operator()(mirror::Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700844 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800845 mirror::Object* ref =
846 obj->GetFieldObject<mirror::Object, kDefaultVerifyFlags, kWithoutReadBarrier>(offset);
847 ConcurrentCopyingAssertToSpaceInvariantRefsVisitor visitor(collector_);
848 visitor(ref);
849 }
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700850 void operator()(mirror::Class* klass, mirror::Reference* ref ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700851 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800852 CHECK(klass->IsTypeOfReferenceClass());
853 }
854
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700855 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
856 SHARED_REQUIRES(Locks::mutator_lock_) {
857 if (!root->IsNull()) {
858 VisitRoot(root);
859 }
860 }
861
862 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
863 SHARED_REQUIRES(Locks::mutator_lock_) {
864 ConcurrentCopyingAssertToSpaceInvariantRefsVisitor visitor(collector_);
865 visitor(root->AsMirrorPtr());
866 }
867
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800868 private:
Mathieu Chartier97509952015-07-13 14:35:43 -0700869 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800870};
871
872class ConcurrentCopyingAssertToSpaceInvariantObjectVisitor {
873 public:
874 explicit ConcurrentCopyingAssertToSpaceInvariantObjectVisitor(ConcurrentCopying* collector)
875 : collector_(collector) {}
876 void operator()(mirror::Object* obj) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700877 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800878 ObjectCallback(obj, collector_);
879 }
880 static void ObjectCallback(mirror::Object* obj, void *arg)
Mathieu Chartier90443472015-07-16 20:32:27 -0700881 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800882 CHECK(obj != nullptr);
883 ConcurrentCopying* collector = reinterpret_cast<ConcurrentCopying*>(arg);
884 space::RegionSpace* region_space = collector->RegionSpace();
885 CHECK(!region_space->IsInFromSpace(obj)) << "Scanning object " << obj << " in from space";
886 collector->AssertToSpaceInvariant(nullptr, MemberOffset(0), obj);
887 ConcurrentCopyingAssertToSpaceInvariantFieldVisitor visitor(collector);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -0700888 obj->VisitReferences(visitor, visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800889 }
890
891 private:
Mathieu Chartier97509952015-07-13 14:35:43 -0700892 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800893};
894
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700895class RevokeThreadLocalMarkStackCheckpoint : public Closure {
896 public:
Roland Levillain3887c462015-08-12 18:15:42 +0100897 RevokeThreadLocalMarkStackCheckpoint(ConcurrentCopying* concurrent_copying,
898 bool disable_weak_ref_access)
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700899 : concurrent_copying_(concurrent_copying),
900 disable_weak_ref_access_(disable_weak_ref_access) {
901 }
902
903 virtual void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
904 // Note: self is not necessarily equal to thread since thread may be suspended.
905 Thread* self = Thread::Current();
906 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
907 << thread->GetState() << " thread " << thread << " self " << self;
908 // Revoke thread local mark stacks.
909 accounting::AtomicStack<mirror::Object>* tl_mark_stack = thread->GetThreadLocalMarkStack();
910 if (tl_mark_stack != nullptr) {
911 MutexLock mu(self, concurrent_copying_->mark_stack_lock_);
912 concurrent_copying_->revoked_mark_stacks_.push_back(tl_mark_stack);
913 thread->SetThreadLocalMarkStack(nullptr);
914 }
915 // Disable weak ref access.
916 if (disable_weak_ref_access_) {
917 thread->SetWeakRefAccessEnabled(false);
918 }
919 // If thread is a running mutator, then act on behalf of the garbage collector.
920 // See the code in ThreadList::RunCheckpoint.
Mathieu Chartier10d25082015-10-28 18:36:09 -0700921 concurrent_copying_->GetBarrier().Pass(self);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700922 }
923
924 private:
925 ConcurrentCopying* const concurrent_copying_;
926 const bool disable_weak_ref_access_;
927};
928
929void ConcurrentCopying::RevokeThreadLocalMarkStacks(bool disable_weak_ref_access) {
930 Thread* self = Thread::Current();
931 RevokeThreadLocalMarkStackCheckpoint check_point(this, disable_weak_ref_access);
932 ThreadList* thread_list = Runtime::Current()->GetThreadList();
933 gc_barrier_->Init(self, 0);
934 size_t barrier_count = thread_list->RunCheckpoint(&check_point);
935 // If there are no threads to wait which implys that all the checkpoint functions are finished,
936 // then no need to release the mutator lock.
937 if (barrier_count == 0) {
938 return;
939 }
940 Locks::mutator_lock_->SharedUnlock(self);
941 {
942 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
943 gc_barrier_->Increment(self, barrier_count);
944 }
945 Locks::mutator_lock_->SharedLock(self);
946}
947
948void ConcurrentCopying::RevokeThreadLocalMarkStack(Thread* thread) {
949 Thread* self = Thread::Current();
950 CHECK_EQ(self, thread);
951 accounting::AtomicStack<mirror::Object>* tl_mark_stack = thread->GetThreadLocalMarkStack();
952 if (tl_mark_stack != nullptr) {
953 CHECK(is_marking_);
954 MutexLock mu(self, mark_stack_lock_);
955 revoked_mark_stacks_.push_back(tl_mark_stack);
956 thread->SetThreadLocalMarkStack(nullptr);
957 }
958}
959
960void ConcurrentCopying::ProcessMarkStack() {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800961 if (kVerboseMode) {
962 LOG(INFO) << "ProcessMarkStack. ";
963 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700964 bool empty_prev = false;
965 while (true) {
966 bool empty = ProcessMarkStackOnce();
967 if (empty_prev && empty) {
968 // Saw empty mark stack for a second time, done.
969 break;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800970 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700971 empty_prev = empty;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800972 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700973}
974
975bool ConcurrentCopying::ProcessMarkStackOnce() {
976 Thread* self = Thread::Current();
977 CHECK(thread_running_gc_ != nullptr);
978 CHECK(self == thread_running_gc_);
979 CHECK(self->GetThreadLocalMarkStack() == nullptr);
980 size_t count = 0;
981 MarkStackMode mark_stack_mode = mark_stack_mode_.LoadRelaxed();
982 if (mark_stack_mode == kMarkStackModeThreadLocal) {
983 // Process the thread-local mark stacks and the GC mark stack.
984 count += ProcessThreadLocalMarkStacks(false);
985 while (!gc_mark_stack_->IsEmpty()) {
986 mirror::Object* to_ref = gc_mark_stack_->PopBack();
987 ProcessMarkStackRef(to_ref);
988 ++count;
989 }
990 gc_mark_stack_->Reset();
991 } else if (mark_stack_mode == kMarkStackModeShared) {
992 // Process the shared GC mark stack with a lock.
993 {
994 MutexLock mu(self, mark_stack_lock_);
995 CHECK(revoked_mark_stacks_.empty());
996 }
997 while (true) {
998 std::vector<mirror::Object*> refs;
999 {
1000 // Copy refs with lock. Note the number of refs should be small.
1001 MutexLock mu(self, mark_stack_lock_);
1002 if (gc_mark_stack_->IsEmpty()) {
1003 break;
1004 }
1005 for (StackReference<mirror::Object>* p = gc_mark_stack_->Begin();
1006 p != gc_mark_stack_->End(); ++p) {
1007 refs.push_back(p->AsMirrorPtr());
1008 }
1009 gc_mark_stack_->Reset();
1010 }
1011 for (mirror::Object* ref : refs) {
1012 ProcessMarkStackRef(ref);
1013 ++count;
1014 }
1015 }
1016 } else {
1017 CHECK_EQ(static_cast<uint32_t>(mark_stack_mode),
1018 static_cast<uint32_t>(kMarkStackModeGcExclusive));
1019 {
1020 MutexLock mu(self, mark_stack_lock_);
1021 CHECK(revoked_mark_stacks_.empty());
1022 }
1023 // Process the GC mark stack in the exclusive mode. No need to take the lock.
1024 while (!gc_mark_stack_->IsEmpty()) {
1025 mirror::Object* to_ref = gc_mark_stack_->PopBack();
1026 ProcessMarkStackRef(to_ref);
1027 ++count;
1028 }
1029 gc_mark_stack_->Reset();
1030 }
1031
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001032 // Return true if the stack was empty.
1033 return count == 0;
1034}
1035
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001036size_t ConcurrentCopying::ProcessThreadLocalMarkStacks(bool disable_weak_ref_access) {
1037 // Run a checkpoint to collect all thread local mark stacks and iterate over them all.
1038 RevokeThreadLocalMarkStacks(disable_weak_ref_access);
1039 size_t count = 0;
1040 std::vector<accounting::AtomicStack<mirror::Object>*> mark_stacks;
1041 {
1042 MutexLock mu(Thread::Current(), mark_stack_lock_);
1043 // Make a copy of the mark stack vector.
1044 mark_stacks = revoked_mark_stacks_;
1045 revoked_mark_stacks_.clear();
1046 }
1047 for (accounting::AtomicStack<mirror::Object>* mark_stack : mark_stacks) {
1048 for (StackReference<mirror::Object>* p = mark_stack->Begin(); p != mark_stack->End(); ++p) {
1049 mirror::Object* to_ref = p->AsMirrorPtr();
1050 ProcessMarkStackRef(to_ref);
1051 ++count;
1052 }
1053 {
1054 MutexLock mu(Thread::Current(), mark_stack_lock_);
1055 if (pooled_mark_stacks_.size() >= kMarkStackPoolSize) {
1056 // The pool has enough. Delete it.
1057 delete mark_stack;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001058 } else {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001059 // Otherwise, put it into the pool for later reuse.
1060 mark_stack->Reset();
1061 pooled_mark_stacks_.push_back(mark_stack);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001062 }
1063 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001064 }
1065 return count;
1066}
1067
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001068inline void ConcurrentCopying::ProcessMarkStackRef(mirror::Object* to_ref) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001069 DCHECK(!region_space_->IsInFromSpace(to_ref));
1070 if (kUseBakerReadBarrier) {
1071 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr())
1072 << " " << to_ref << " " << to_ref->GetReadBarrierPointer()
1073 << " is_marked=" << IsMarked(to_ref);
1074 }
1075 // Scan ref fields.
1076 Scan(to_ref);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001077 if (kUseBakerReadBarrier) {
1078 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr())
1079 << " " << to_ref << " " << to_ref->GetReadBarrierPointer()
1080 << " is_marked=" << IsMarked(to_ref);
1081 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001082#ifdef USE_BAKER_OR_BROOKS_READ_BARRIER
1083 if (UNLIKELY((to_ref->GetClass<kVerifyNone, kWithoutReadBarrier>()->IsTypeOfReferenceClass() &&
1084 to_ref->AsReference()->GetReferent<kWithoutReadBarrier>() != nullptr &&
1085 !IsInToSpace(to_ref->AsReference()->GetReferent<kWithoutReadBarrier>())))) {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001086 // Leave this reference gray in the queue so that GetReferent() will trigger a read barrier. We
1087 // will change it to white later in ReferenceQueue::DequeuePendingReference().
Richard Uhlere3627402016-02-02 13:36:55 -08001088 DCHECK(to_ref->AsReference()->GetPendingNext() != nullptr) << "Left unenqueued ref gray " << to_ref;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001089 } else {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001090 // We may occasionally leave a reference white in the queue if its referent happens to be
1091 // concurrently marked after the Scan() call above has enqueued the Reference, in which case the
1092 // above IsInToSpace() evaluates to true and we change the color from gray to white here in this
1093 // else block.
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001094 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001095 bool success = to_ref->AtomicSetReadBarrierPointer</*kCasRelease*/true>(
1096 ReadBarrier::GrayPtr(),
1097 ReadBarrier::WhitePtr());
1098 DCHECK(success) << "Must succeed as we won the race.";
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001099 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001100 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001101#else
1102 DCHECK(!kUseBakerReadBarrier);
1103#endif
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001104
1105 if (region_space_->IsInUnevacFromSpace(to_ref)) {
1106 // Add to the live bytes per unevacuated from space. Note this code is always run by the
1107 // GC-running thread (no synchronization required).
1108 DCHECK(region_space_bitmap_->Test(to_ref));
1109 // Disable the read barrier in SizeOf for performance, which is safe.
1110 size_t obj_size = to_ref->SizeOf<kDefaultVerifyFlags, kWithoutReadBarrier>();
1111 size_t alloc_size = RoundUp(obj_size, space::RegionSpace::kAlignment);
1112 region_space_->AddLiveBytes(to_ref, alloc_size);
1113 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001114 if (ReadBarrier::kEnableToSpaceInvariantChecks || kIsDebugBuild) {
1115 ConcurrentCopyingAssertToSpaceInvariantObjectVisitor visitor(this);
1116 visitor(to_ref);
1117 }
1118}
1119
1120void ConcurrentCopying::SwitchToSharedMarkStackMode() {
1121 Thread* self = Thread::Current();
1122 CHECK(thread_running_gc_ != nullptr);
1123 CHECK_EQ(self, thread_running_gc_);
1124 CHECK(self->GetThreadLocalMarkStack() == nullptr);
1125 MarkStackMode before_mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1126 CHECK_EQ(static_cast<uint32_t>(before_mark_stack_mode),
1127 static_cast<uint32_t>(kMarkStackModeThreadLocal));
1128 mark_stack_mode_.StoreRelaxed(kMarkStackModeShared);
1129 CHECK(weak_ref_access_enabled_.LoadRelaxed());
1130 weak_ref_access_enabled_.StoreRelaxed(false);
1131 QuasiAtomic::ThreadFenceForConstructor();
1132 // Process the thread local mark stacks one last time after switching to the shared mark stack
1133 // mode and disable weak ref accesses.
1134 ProcessThreadLocalMarkStacks(true);
1135 if (kVerboseMode) {
1136 LOG(INFO) << "Switched to shared mark stack mode and disabled weak ref access";
1137 }
1138}
1139
1140void ConcurrentCopying::SwitchToGcExclusiveMarkStackMode() {
1141 Thread* self = Thread::Current();
1142 CHECK(thread_running_gc_ != nullptr);
1143 CHECK_EQ(self, thread_running_gc_);
1144 CHECK(self->GetThreadLocalMarkStack() == nullptr);
1145 MarkStackMode before_mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1146 CHECK_EQ(static_cast<uint32_t>(before_mark_stack_mode),
1147 static_cast<uint32_t>(kMarkStackModeShared));
1148 mark_stack_mode_.StoreRelaxed(kMarkStackModeGcExclusive);
1149 QuasiAtomic::ThreadFenceForConstructor();
1150 if (kVerboseMode) {
1151 LOG(INFO) << "Switched to GC exclusive mark stack mode";
1152 }
1153}
1154
1155void ConcurrentCopying::CheckEmptyMarkStack() {
1156 Thread* self = Thread::Current();
1157 CHECK(thread_running_gc_ != nullptr);
1158 CHECK_EQ(self, thread_running_gc_);
1159 CHECK(self->GetThreadLocalMarkStack() == nullptr);
1160 MarkStackMode mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1161 if (mark_stack_mode == kMarkStackModeThreadLocal) {
1162 // Thread-local mark stack mode.
1163 RevokeThreadLocalMarkStacks(false);
1164 MutexLock mu(Thread::Current(), mark_stack_lock_);
1165 if (!revoked_mark_stacks_.empty()) {
1166 for (accounting::AtomicStack<mirror::Object>* mark_stack : revoked_mark_stacks_) {
1167 while (!mark_stack->IsEmpty()) {
1168 mirror::Object* obj = mark_stack->PopBack();
1169 if (kUseBakerReadBarrier) {
1170 mirror::Object* rb_ptr = obj->GetReadBarrierPointer();
1171 LOG(INFO) << "On mark queue : " << obj << " " << PrettyTypeOf(obj) << " rb_ptr=" << rb_ptr
1172 << " is_marked=" << IsMarked(obj);
1173 } else {
1174 LOG(INFO) << "On mark queue : " << obj << " " << PrettyTypeOf(obj)
1175 << " is_marked=" << IsMarked(obj);
1176 }
1177 }
1178 }
1179 LOG(FATAL) << "mark stack is not empty";
1180 }
1181 } else {
1182 // Shared, GC-exclusive, or off.
1183 MutexLock mu(Thread::Current(), mark_stack_lock_);
1184 CHECK(gc_mark_stack_->IsEmpty());
1185 CHECK(revoked_mark_stacks_.empty());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001186 }
1187}
1188
1189void ConcurrentCopying::SweepSystemWeaks(Thread* self) {
1190 TimingLogger::ScopedTiming split("SweepSystemWeaks", GetTimings());
1191 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier97509952015-07-13 14:35:43 -07001192 Runtime::Current()->SweepSystemWeaks(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001193}
1194
1195void ConcurrentCopying::Sweep(bool swap_bitmaps) {
1196 {
1197 TimingLogger::ScopedTiming t("MarkStackAsLive", GetTimings());
1198 accounting::ObjectStack* live_stack = heap_->GetLiveStack();
1199 if (kEnableFromSpaceAccountingCheck) {
1200 CHECK_GE(live_stack_freeze_size_, live_stack->Size());
1201 }
1202 heap_->MarkAllocStackAsLive(live_stack);
1203 live_stack->Reset();
1204 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001205 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001206 TimingLogger::ScopedTiming split("Sweep", GetTimings());
1207 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
1208 if (space->IsContinuousMemMapAllocSpace()) {
1209 space::ContinuousMemMapAllocSpace* alloc_space = space->AsContinuousMemMapAllocSpace();
Mathieu Chartier763a31e2015-11-16 16:05:55 -08001210 if (space == region_space_ || immune_spaces_.ContainsSpace(space)) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001211 continue;
1212 }
1213 TimingLogger::ScopedTiming split2(
1214 alloc_space->IsZygoteSpace() ? "SweepZygoteSpace" : "SweepAllocSpace", GetTimings());
1215 RecordFree(alloc_space->Sweep(swap_bitmaps));
1216 }
1217 }
1218 SweepLargeObjects(swap_bitmaps);
1219}
1220
1221void ConcurrentCopying::SweepLargeObjects(bool swap_bitmaps) {
1222 TimingLogger::ScopedTiming split("SweepLargeObjects", GetTimings());
1223 RecordFreeLOS(heap_->GetLargeObjectsSpace()->Sweep(swap_bitmaps));
1224}
1225
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001226void ConcurrentCopying::ReclaimPhase() {
1227 TimingLogger::ScopedTiming split("ReclaimPhase", GetTimings());
1228 if (kVerboseMode) {
1229 LOG(INFO) << "GC ReclaimPhase";
1230 }
1231 Thread* self = Thread::Current();
1232
1233 {
1234 // Double-check that the mark stack is empty.
1235 // Note: need to set this after VerifyNoFromSpaceRef().
1236 is_asserting_to_space_invariant_ = false;
1237 QuasiAtomic::ThreadFenceForConstructor();
1238 if (kVerboseMode) {
1239 LOG(INFO) << "Issue an empty check point. ";
1240 }
1241 IssueEmptyCheckpoint();
1242 // Disable the check.
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001243 is_mark_stack_push_disallowed_.StoreSequentiallyConsistent(0);
1244 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001245 }
1246
1247 {
1248 // Record freed objects.
1249 TimingLogger::ScopedTiming split2("RecordFree", GetTimings());
1250 // Don't include thread-locals that are in the to-space.
1251 uint64_t from_bytes = region_space_->GetBytesAllocatedInFromSpace();
1252 uint64_t from_objects = region_space_->GetObjectsAllocatedInFromSpace();
1253 uint64_t unevac_from_bytes = region_space_->GetBytesAllocatedInUnevacFromSpace();
1254 uint64_t unevac_from_objects = region_space_->GetObjectsAllocatedInUnevacFromSpace();
1255 uint64_t to_bytes = bytes_moved_.LoadSequentiallyConsistent();
1256 uint64_t to_objects = objects_moved_.LoadSequentiallyConsistent();
1257 if (kEnableFromSpaceAccountingCheck) {
1258 CHECK_EQ(from_space_num_objects_at_first_pause_, from_objects + unevac_from_objects);
1259 CHECK_EQ(from_space_num_bytes_at_first_pause_, from_bytes + unevac_from_bytes);
1260 }
1261 CHECK_LE(to_objects, from_objects);
1262 CHECK_LE(to_bytes, from_bytes);
1263 int64_t freed_bytes = from_bytes - to_bytes;
1264 int64_t freed_objects = from_objects - to_objects;
1265 if (kVerboseMode) {
1266 LOG(INFO) << "RecordFree:"
1267 << " from_bytes=" << from_bytes << " from_objects=" << from_objects
1268 << " unevac_from_bytes=" << unevac_from_bytes << " unevac_from_objects=" << unevac_from_objects
1269 << " to_bytes=" << to_bytes << " to_objects=" << to_objects
1270 << " freed_bytes=" << freed_bytes << " freed_objects=" << freed_objects
1271 << " from_space size=" << region_space_->FromSpaceSize()
1272 << " unevac_from_space size=" << region_space_->UnevacFromSpaceSize()
1273 << " to_space size=" << region_space_->ToSpaceSize();
1274 LOG(INFO) << "(before) num_bytes_allocated=" << heap_->num_bytes_allocated_.LoadSequentiallyConsistent();
1275 }
1276 RecordFree(ObjectBytePair(freed_objects, freed_bytes));
1277 if (kVerboseMode) {
1278 LOG(INFO) << "(after) num_bytes_allocated=" << heap_->num_bytes_allocated_.LoadSequentiallyConsistent();
1279 }
1280 }
1281
1282 {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001283 TimingLogger::ScopedTiming split4("ClearFromSpace", GetTimings());
1284 region_space_->ClearFromSpace();
1285 }
1286
1287 {
1288 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001289 Sweep(false);
1290 SwapBitmaps();
1291 heap_->UnBindBitmaps();
1292
1293 // Remove bitmaps for the immune spaces.
1294 while (!cc_bitmaps_.empty()) {
1295 accounting::ContinuousSpaceBitmap* cc_bitmap = cc_bitmaps_.back();
1296 cc_heap_bitmap_->RemoveContinuousSpaceBitmap(cc_bitmap);
1297 delete cc_bitmap;
1298 cc_bitmaps_.pop_back();
1299 }
1300 region_space_bitmap_ = nullptr;
1301 }
1302
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001303 CheckEmptyMarkStack();
1304
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001305 if (kVerboseMode) {
1306 LOG(INFO) << "GC end of ReclaimPhase";
1307 }
1308}
1309
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001310// Assert the to-space invariant.
1311void ConcurrentCopying::AssertToSpaceInvariant(mirror::Object* obj, MemberOffset offset,
1312 mirror::Object* ref) {
1313 CHECK(heap_->collector_type_ == kCollectorTypeCC) << static_cast<size_t>(heap_->collector_type_);
1314 if (is_asserting_to_space_invariant_) {
1315 if (region_space_->IsInToSpace(ref)) {
1316 // OK.
1317 return;
1318 } else if (region_space_->IsInUnevacFromSpace(ref)) {
1319 CHECK(region_space_bitmap_->Test(ref)) << ref;
1320 } else if (region_space_->IsInFromSpace(ref)) {
1321 // Not OK. Do extra logging.
1322 if (obj != nullptr) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001323 LogFromSpaceRefHolder(obj, offset);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001324 }
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001325 ref->GetLockWord(false).Dump(LOG(INTERNAL_FATAL));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001326 CHECK(false) << "Found from-space ref " << ref << " " << PrettyTypeOf(ref);
1327 } else {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001328 AssertToSpaceInvariantInNonMovingSpace(obj, ref);
1329 }
1330 }
1331}
1332
1333class RootPrinter {
1334 public:
1335 RootPrinter() { }
1336
1337 template <class MirrorType>
1338 ALWAYS_INLINE void VisitRootIfNonNull(mirror::CompressedReference<MirrorType>* root)
Mathieu Chartier90443472015-07-16 20:32:27 -07001339 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001340 if (!root->IsNull()) {
1341 VisitRoot(root);
1342 }
1343 }
1344
1345 template <class MirrorType>
1346 void VisitRoot(mirror::Object** root)
Mathieu Chartier90443472015-07-16 20:32:27 -07001347 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001348 LOG(INTERNAL_FATAL) << "root=" << root << " ref=" << *root;
1349 }
1350
1351 template <class MirrorType>
1352 void VisitRoot(mirror::CompressedReference<MirrorType>* root)
Mathieu Chartier90443472015-07-16 20:32:27 -07001353 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001354 LOG(INTERNAL_FATAL) << "root=" << root << " ref=" << root->AsMirrorPtr();
1355 }
1356};
1357
1358void ConcurrentCopying::AssertToSpaceInvariant(GcRootSource* gc_root_source,
1359 mirror::Object* ref) {
1360 CHECK(heap_->collector_type_ == kCollectorTypeCC) << static_cast<size_t>(heap_->collector_type_);
1361 if (is_asserting_to_space_invariant_) {
1362 if (region_space_->IsInToSpace(ref)) {
1363 // OK.
1364 return;
1365 } else if (region_space_->IsInUnevacFromSpace(ref)) {
1366 CHECK(region_space_bitmap_->Test(ref)) << ref;
1367 } else if (region_space_->IsInFromSpace(ref)) {
1368 // Not OK. Do extra logging.
1369 if (gc_root_source == nullptr) {
1370 // No info.
1371 } else if (gc_root_source->HasArtField()) {
1372 ArtField* field = gc_root_source->GetArtField();
1373 LOG(INTERNAL_FATAL) << "gc root in field " << field << " " << PrettyField(field);
1374 RootPrinter root_printer;
1375 field->VisitRoots(root_printer);
1376 } else if (gc_root_source->HasArtMethod()) {
1377 ArtMethod* method = gc_root_source->GetArtMethod();
1378 LOG(INTERNAL_FATAL) << "gc root in method " << method << " " << PrettyMethod(method);
1379 RootPrinter root_printer;
Mathieu Chartier1147b9b2015-09-14 18:50:08 -07001380 method->VisitRoots(root_printer, sizeof(void*));
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001381 }
1382 ref->GetLockWord(false).Dump(LOG(INTERNAL_FATAL));
1383 region_space_->DumpNonFreeRegions(LOG(INTERNAL_FATAL));
1384 PrintFileToLog("/proc/self/maps", LogSeverity::INTERNAL_FATAL);
1385 MemMap::DumpMaps(LOG(INTERNAL_FATAL), true);
1386 CHECK(false) << "Found from-space ref " << ref << " " << PrettyTypeOf(ref);
1387 } else {
1388 AssertToSpaceInvariantInNonMovingSpace(nullptr, ref);
1389 }
1390 }
1391}
1392
1393void ConcurrentCopying::LogFromSpaceRefHolder(mirror::Object* obj, MemberOffset offset) {
1394 if (kUseBakerReadBarrier) {
1395 LOG(INFO) << "holder=" << obj << " " << PrettyTypeOf(obj)
1396 << " holder rb_ptr=" << obj->GetReadBarrierPointer();
1397 } else {
1398 LOG(INFO) << "holder=" << obj << " " << PrettyTypeOf(obj);
1399 }
1400 if (region_space_->IsInFromSpace(obj)) {
1401 LOG(INFO) << "holder is in the from-space.";
1402 } else if (region_space_->IsInToSpace(obj)) {
1403 LOG(INFO) << "holder is in the to-space.";
1404 } else if (region_space_->IsInUnevacFromSpace(obj)) {
1405 LOG(INFO) << "holder is in the unevac from-space.";
1406 if (region_space_bitmap_->Test(obj)) {
1407 LOG(INFO) << "holder is marked in the region space bitmap.";
1408 } else {
1409 LOG(INFO) << "holder is not marked in the region space bitmap.";
1410 }
1411 } else {
1412 // In a non-moving space.
Mathieu Chartier763a31e2015-11-16 16:05:55 -08001413 if (immune_spaces_.ContainsObject(obj)) {
1414 LOG(INFO) << "holder is in an immune image or the zygote space.";
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001415 accounting::ContinuousSpaceBitmap* cc_bitmap =
1416 cc_heap_bitmap_->GetContinuousSpaceBitmap(obj);
1417 CHECK(cc_bitmap != nullptr)
1418 << "An immune space object must have a bitmap.";
1419 if (cc_bitmap->Test(obj)) {
1420 LOG(INFO) << "holder is marked in the bit map.";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001421 } else {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001422 LOG(INFO) << "holder is NOT marked in the bit map.";
1423 }
1424 } else {
Mathieu Chartier763a31e2015-11-16 16:05:55 -08001425 LOG(INFO) << "holder is in a non-immune, non-moving (or main) space.";
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001426 accounting::ContinuousSpaceBitmap* mark_bitmap =
1427 heap_mark_bitmap_->GetContinuousSpaceBitmap(obj);
1428 accounting::LargeObjectBitmap* los_bitmap =
1429 heap_mark_bitmap_->GetLargeObjectBitmap(obj);
1430 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
1431 bool is_los = mark_bitmap == nullptr;
1432 if (!is_los && mark_bitmap->Test(obj)) {
1433 LOG(INFO) << "holder is marked in the mark bit map.";
1434 } else if (is_los && los_bitmap->Test(obj)) {
1435 LOG(INFO) << "holder is marked in the los bit map.";
1436 } else {
1437 // If ref is on the allocation stack, then it is considered
1438 // mark/alive (but not necessarily on the live stack.)
1439 if (IsOnAllocStack(obj)) {
1440 LOG(INFO) << "holder is on the alloc stack.";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001441 } else {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001442 LOG(INFO) << "holder is not marked or on the alloc stack.";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001443 }
1444 }
1445 }
1446 }
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001447 LOG(INFO) << "offset=" << offset.SizeValue();
1448}
1449
1450void ConcurrentCopying::AssertToSpaceInvariantInNonMovingSpace(mirror::Object* obj,
1451 mirror::Object* ref) {
1452 // In a non-moving spaces. Check that the ref is marked.
Mathieu Chartier763a31e2015-11-16 16:05:55 -08001453 if (immune_spaces_.ContainsObject(ref)) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001454 accounting::ContinuousSpaceBitmap* cc_bitmap =
1455 cc_heap_bitmap_->GetContinuousSpaceBitmap(ref);
1456 CHECK(cc_bitmap != nullptr)
1457 << "An immune space ref must have a bitmap. " << ref;
1458 if (kUseBakerReadBarrier) {
1459 CHECK(cc_bitmap->Test(ref))
1460 << "Unmarked immune space ref. obj=" << obj << " rb_ptr="
1461 << obj->GetReadBarrierPointer() << " ref=" << ref;
1462 } else {
1463 CHECK(cc_bitmap->Test(ref))
1464 << "Unmarked immune space ref. obj=" << obj << " ref=" << ref;
1465 }
1466 } else {
1467 accounting::ContinuousSpaceBitmap* mark_bitmap =
1468 heap_mark_bitmap_->GetContinuousSpaceBitmap(ref);
1469 accounting::LargeObjectBitmap* los_bitmap =
1470 heap_mark_bitmap_->GetLargeObjectBitmap(ref);
1471 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
1472 bool is_los = mark_bitmap == nullptr;
1473 if ((!is_los && mark_bitmap->Test(ref)) ||
1474 (is_los && los_bitmap->Test(ref))) {
1475 // OK.
1476 } else {
1477 // If ref is on the allocation stack, then it may not be
1478 // marked live, but considered marked/alive (but not
1479 // necessarily on the live stack).
1480 CHECK(IsOnAllocStack(ref)) << "Unmarked ref that's not on the allocation stack. "
1481 << "obj=" << obj << " ref=" << ref;
1482 }
1483 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001484}
1485
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001486// Used to scan ref fields of an object.
1487class ConcurrentCopyingRefFieldsVisitor {
1488 public:
1489 explicit ConcurrentCopyingRefFieldsVisitor(ConcurrentCopying* collector)
1490 : collector_(collector) {}
1491
1492 void operator()(mirror::Object* obj, MemberOffset offset, bool /* is_static */)
Mathieu Chartier90443472015-07-16 20:32:27 -07001493 const ALWAYS_INLINE SHARED_REQUIRES(Locks::mutator_lock_)
1494 SHARED_REQUIRES(Locks::heap_bitmap_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001495 collector_->Process(obj, offset);
1496 }
1497
1498 void operator()(mirror::Class* klass, mirror::Reference* ref) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001499 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001500 CHECK(klass->IsTypeOfReferenceClass());
1501 collector_->DelayReferenceReferent(klass, ref);
1502 }
1503
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001504 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001505 ALWAYS_INLINE
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001506 SHARED_REQUIRES(Locks::mutator_lock_) {
1507 if (!root->IsNull()) {
1508 VisitRoot(root);
1509 }
1510 }
1511
1512 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001513 ALWAYS_INLINE
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001514 SHARED_REQUIRES(Locks::mutator_lock_) {
1515 collector_->MarkRoot(root);
1516 }
1517
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001518 private:
1519 ConcurrentCopying* const collector_;
1520};
1521
1522// Scan ref fields of an object.
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001523inline void ConcurrentCopying::Scan(mirror::Object* to_ref) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001524 DCHECK(!region_space_->IsInFromSpace(to_ref));
1525 ConcurrentCopyingRefFieldsVisitor visitor(this);
Hiroshi Yamauchi5496f692016-02-17 13:29:59 -08001526 // Disable the read barrier for a performance reason.
1527 to_ref->VisitReferences</*kVisitNativeRoots*/true, kDefaultVerifyFlags, kWithoutReadBarrier>(
1528 visitor, visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001529}
1530
1531// Process a field.
1532inline void ConcurrentCopying::Process(mirror::Object* obj, MemberOffset offset) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001533 mirror::Object* ref = obj->GetFieldObject<
1534 mirror::Object, kVerifyNone, kWithoutReadBarrier, false>(offset);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001535 mirror::Object* to_ref = Mark(ref);
1536 if (to_ref == ref) {
1537 return;
1538 }
1539 // This may fail if the mutator writes to the field at the same time. But it's ok.
1540 mirror::Object* expected_ref = ref;
1541 mirror::Object* new_ref = to_ref;
1542 do {
1543 if (expected_ref !=
1544 obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier, false>(offset)) {
1545 // It was updated by the mutator.
1546 break;
1547 }
Hiroshi Yamauchifed3e2f2015-10-20 11:11:56 -07001548 } while (!obj->CasFieldWeakRelaxedObjectWithoutWriteBarrier<
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001549 false, false, kVerifyNone>(offset, expected_ref, new_ref));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001550}
1551
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001552// Process some roots.
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001553inline void ConcurrentCopying::VisitRoots(
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001554 mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED) {
1555 for (size_t i = 0; i < count; ++i) {
1556 mirror::Object** root = roots[i];
1557 mirror::Object* ref = *root;
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001558 mirror::Object* to_ref = Mark(ref);
1559 if (to_ref == ref) {
Mathieu Chartier4809d0a2015-04-07 10:39:04 -07001560 continue;
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001561 }
1562 Atomic<mirror::Object*>* addr = reinterpret_cast<Atomic<mirror::Object*>*>(root);
1563 mirror::Object* expected_ref = ref;
1564 mirror::Object* new_ref = to_ref;
1565 do {
1566 if (expected_ref != addr->LoadRelaxed()) {
1567 // It was updated by the mutator.
1568 break;
1569 }
Hiroshi Yamauchifed3e2f2015-10-20 11:11:56 -07001570 } while (!addr->CompareExchangeWeakRelaxed(expected_ref, new_ref));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001571 }
1572}
1573
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001574inline void ConcurrentCopying::MarkRoot(mirror::CompressedReference<mirror::Object>* root) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001575 DCHECK(!root->IsNull());
1576 mirror::Object* const ref = root->AsMirrorPtr();
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001577 mirror::Object* to_ref = Mark(ref);
1578 if (to_ref != ref) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001579 auto* addr = reinterpret_cast<Atomic<mirror::CompressedReference<mirror::Object>>*>(root);
1580 auto expected_ref = mirror::CompressedReference<mirror::Object>::FromMirrorPtr(ref);
1581 auto new_ref = mirror::CompressedReference<mirror::Object>::FromMirrorPtr(to_ref);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001582 // If the cas fails, then it was updated by the mutator.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001583 do {
1584 if (ref != addr->LoadRelaxed().AsMirrorPtr()) {
1585 // It was updated by the mutator.
1586 break;
1587 }
Hiroshi Yamauchifed3e2f2015-10-20 11:11:56 -07001588 } while (!addr->CompareExchangeWeakRelaxed(expected_ref, new_ref));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001589 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001590}
1591
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001592inline void ConcurrentCopying::VisitRoots(
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001593 mirror::CompressedReference<mirror::Object>** roots, size_t count,
1594 const RootInfo& info ATTRIBUTE_UNUSED) {
1595 for (size_t i = 0; i < count; ++i) {
1596 mirror::CompressedReference<mirror::Object>* const root = roots[i];
1597 if (!root->IsNull()) {
1598 MarkRoot(root);
1599 }
1600 }
1601}
1602
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001603// Fill the given memory block with a dummy object. Used to fill in a
1604// copy of objects that was lost in race.
1605void ConcurrentCopying::FillWithDummyObject(mirror::Object* dummy_obj, size_t byte_size) {
Roland Levillain14d90572015-07-16 10:52:26 +01001606 CHECK_ALIGNED(byte_size, kObjectAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001607 memset(dummy_obj, 0, byte_size);
1608 mirror::Class* int_array_class = mirror::IntArray::GetArrayClass();
1609 CHECK(int_array_class != nullptr);
1610 AssertToSpaceInvariant(nullptr, MemberOffset(0), int_array_class);
1611 size_t component_size = int_array_class->GetComponentSize();
1612 CHECK_EQ(component_size, sizeof(int32_t));
1613 size_t data_offset = mirror::Array::DataOffset(component_size).SizeValue();
1614 if (data_offset > byte_size) {
1615 // An int array is too big. Use java.lang.Object.
1616 mirror::Class* java_lang_Object = WellKnownClasses::ToClass(WellKnownClasses::java_lang_Object);
1617 AssertToSpaceInvariant(nullptr, MemberOffset(0), java_lang_Object);
1618 CHECK_EQ(byte_size, java_lang_Object->GetObjectSize());
1619 dummy_obj->SetClass(java_lang_Object);
1620 CHECK_EQ(byte_size, dummy_obj->SizeOf());
1621 } else {
1622 // Use an int array.
1623 dummy_obj->SetClass(int_array_class);
1624 CHECK(dummy_obj->IsArrayInstance());
1625 int32_t length = (byte_size - data_offset) / component_size;
1626 dummy_obj->AsArray()->SetLength(length);
1627 CHECK_EQ(dummy_obj->AsArray()->GetLength(), length)
1628 << "byte_size=" << byte_size << " length=" << length
1629 << " component_size=" << component_size << " data_offset=" << data_offset;
1630 CHECK_EQ(byte_size, dummy_obj->SizeOf())
1631 << "byte_size=" << byte_size << " length=" << length
1632 << " component_size=" << component_size << " data_offset=" << data_offset;
1633 }
1634}
1635
1636// Reuse the memory blocks that were copy of objects that were lost in race.
1637mirror::Object* ConcurrentCopying::AllocateInSkippedBlock(size_t alloc_size) {
1638 // Try to reuse the blocks that were unused due to CAS failures.
Roland Levillain14d90572015-07-16 10:52:26 +01001639 CHECK_ALIGNED(alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001640 Thread* self = Thread::Current();
1641 size_t min_object_size = RoundUp(sizeof(mirror::Object), space::RegionSpace::kAlignment);
1642 MutexLock mu(self, skipped_blocks_lock_);
1643 auto it = skipped_blocks_map_.lower_bound(alloc_size);
1644 if (it == skipped_blocks_map_.end()) {
1645 // Not found.
1646 return nullptr;
1647 }
1648 {
1649 size_t byte_size = it->first;
1650 CHECK_GE(byte_size, alloc_size);
1651 if (byte_size > alloc_size && byte_size - alloc_size < min_object_size) {
1652 // If remainder would be too small for a dummy object, retry with a larger request size.
1653 it = skipped_blocks_map_.lower_bound(alloc_size + min_object_size);
1654 if (it == skipped_blocks_map_.end()) {
1655 // Not found.
1656 return nullptr;
1657 }
Roland Levillain14d90572015-07-16 10:52:26 +01001658 CHECK_ALIGNED(it->first - alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001659 CHECK_GE(it->first - alloc_size, min_object_size)
1660 << "byte_size=" << byte_size << " it->first=" << it->first << " alloc_size=" << alloc_size;
1661 }
1662 }
1663 // Found a block.
1664 CHECK(it != skipped_blocks_map_.end());
1665 size_t byte_size = it->first;
1666 uint8_t* addr = it->second;
1667 CHECK_GE(byte_size, alloc_size);
1668 CHECK(region_space_->IsInToSpace(reinterpret_cast<mirror::Object*>(addr)));
Roland Levillain14d90572015-07-16 10:52:26 +01001669 CHECK_ALIGNED(byte_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001670 if (kVerboseMode) {
1671 LOG(INFO) << "Reusing skipped bytes : " << reinterpret_cast<void*>(addr) << ", " << byte_size;
1672 }
1673 skipped_blocks_map_.erase(it);
1674 memset(addr, 0, byte_size);
1675 if (byte_size > alloc_size) {
1676 // Return the remainder to the map.
Roland Levillain14d90572015-07-16 10:52:26 +01001677 CHECK_ALIGNED(byte_size - alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001678 CHECK_GE(byte_size - alloc_size, min_object_size);
1679 FillWithDummyObject(reinterpret_cast<mirror::Object*>(addr + alloc_size),
1680 byte_size - alloc_size);
1681 CHECK(region_space_->IsInToSpace(reinterpret_cast<mirror::Object*>(addr + alloc_size)));
1682 skipped_blocks_map_.insert(std::make_pair(byte_size - alloc_size, addr + alloc_size));
1683 }
1684 return reinterpret_cast<mirror::Object*>(addr);
1685}
1686
1687mirror::Object* ConcurrentCopying::Copy(mirror::Object* from_ref) {
1688 DCHECK(region_space_->IsInFromSpace(from_ref));
1689 // No read barrier to avoid nested RB that might violate the to-space
1690 // invariant. Note that from_ref is a from space ref so the SizeOf()
1691 // call will access the from-space meta objects, but it's ok and necessary.
1692 size_t obj_size = from_ref->SizeOf<kDefaultVerifyFlags, kWithoutReadBarrier>();
1693 size_t region_space_alloc_size = RoundUp(obj_size, space::RegionSpace::kAlignment);
1694 size_t region_space_bytes_allocated = 0U;
1695 size_t non_moving_space_bytes_allocated = 0U;
1696 size_t bytes_allocated = 0U;
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001697 size_t dummy;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001698 mirror::Object* to_ref = region_space_->AllocNonvirtual<true>(
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001699 region_space_alloc_size, &region_space_bytes_allocated, nullptr, &dummy);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001700 bytes_allocated = region_space_bytes_allocated;
1701 if (to_ref != nullptr) {
1702 DCHECK_EQ(region_space_alloc_size, region_space_bytes_allocated);
1703 }
1704 bool fall_back_to_non_moving = false;
1705 if (UNLIKELY(to_ref == nullptr)) {
1706 // Failed to allocate in the region space. Try the skipped blocks.
1707 to_ref = AllocateInSkippedBlock(region_space_alloc_size);
1708 if (to_ref != nullptr) {
1709 // Succeeded to allocate in a skipped block.
1710 if (heap_->use_tlab_) {
1711 // This is necessary for the tlab case as it's not accounted in the space.
1712 region_space_->RecordAlloc(to_ref);
1713 }
1714 bytes_allocated = region_space_alloc_size;
1715 } else {
1716 // Fall back to the non-moving space.
1717 fall_back_to_non_moving = true;
1718 if (kVerboseMode) {
1719 LOG(INFO) << "Out of memory in the to-space. Fall back to non-moving. skipped_bytes="
1720 << to_space_bytes_skipped_.LoadSequentiallyConsistent()
1721 << " skipped_objects=" << to_space_objects_skipped_.LoadSequentiallyConsistent();
1722 }
1723 fall_back_to_non_moving = true;
1724 to_ref = heap_->non_moving_space_->Alloc(Thread::Current(), obj_size,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001725 &non_moving_space_bytes_allocated, nullptr, &dummy);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001726 CHECK(to_ref != nullptr) << "Fall-back non-moving space allocation failed";
1727 bytes_allocated = non_moving_space_bytes_allocated;
1728 // Mark it in the mark bitmap.
1729 accounting::ContinuousSpaceBitmap* mark_bitmap =
1730 heap_mark_bitmap_->GetContinuousSpaceBitmap(to_ref);
1731 CHECK(mark_bitmap != nullptr);
1732 CHECK(!mark_bitmap->AtomicTestAndSet(to_ref));
1733 }
1734 }
1735 DCHECK(to_ref != nullptr);
1736
1737 // Attempt to install the forward pointer. This is in a loop as the
1738 // lock word atomic write can fail.
1739 while (true) {
1740 // Copy the object. TODO: copy only the lockword in the second iteration and on?
1741 memcpy(to_ref, from_ref, obj_size);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001742
1743 LockWord old_lock_word = to_ref->GetLockWord(false);
1744
1745 if (old_lock_word.GetState() == LockWord::kForwardingAddress) {
1746 // Lost the race. Another thread (either GC or mutator) stored
1747 // the forwarding pointer first. Make the lost copy (to_ref)
1748 // look like a valid but dead (dummy) object and keep it for
1749 // future reuse.
1750 FillWithDummyObject(to_ref, bytes_allocated);
1751 if (!fall_back_to_non_moving) {
1752 DCHECK(region_space_->IsInToSpace(to_ref));
1753 if (bytes_allocated > space::RegionSpace::kRegionSize) {
1754 // Free the large alloc.
1755 region_space_->FreeLarge(to_ref, bytes_allocated);
1756 } else {
1757 // Record the lost copy for later reuse.
1758 heap_->num_bytes_allocated_.FetchAndAddSequentiallyConsistent(bytes_allocated);
1759 to_space_bytes_skipped_.FetchAndAddSequentiallyConsistent(bytes_allocated);
1760 to_space_objects_skipped_.FetchAndAddSequentiallyConsistent(1);
1761 MutexLock mu(Thread::Current(), skipped_blocks_lock_);
1762 skipped_blocks_map_.insert(std::make_pair(bytes_allocated,
1763 reinterpret_cast<uint8_t*>(to_ref)));
1764 }
1765 } else {
1766 DCHECK(heap_->non_moving_space_->HasAddress(to_ref));
1767 DCHECK_EQ(bytes_allocated, non_moving_space_bytes_allocated);
1768 // Free the non-moving-space chunk.
1769 accounting::ContinuousSpaceBitmap* mark_bitmap =
1770 heap_mark_bitmap_->GetContinuousSpaceBitmap(to_ref);
1771 CHECK(mark_bitmap != nullptr);
1772 CHECK(mark_bitmap->Clear(to_ref));
1773 heap_->non_moving_space_->Free(Thread::Current(), to_ref);
1774 }
1775
1776 // Get the winner's forward ptr.
1777 mirror::Object* lost_fwd_ptr = to_ref;
1778 to_ref = reinterpret_cast<mirror::Object*>(old_lock_word.ForwardingAddress());
1779 CHECK(to_ref != nullptr);
1780 CHECK_NE(to_ref, lost_fwd_ptr);
1781 CHECK(region_space_->IsInToSpace(to_ref) || heap_->non_moving_space_->HasAddress(to_ref));
1782 CHECK_NE(to_ref->GetLockWord(false).GetState(), LockWord::kForwardingAddress);
1783 return to_ref;
1784 }
1785
Hiroshi Yamauchi60f63f52015-04-23 16:12:40 -07001786 // Set the gray ptr.
1787 if (kUseBakerReadBarrier) {
1788 to_ref->SetReadBarrierPointer(ReadBarrier::GrayPtr());
1789 }
1790
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001791 LockWord new_lock_word = LockWord::FromForwardingAddress(reinterpret_cast<size_t>(to_ref));
1792
1793 // Try to atomically write the fwd ptr.
1794 bool success = from_ref->CasLockWordWeakSequentiallyConsistent(old_lock_word, new_lock_word);
1795 if (LIKELY(success)) {
1796 // The CAS succeeded.
1797 objects_moved_.FetchAndAddSequentiallyConsistent(1);
1798 bytes_moved_.FetchAndAddSequentiallyConsistent(region_space_alloc_size);
1799 if (LIKELY(!fall_back_to_non_moving)) {
1800 DCHECK(region_space_->IsInToSpace(to_ref));
1801 } else {
1802 DCHECK(heap_->non_moving_space_->HasAddress(to_ref));
1803 DCHECK_EQ(bytes_allocated, non_moving_space_bytes_allocated);
1804 }
1805 if (kUseBakerReadBarrier) {
1806 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr());
1807 }
1808 DCHECK(GetFwdPtr(from_ref) == to_ref);
1809 CHECK_NE(to_ref->GetLockWord(false).GetState(), LockWord::kForwardingAddress);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001810 PushOntoMarkStack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001811 return to_ref;
1812 } else {
1813 // The CAS failed. It may have lost the race or may have failed
1814 // due to monitor/hashcode ops. Either way, retry.
1815 }
1816 }
1817}
1818
1819mirror::Object* ConcurrentCopying::IsMarked(mirror::Object* from_ref) {
1820 DCHECK(from_ref != nullptr);
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08001821 space::RegionSpace::RegionType rtype = region_space_->GetRegionType(from_ref);
1822 if (rtype == space::RegionSpace::RegionType::kRegionTypeToSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001823 // It's already marked.
1824 return from_ref;
1825 }
1826 mirror::Object* to_ref;
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08001827 if (rtype == space::RegionSpace::RegionType::kRegionTypeFromSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001828 to_ref = GetFwdPtr(from_ref);
1829 DCHECK(to_ref == nullptr || region_space_->IsInToSpace(to_ref) ||
1830 heap_->non_moving_space_->HasAddress(to_ref))
1831 << "from_ref=" << from_ref << " to_ref=" << to_ref;
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08001832 } else if (rtype == space::RegionSpace::RegionType::kRegionTypeUnevacFromSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001833 if (region_space_bitmap_->Test(from_ref)) {
1834 to_ref = from_ref;
1835 } else {
1836 to_ref = nullptr;
1837 }
1838 } else {
1839 // from_ref is in a non-moving space.
Mathieu Chartier763a31e2015-11-16 16:05:55 -08001840 if (immune_spaces_.ContainsObject(from_ref)) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001841 accounting::ContinuousSpaceBitmap* cc_bitmap =
1842 cc_heap_bitmap_->GetContinuousSpaceBitmap(from_ref);
1843 DCHECK(cc_bitmap != nullptr)
1844 << "An immune space object must have a bitmap";
1845 if (kIsDebugBuild) {
1846 DCHECK(heap_mark_bitmap_->GetContinuousSpaceBitmap(from_ref)->Test(from_ref))
1847 << "Immune space object must be already marked";
1848 }
1849 if (cc_bitmap->Test(from_ref)) {
1850 // Already marked.
1851 to_ref = from_ref;
1852 } else {
1853 // Newly marked.
1854 to_ref = nullptr;
1855 }
1856 } else {
1857 // Non-immune non-moving space. Use the mark bitmap.
1858 accounting::ContinuousSpaceBitmap* mark_bitmap =
1859 heap_mark_bitmap_->GetContinuousSpaceBitmap(from_ref);
1860 accounting::LargeObjectBitmap* los_bitmap =
1861 heap_mark_bitmap_->GetLargeObjectBitmap(from_ref);
1862 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
1863 bool is_los = mark_bitmap == nullptr;
1864 if (!is_los && mark_bitmap->Test(from_ref)) {
1865 // Already marked.
1866 to_ref = from_ref;
1867 } else if (is_los && los_bitmap->Test(from_ref)) {
1868 // Already marked in LOS.
1869 to_ref = from_ref;
1870 } else {
1871 // Not marked.
1872 if (IsOnAllocStack(from_ref)) {
1873 // If on the allocation stack, it's considered marked.
1874 to_ref = from_ref;
1875 } else {
1876 // Not marked.
1877 to_ref = nullptr;
1878 }
1879 }
1880 }
1881 }
1882 return to_ref;
1883}
1884
1885bool ConcurrentCopying::IsOnAllocStack(mirror::Object* ref) {
1886 QuasiAtomic::ThreadFenceAcquire();
1887 accounting::ObjectStack* alloc_stack = GetAllocationStack();
Mathieu Chartiercb535da2015-01-23 13:50:03 -08001888 return alloc_stack->Contains(ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001889}
1890
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001891mirror::Object* ConcurrentCopying::MarkNonMoving(mirror::Object* ref) {
1892 // ref is in a non-moving space (from_ref == to_ref).
1893 DCHECK(!region_space_->HasAddress(ref)) << ref;
Mathieu Chartier763a31e2015-11-16 16:05:55 -08001894 if (immune_spaces_.ContainsObject(ref)) {
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001895 accounting::ContinuousSpaceBitmap* cc_bitmap =
1896 cc_heap_bitmap_->GetContinuousSpaceBitmap(ref);
1897 DCHECK(cc_bitmap != nullptr)
1898 << "An immune space object must have a bitmap";
1899 if (kIsDebugBuild) {
1900 DCHECK(heap_mark_bitmap_->GetContinuousSpaceBitmap(ref)->Test(ref))
1901 << "Immune space object must be already marked";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001902 }
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001903 MarkUnevacFromSpaceRegionOrImmuneSpace(ref, cc_bitmap);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001904 } else {
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001905 // Use the mark bitmap.
1906 accounting::ContinuousSpaceBitmap* mark_bitmap =
1907 heap_mark_bitmap_->GetContinuousSpaceBitmap(ref);
1908 accounting::LargeObjectBitmap* los_bitmap =
1909 heap_mark_bitmap_->GetLargeObjectBitmap(ref);
1910 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
1911 bool is_los = mark_bitmap == nullptr;
1912 if (!is_los && mark_bitmap->Test(ref)) {
1913 // Already marked.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001914 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001915 DCHECK(ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr() ||
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001916 ref->GetReadBarrierPointer() == ReadBarrier::WhitePtr());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001917 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001918 } else if (is_los && los_bitmap->Test(ref)) {
1919 // Already marked in LOS.
1920 if (kUseBakerReadBarrier) {
1921 DCHECK(ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr() ||
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001922 ref->GetReadBarrierPointer() == ReadBarrier::WhitePtr());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001923 }
1924 } else {
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001925 // Not marked.
1926 if (IsOnAllocStack(ref)) {
1927 // If it's on the allocation stack, it's considered marked. Keep it white.
1928 // Objects on the allocation stack need not be marked.
1929 if (!is_los) {
1930 DCHECK(!mark_bitmap->Test(ref));
1931 } else {
1932 DCHECK(!los_bitmap->Test(ref));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001933 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001934 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001935 DCHECK_EQ(ref->GetReadBarrierPointer(), ReadBarrier::WhitePtr());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001936 }
1937 } else {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001938 // For the baker-style RB, we need to handle 'false-gray' cases. See the
1939 // kRegionTypeUnevacFromSpace-case comment in Mark().
1940 if (kUseBakerReadBarrier) {
1941 // Test the bitmap first to reduce the chance of false gray cases.
1942 if ((!is_los && mark_bitmap->Test(ref)) ||
1943 (is_los && los_bitmap->Test(ref))) {
1944 return ref;
1945 }
1946 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001947 // Not marked or on the allocation stack. Try to mark it.
1948 // This may or may not succeed, which is ok.
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001949 bool cas_success = false;
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001950 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001951 cas_success = ref->AtomicSetReadBarrierPointer(ReadBarrier::WhitePtr(),
1952 ReadBarrier::GrayPtr());
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001953 }
1954 if (!is_los && mark_bitmap->AtomicTestAndSet(ref)) {
1955 // Already marked.
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001956 if (kUseBakerReadBarrier && cas_success &&
1957 ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr()) {
1958 PushOntoFalseGrayStack(ref);
1959 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001960 } else if (is_los && los_bitmap->AtomicTestAndSet(ref)) {
1961 // Already marked in LOS.
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001962 if (kUseBakerReadBarrier && cas_success &&
1963 ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr()) {
1964 PushOntoFalseGrayStack(ref);
1965 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001966 } else {
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001967 // Newly marked.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001968 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001969 DCHECK_EQ(ref->GetReadBarrierPointer(), ReadBarrier::GrayPtr());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001970 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001971 PushOntoMarkStack(ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001972 }
1973 }
1974 }
1975 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001976 return ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001977}
1978
1979void ConcurrentCopying::FinishPhase() {
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -08001980 Thread* const self = Thread::Current();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001981 {
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -08001982 MutexLock mu(self, mark_stack_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001983 CHECK_EQ(pooled_mark_stacks_.size(), kMarkStackPoolSize);
1984 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001985 region_space_ = nullptr;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001986 {
1987 MutexLock mu(Thread::Current(), skipped_blocks_lock_);
1988 skipped_blocks_map_.clear();
1989 }
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -08001990 ReaderMutexLock mu(self, *Locks::mutator_lock_);
1991 WriterMutexLock mu2(self, *Locks::heap_bitmap_lock_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001992 heap_->ClearMarkedObjects();
1993}
1994
Mathieu Chartier97509952015-07-13 14:35:43 -07001995bool ConcurrentCopying::IsMarkedHeapReference(mirror::HeapReference<mirror::Object>* field) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001996 mirror::Object* from_ref = field->AsMirrorPtr();
Mathieu Chartier97509952015-07-13 14:35:43 -07001997 mirror::Object* to_ref = IsMarked(from_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001998 if (to_ref == nullptr) {
1999 return false;
2000 }
2001 if (from_ref != to_ref) {
2002 QuasiAtomic::ThreadFenceRelease();
2003 field->Assign(to_ref);
2004 QuasiAtomic::ThreadFenceSequentiallyConsistent();
2005 }
2006 return true;
2007}
2008
Mathieu Chartier97509952015-07-13 14:35:43 -07002009mirror::Object* ConcurrentCopying::MarkObject(mirror::Object* from_ref) {
2010 return Mark(from_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002011}
2012
2013void ConcurrentCopying::DelayReferenceReferent(mirror::Class* klass, mirror::Reference* reference) {
Mathieu Chartier97509952015-07-13 14:35:43 -07002014 heap_->GetReferenceProcessor()->DelayReferenceReferent(klass, reference, this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002015}
2016
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002017void ConcurrentCopying::ProcessReferences(Thread* self) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002018 TimingLogger::ScopedTiming split("ProcessReferences", GetTimings());
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002019 // 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 -08002020 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
2021 GetHeap()->GetReferenceProcessor()->ProcessReferences(
Mathieu Chartier97509952015-07-13 14:35:43 -07002022 true /*concurrent*/, GetTimings(), GetCurrentIteration()->GetClearSoftReferences(), this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002023}
2024
2025void ConcurrentCopying::RevokeAllThreadLocalBuffers() {
2026 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
2027 region_space_->RevokeAllThreadLocalBuffers();
2028}
2029
Hiroshi Yamauchid5307ec2014-03-27 21:07:51 -07002030} // namespace collector
2031} // namespace gc
2032} // namespace art