blob: d7e8f81227befc1c1a990b51772e5087468f2286 [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"
26#include "gc/space/space.h"
27#include "intern_table.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070028#include "mirror/class-inl.h"
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080029#include "mirror/object-inl.h"
30#include "scoped_thread_state_change.h"
31#include "thread-inl.h"
32#include "thread_list.h"
33#include "well_known_classes.h"
34
Hiroshi Yamauchid5307ec2014-03-27 21:07:51 -070035namespace art {
36namespace gc {
37namespace collector {
38
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -070039static constexpr size_t kDefaultGcMarkStackSize = 2 * MB;
40
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080041ConcurrentCopying::ConcurrentCopying(Heap* heap, const std::string& name_prefix)
42 : GarbageCollector(heap,
43 name_prefix + (name_prefix.empty() ? "" : " ") +
44 "concurrent copying + mark sweep"),
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070045 region_space_(nullptr), gc_barrier_(new Barrier(0)),
46 gc_mark_stack_(accounting::ObjectStack::Create("concurrent copying gc mark stack",
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -070047 kDefaultGcMarkStackSize,
48 kDefaultGcMarkStackSize)),
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070049 mark_stack_lock_("concurrent copying mark stack lock", kMarkSweepMarkStackLock),
50 thread_running_gc_(nullptr),
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080051 is_marking_(false), is_active_(false), is_asserting_to_space_invariant_(false),
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070052 heap_mark_bitmap_(nullptr), live_stack_freeze_size_(0), mark_stack_mode_(kMarkStackModeOff),
53 weak_ref_access_enabled_(true),
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080054 skipped_blocks_lock_("concurrent copying bytes blocks lock", kMarkSweepMarkStackLock),
55 rb_table_(heap_->GetReadBarrierTable()),
56 force_evacuate_all_(false) {
57 static_assert(space::RegionSpace::kRegionSize == accounting::ReadBarrierTable::kRegionSize,
58 "The region space size and the read barrier table region size must match");
59 cc_heap_bitmap_.reset(new accounting::HeapBitmap(heap));
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070060 Thread* self = Thread::Current();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080061 {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080062 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
63 // Cache this so that we won't have to lock heap_bitmap_lock_ in
64 // Mark() which could cause a nested lock on heap_bitmap_lock_
65 // when GC causes a RB while doing GC or a lock order violation
66 // (class_linker_lock_ and heap_bitmap_lock_).
67 heap_mark_bitmap_ = heap->GetMarkBitmap();
68 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070069 {
70 MutexLock mu(self, mark_stack_lock_);
71 for (size_t i = 0; i < kMarkStackPoolSize; ++i) {
72 accounting::AtomicStack<mirror::Object>* mark_stack =
73 accounting::AtomicStack<mirror::Object>::Create(
74 "thread local mark stack", kMarkStackSize, kMarkStackSize);
75 pooled_mark_stacks_.push_back(mark_stack);
76 }
77 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080078}
79
Mathieu Chartierb19ccb12015-07-15 10:24:16 -070080void ConcurrentCopying::MarkHeapReference(mirror::HeapReference<mirror::Object>* from_ref) {
81 // Used for preserving soft references, should be OK to not have a CAS here since there should be
82 // no other threads which can trigger read barriers on the same referent during reference
83 // processing.
84 from_ref->Assign(Mark(from_ref->AsMirrorPtr()));
Mathieu Chartier81187812015-07-15 14:24:07 -070085 DCHECK(!from_ref->IsNull());
Mathieu Chartier97509952015-07-13 14:35:43 -070086}
87
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080088ConcurrentCopying::~ConcurrentCopying() {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070089 STLDeleteElements(&pooled_mark_stacks_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080090}
91
92void ConcurrentCopying::RunPhases() {
93 CHECK(kUseBakerReadBarrier || kUseTableLookupReadBarrier);
94 CHECK(!is_active_);
95 is_active_ = true;
96 Thread* self = Thread::Current();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070097 thread_running_gc_ = self;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080098 Locks::mutator_lock_->AssertNotHeld(self);
99 {
100 ReaderMutexLock mu(self, *Locks::mutator_lock_);
101 InitializePhase();
102 }
103 FlipThreadRoots();
104 {
105 ReaderMutexLock mu(self, *Locks::mutator_lock_);
106 MarkingPhase();
107 }
108 // Verify no from space refs. This causes a pause.
109 if (kEnableNoFromSpaceRefsVerification || kIsDebugBuild) {
110 TimingLogger::ScopedTiming split("(Paused)VerifyNoFromSpaceReferences", GetTimings());
111 ScopedPause pause(this);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700112 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800113 if (kVerboseMode) {
114 LOG(INFO) << "Verifying no from-space refs";
115 }
116 VerifyNoFromSpaceReferences();
Mathieu Chartier720e71a2015-04-06 17:10:58 -0700117 if (kVerboseMode) {
118 LOG(INFO) << "Done verifying no from-space refs";
119 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700120 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800121 }
122 {
123 ReaderMutexLock mu(self, *Locks::mutator_lock_);
124 ReclaimPhase();
125 }
126 FinishPhase();
127 CHECK(is_active_);
128 is_active_ = false;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700129 thread_running_gc_ = nullptr;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800130}
131
132void ConcurrentCopying::BindBitmaps() {
133 Thread* self = Thread::Current();
134 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
135 // Mark all of the spaces we never collect as immune.
136 for (const auto& space : heap_->GetContinuousSpaces()) {
137 if (space->GetGcRetentionPolicy() == space::kGcRetentionPolicyNeverCollect
138 || space->GetGcRetentionPolicy() == space::kGcRetentionPolicyFullCollect) {
139 CHECK(space->IsZygoteSpace() || space->IsImageSpace());
140 CHECK(immune_region_.AddContinuousSpace(space)) << "Failed to add space " << *space;
141 const char* bitmap_name = space->IsImageSpace() ? "cc image space bitmap" :
142 "cc zygote space bitmap";
143 // TODO: try avoiding using bitmaps for image/zygote to save space.
144 accounting::ContinuousSpaceBitmap* bitmap =
145 accounting::ContinuousSpaceBitmap::Create(bitmap_name, space->Begin(), space->Capacity());
146 cc_heap_bitmap_->AddContinuousSpaceBitmap(bitmap);
147 cc_bitmaps_.push_back(bitmap);
148 } else if (space == region_space_) {
149 accounting::ContinuousSpaceBitmap* bitmap =
150 accounting::ContinuousSpaceBitmap::Create("cc region space bitmap",
151 space->Begin(), space->Capacity());
152 cc_heap_bitmap_->AddContinuousSpaceBitmap(bitmap);
153 cc_bitmaps_.push_back(bitmap);
154 region_space_bitmap_ = bitmap;
155 }
156 }
157}
158
159void ConcurrentCopying::InitializePhase() {
160 TimingLogger::ScopedTiming split("InitializePhase", GetTimings());
161 if (kVerboseMode) {
162 LOG(INFO) << "GC InitializePhase";
163 LOG(INFO) << "Region-space : " << reinterpret_cast<void*>(region_space_->Begin()) << "-"
164 << reinterpret_cast<void*>(region_space_->Limit());
165 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700166 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800167 immune_region_.Reset();
168 bytes_moved_.StoreRelaxed(0);
169 objects_moved_.StoreRelaxed(0);
170 if (GetCurrentIteration()->GetGcCause() == kGcCauseExplicit ||
171 GetCurrentIteration()->GetGcCause() == kGcCauseForNativeAlloc ||
172 GetCurrentIteration()->GetClearSoftReferences()) {
173 force_evacuate_all_ = true;
174 } else {
175 force_evacuate_all_ = false;
176 }
177 BindBitmaps();
178 if (kVerboseMode) {
179 LOG(INFO) << "force_evacuate_all=" << force_evacuate_all_;
180 LOG(INFO) << "Immune region: " << immune_region_.Begin() << "-" << immune_region_.End();
181 LOG(INFO) << "GC end of InitializePhase";
182 }
183}
184
185// Used to switch the thread roots of a thread from from-space refs to to-space refs.
186class ThreadFlipVisitor : public Closure {
187 public:
Roland Levillain3887c462015-08-12 18:15:42 +0100188 ThreadFlipVisitor(ConcurrentCopying* concurrent_copying, bool use_tlab)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800189 : concurrent_copying_(concurrent_copying), use_tlab_(use_tlab) {
190 }
191
Mathieu Chartier90443472015-07-16 20:32:27 -0700192 virtual void Run(Thread* thread) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800193 // Note: self is not necessarily equal to thread since thread may be suspended.
194 Thread* self = Thread::Current();
195 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
196 << thread->GetState() << " thread " << thread << " self " << self;
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700197 thread->SetIsGcMarking(true);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800198 if (use_tlab_ && thread->HasTlab()) {
199 if (ConcurrentCopying::kEnableFromSpaceAccountingCheck) {
200 // This must come before the revoke.
201 size_t thread_local_objects = thread->GetThreadLocalObjectsAllocated();
202 concurrent_copying_->region_space_->RevokeThreadLocalBuffers(thread);
203 reinterpret_cast<Atomic<size_t>*>(&concurrent_copying_->from_space_num_objects_at_first_pause_)->
204 FetchAndAddSequentiallyConsistent(thread_local_objects);
205 } else {
206 concurrent_copying_->region_space_->RevokeThreadLocalBuffers(thread);
207 }
208 }
209 if (kUseThreadLocalAllocationStack) {
210 thread->RevokeThreadLocalAllocationStack();
211 }
212 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700213 thread->VisitRoots(concurrent_copying_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800214 concurrent_copying_->GetBarrier().Pass(self);
215 }
216
217 private:
218 ConcurrentCopying* const concurrent_copying_;
219 const bool use_tlab_;
220};
221
222// Called back from Runtime::FlipThreadRoots() during a pause.
223class FlipCallback : public Closure {
224 public:
225 explicit FlipCallback(ConcurrentCopying* concurrent_copying)
226 : concurrent_copying_(concurrent_copying) {
227 }
228
Mathieu Chartier90443472015-07-16 20:32:27 -0700229 virtual void Run(Thread* thread) OVERRIDE REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800230 ConcurrentCopying* cc = concurrent_copying_;
231 TimingLogger::ScopedTiming split("(Paused)FlipCallback", cc->GetTimings());
232 // Note: self is not necessarily equal to thread since thread may be suspended.
233 Thread* self = Thread::Current();
234 CHECK(thread == self);
235 Locks::mutator_lock_->AssertExclusiveHeld(self);
236 cc->region_space_->SetFromSpace(cc->rb_table_, cc->force_evacuate_all_);
Mathieu Chartiera4f6af92015-08-11 17:35:25 -0700237 cc->SwapStacks();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800238 if (ConcurrentCopying::kEnableFromSpaceAccountingCheck) {
239 cc->RecordLiveStackFreezeSize(self);
240 cc->from_space_num_objects_at_first_pause_ = cc->region_space_->GetObjectsAllocated();
241 cc->from_space_num_bytes_at_first_pause_ = cc->region_space_->GetBytesAllocated();
242 }
243 cc->is_marking_ = true;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700244 cc->mark_stack_mode_.StoreRelaxed(ConcurrentCopying::kMarkStackModeThreadLocal);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800245 if (UNLIKELY(Runtime::Current()->IsActiveTransaction())) {
Mathieu Chartier184c9dc2015-03-05 13:20:54 -0800246 CHECK(Runtime::Current()->IsAotCompiler());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800247 TimingLogger::ScopedTiming split2("(Paused)VisitTransactionRoots", cc->GetTimings());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700248 Runtime::Current()->VisitTransactionRoots(cc);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800249 }
250 }
251
252 private:
253 ConcurrentCopying* const concurrent_copying_;
254};
255
256// Switch threads that from from-space to to-space refs. Forward/mark the thread roots.
257void ConcurrentCopying::FlipThreadRoots() {
258 TimingLogger::ScopedTiming split("FlipThreadRoots", GetTimings());
259 if (kVerboseMode) {
260 LOG(INFO) << "time=" << region_space_->Time();
261 region_space_->DumpNonFreeRegions(LOG(INFO));
262 }
263 Thread* self = Thread::Current();
264 Locks::mutator_lock_->AssertNotHeld(self);
265 gc_barrier_->Init(self, 0);
266 ThreadFlipVisitor thread_flip_visitor(this, heap_->use_tlab_);
267 FlipCallback flip_callback(this);
Hiroshi Yamauchi76f55b02015-08-21 16:10:39 -0700268 heap_->ThreadFlipBegin(self); // Sync with JNI critical calls.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800269 size_t barrier_count = Runtime::Current()->FlipThreadRoots(
270 &thread_flip_visitor, &flip_callback, this);
Hiroshi Yamauchi76f55b02015-08-21 16:10:39 -0700271 heap_->ThreadFlipEnd(self);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800272 {
273 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
274 gc_barrier_->Increment(self, barrier_count);
275 }
276 is_asserting_to_space_invariant_ = true;
277 QuasiAtomic::ThreadFenceForConstructor();
278 if (kVerboseMode) {
279 LOG(INFO) << "time=" << region_space_->Time();
280 region_space_->DumpNonFreeRegions(LOG(INFO));
281 LOG(INFO) << "GC end of FlipThreadRoots";
282 }
283}
284
Mathieu Chartiera4f6af92015-08-11 17:35:25 -0700285void ConcurrentCopying::SwapStacks() {
286 heap_->SwapStacks();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800287}
288
289void ConcurrentCopying::RecordLiveStackFreezeSize(Thread* self) {
290 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
291 live_stack_freeze_size_ = heap_->GetLiveStack()->Size();
292}
293
294// Used to visit objects in the immune spaces.
295class ConcurrentCopyingImmuneSpaceObjVisitor {
296 public:
297 explicit ConcurrentCopyingImmuneSpaceObjVisitor(ConcurrentCopying* cc)
298 : collector_(cc) {}
299
Mathieu Chartier90443472015-07-16 20:32:27 -0700300 void operator()(mirror::Object* obj) const SHARED_REQUIRES(Locks::mutator_lock_)
301 SHARED_REQUIRES(Locks::heap_bitmap_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800302 DCHECK(obj != nullptr);
303 DCHECK(collector_->immune_region_.ContainsObject(obj));
304 accounting::ContinuousSpaceBitmap* cc_bitmap =
305 collector_->cc_heap_bitmap_->GetContinuousSpaceBitmap(obj);
306 DCHECK(cc_bitmap != nullptr)
307 << "An immune space object must have a bitmap";
308 if (kIsDebugBuild) {
309 DCHECK(collector_->heap_->GetMarkBitmap()->Test(obj))
310 << "Immune space object must be already marked";
311 }
312 // This may or may not succeed, which is ok.
313 if (kUseBakerReadBarrier) {
314 obj->AtomicSetReadBarrierPointer(ReadBarrier::WhitePtr(), ReadBarrier::GrayPtr());
315 }
316 if (cc_bitmap->AtomicTestAndSet(obj)) {
317 // Already marked. Do nothing.
318 } else {
319 // Newly marked. Set the gray bit and push it onto the mark stack.
320 CHECK(!kUseBakerReadBarrier || obj->GetReadBarrierPointer() == ReadBarrier::GrayPtr());
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700321 collector_->PushOntoMarkStack(obj);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800322 }
323 }
324
325 private:
Mathieu Chartier97509952015-07-13 14:35:43 -0700326 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800327};
328
329class EmptyCheckpoint : public Closure {
330 public:
331 explicit EmptyCheckpoint(ConcurrentCopying* concurrent_copying)
332 : concurrent_copying_(concurrent_copying) {
333 }
334
335 virtual void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
336 // Note: self is not necessarily equal to thread since thread may be suspended.
337 Thread* self = Thread::Current();
338 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
339 << thread->GetState() << " thread " << thread << " self " << self;
Lei Lidd9943d2015-02-02 14:24:44 +0800340 // If thread is a running mutator, then act on behalf of the garbage collector.
341 // See the code in ThreadList::RunCheckpoint.
Mathieu Chartier10d25082015-10-28 18:36:09 -0700342 concurrent_copying_->GetBarrier().Pass(self);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800343 }
344
345 private:
346 ConcurrentCopying* const concurrent_copying_;
347};
348
349// Concurrently mark roots that are guarded by read barriers and process the mark stack.
350void ConcurrentCopying::MarkingPhase() {
351 TimingLogger::ScopedTiming split("MarkingPhase", GetTimings());
352 if (kVerboseMode) {
353 LOG(INFO) << "GC MarkingPhase";
354 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700355 CHECK(weak_ref_access_enabled_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800356 {
357 // Mark the image root. The WB-based collectors do not need to
358 // scan the image objects from roots by relying on the card table,
359 // but it's necessary for the RB to-space invariant to hold.
360 TimingLogger::ScopedTiming split1("VisitImageRoots", GetTimings());
361 gc::space::ImageSpace* image = heap_->GetImageSpace();
362 if (image != nullptr) {
363 mirror::ObjectArray<mirror::Object>* image_root = image->GetImageHeader().GetImageRoots();
364 mirror::Object* marked_image_root = Mark(image_root);
365 CHECK_EQ(image_root, marked_image_root) << "An image object does not move";
366 if (ReadBarrier::kEnableToSpaceInvariantChecks) {
367 AssertToSpaceInvariant(nullptr, MemberOffset(0), marked_image_root);
368 }
369 }
370 }
Man Cao41656de2015-07-06 18:53:15 -0700371 // TODO: Other garbage collectors uses Runtime::VisitConcurrentRoots(), refactor this part
372 // to also use the same function.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800373 {
374 TimingLogger::ScopedTiming split2("VisitConstantRoots", GetTimings());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700375 Runtime::Current()->VisitConstantRoots(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800376 }
377 {
378 TimingLogger::ScopedTiming split3("VisitInternTableRoots", GetTimings());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700379 Runtime::Current()->GetInternTable()->VisitRoots(this, kVisitRootFlagAllRoots);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800380 }
381 {
382 TimingLogger::ScopedTiming split4("VisitClassLinkerRoots", GetTimings());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700383 Runtime::Current()->GetClassLinker()->VisitRoots(this, kVisitRootFlagAllRoots);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800384 }
385 {
386 // TODO: don't visit the transaction roots if it's not active.
387 TimingLogger::ScopedTiming split5("VisitNonThreadRoots", GetTimings());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700388 Runtime::Current()->VisitNonThreadRoots(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800389 }
Mathieu Chartiera6b1ead2015-10-06 10:32:38 -0700390 {
391 TimingLogger::ScopedTiming split6("Dbg::VisitRoots", GetTimings());
392 Dbg::VisitRoots(this);
393 }
Man Cao41656de2015-07-06 18:53:15 -0700394 Runtime::Current()->GetHeap()->VisitAllocationRecords(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800395
396 // Immune spaces.
397 for (auto& space : heap_->GetContinuousSpaces()) {
398 if (immune_region_.ContainsSpace(space)) {
399 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
400 accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
401 ConcurrentCopyingImmuneSpaceObjVisitor visitor(this);
402 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()),
403 reinterpret_cast<uintptr_t>(space->Limit()),
404 visitor);
405 }
406 }
407
408 Thread* self = Thread::Current();
409 {
Mathieu Chartiera6b1ead2015-10-06 10:32:38 -0700410 TimingLogger::ScopedTiming split7("ProcessMarkStack", GetTimings());
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700411 // We transition through three mark stack modes (thread-local, shared, GC-exclusive). The
412 // primary reasons are the fact that we need to use a checkpoint to process thread-local mark
413 // stacks, but after we disable weak refs accesses, we can't use a checkpoint due to a deadlock
414 // issue because running threads potentially blocking at WaitHoldingLocks, and that once we
415 // reach the point where we process weak references, we can avoid using a lock when accessing
416 // the GC mark stack, which makes mark stack processing more efficient.
417
418 // Process the mark stack once in the thread local stack mode. This marks most of the live
419 // objects, aside from weak ref accesses with read barriers (Reference::GetReferent() and system
420 // weaks) that may happen concurrently while we processing the mark stack and newly mark/gray
421 // objects and push refs on the mark stack.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800422 ProcessMarkStack();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700423 // Switch to the shared mark stack mode. That is, revoke and process thread-local mark stacks
424 // for the last time before transitioning to the shared mark stack mode, which would process new
425 // refs that may have been concurrently pushed onto the mark stack during the ProcessMarkStack()
426 // call above. At the same time, disable weak ref accesses using a per-thread flag. It's
427 // important to do these together in a single checkpoint so that we can ensure that mutators
428 // won't newly gray objects and push new refs onto the mark stack due to weak ref accesses and
429 // mutators safely transition to the shared mark stack mode (without leaving unprocessed refs on
430 // the thread-local mark stacks), without a race. This is why we use a thread-local weak ref
431 // access flag Thread::tls32_.weak_ref_access_enabled_ instead of the global ones.
432 SwitchToSharedMarkStackMode();
433 CHECK(!self->GetWeakRefAccessEnabled());
434 // Now that weak refs accesses are disabled, once we exhaust the shared mark stack again here
435 // (which may be non-empty if there were refs found on thread-local mark stacks during the above
436 // SwitchToSharedMarkStackMode() call), we won't have new refs to process, that is, mutators
437 // (via read barriers) have no way to produce any more refs to process. Marking converges once
438 // before we process weak refs below.
439 ProcessMarkStack();
440 CheckEmptyMarkStack();
441 // Switch to the GC exclusive mark stack mode so that we can process the mark stack without a
442 // lock from this point on.
443 SwitchToGcExclusiveMarkStackMode();
444 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800445 if (kVerboseMode) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800446 LOG(INFO) << "ProcessReferences";
447 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700448 // Process weak references. This may produce new refs to process and have them processed via
Mathieu Chartier97509952015-07-13 14:35:43 -0700449 // ProcessMarkStack (in the GC exclusive mark stack mode).
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700450 ProcessReferences(self);
451 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800452 if (kVerboseMode) {
453 LOG(INFO) << "SweepSystemWeaks";
454 }
455 SweepSystemWeaks(self);
456 if (kVerboseMode) {
457 LOG(INFO) << "SweepSystemWeaks done";
458 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700459 // Process the mark stack here one last time because the above SweepSystemWeaks() call may have
460 // marked some objects (strings alive) as hash_set::Erase() can call the hash function for
461 // arbitrary elements in the weak intern table in InternTable::Table::SweepWeaks().
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800462 ProcessMarkStack();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700463 CheckEmptyMarkStack();
464 // Re-enable weak ref accesses.
465 ReenableWeakRefAccess(self);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -0700466 // Free data for class loaders that we unloaded.
467 Runtime::Current()->GetClassLinker()->CleanupClassLoaders();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700468 // Marking is done. Disable marking.
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700469 DisableMarking();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700470 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800471 }
472
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700473 CHECK(weak_ref_access_enabled_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800474 if (kVerboseMode) {
475 LOG(INFO) << "GC end of MarkingPhase";
476 }
477}
478
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700479void ConcurrentCopying::ReenableWeakRefAccess(Thread* self) {
480 if (kVerboseMode) {
481 LOG(INFO) << "ReenableWeakRefAccess";
482 }
483 weak_ref_access_enabled_.StoreRelaxed(true); // This is for new threads.
484 QuasiAtomic::ThreadFenceForConstructor();
485 // Iterate all threads (don't need to or can't use a checkpoint) and re-enable weak ref access.
486 {
487 MutexLock mu(self, *Locks::thread_list_lock_);
488 std::list<Thread*> thread_list = Runtime::Current()->GetThreadList()->GetList();
489 for (Thread* thread : thread_list) {
490 thread->SetWeakRefAccessEnabled(true);
491 }
492 }
493 // Unblock blocking threads.
494 GetHeap()->GetReferenceProcessor()->BroadcastForSlowPath(self);
495 Runtime::Current()->BroadcastForNewSystemWeaks();
496}
497
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700498class DisableMarkingCheckpoint : public Closure {
499 public:
500 explicit DisableMarkingCheckpoint(ConcurrentCopying* concurrent_copying)
501 : concurrent_copying_(concurrent_copying) {
502 }
503
504 void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
505 // Note: self is not necessarily equal to thread since thread may be suspended.
506 Thread* self = Thread::Current();
507 DCHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
508 << thread->GetState() << " thread " << thread << " self " << self;
509 // Disable the thread-local is_gc_marking flag.
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -0700510 // Note a thread that has just started right before this checkpoint may have already this flag
511 // set to false, which is ok.
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700512 thread->SetIsGcMarking(false);
513 // If thread is a running mutator, then act on behalf of the garbage collector.
514 // See the code in ThreadList::RunCheckpoint.
Mathieu Chartier10d25082015-10-28 18:36:09 -0700515 concurrent_copying_->GetBarrier().Pass(self);
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700516 }
517
518 private:
519 ConcurrentCopying* const concurrent_copying_;
520};
521
522void ConcurrentCopying::IssueDisableMarkingCheckpoint() {
523 Thread* self = Thread::Current();
524 DisableMarkingCheckpoint check_point(this);
525 ThreadList* thread_list = Runtime::Current()->GetThreadList();
526 gc_barrier_->Init(self, 0);
527 size_t barrier_count = thread_list->RunCheckpoint(&check_point);
528 // If there are no threads to wait which implies that all the checkpoint functions are finished,
529 // then no need to release the mutator lock.
530 if (barrier_count == 0) {
531 return;
532 }
533 // Release locks then wait for all mutator threads to pass the barrier.
534 Locks::mutator_lock_->SharedUnlock(self);
535 {
536 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
537 gc_barrier_->Increment(self, barrier_count);
538 }
539 Locks::mutator_lock_->SharedLock(self);
540}
541
542void ConcurrentCopying::DisableMarking() {
543 // Change the global is_marking flag to false. Do a fence before doing a checkpoint to update the
544 // thread-local flags so that a new thread starting up will get the correct is_marking flag.
545 is_marking_ = false;
546 QuasiAtomic::ThreadFenceForConstructor();
547 // Use a checkpoint to turn off the thread-local is_gc_marking flags and to ensure no threads are
548 // still in the middle of a read barrier which may have a from-space ref cached in a local
549 // variable.
550 IssueDisableMarkingCheckpoint();
551 if (kUseTableLookupReadBarrier) {
552 heap_->rb_table_->ClearAll();
553 DCHECK(heap_->rb_table_->IsAllCleared());
554 }
555 is_mark_stack_push_disallowed_.StoreSequentiallyConsistent(1);
556 mark_stack_mode_.StoreSequentiallyConsistent(kMarkStackModeOff);
557}
558
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800559void ConcurrentCopying::IssueEmptyCheckpoint() {
560 Thread* self = Thread::Current();
561 EmptyCheckpoint check_point(this);
562 ThreadList* thread_list = Runtime::Current()->GetThreadList();
563 gc_barrier_->Init(self, 0);
564 size_t barrier_count = thread_list->RunCheckpoint(&check_point);
Lei Lidd9943d2015-02-02 14:24:44 +0800565 // If there are no threads to wait which implys that all the checkpoint functions are finished,
566 // then no need to release the mutator lock.
567 if (barrier_count == 0) {
568 return;
569 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800570 // Release locks then wait for all mutator threads to pass the barrier.
571 Locks::mutator_lock_->SharedUnlock(self);
572 {
573 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
574 gc_barrier_->Increment(self, barrier_count);
575 }
576 Locks::mutator_lock_->SharedLock(self);
577}
578
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -0700579void ConcurrentCopying::ExpandGcMarkStack() {
580 DCHECK(gc_mark_stack_->IsFull());
581 const size_t new_size = gc_mark_stack_->Capacity() * 2;
582 std::vector<StackReference<mirror::Object>> temp(gc_mark_stack_->Begin(),
583 gc_mark_stack_->End());
584 gc_mark_stack_->Resize(new_size);
585 for (auto& ref : temp) {
586 gc_mark_stack_->PushBack(ref.AsMirrorPtr());
587 }
588 DCHECK(!gc_mark_stack_->IsFull());
589}
590
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800591void ConcurrentCopying::PushOntoMarkStack(mirror::Object* to_ref) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700592 CHECK_EQ(is_mark_stack_push_disallowed_.LoadRelaxed(), 0)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800593 << " " << to_ref << " " << PrettyTypeOf(to_ref);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700594 Thread* self = Thread::Current(); // TODO: pass self as an argument from call sites?
595 CHECK(thread_running_gc_ != nullptr);
596 MarkStackMode mark_stack_mode = mark_stack_mode_.LoadRelaxed();
597 if (mark_stack_mode == kMarkStackModeThreadLocal) {
598 if (self == thread_running_gc_) {
599 // If GC-running thread, use the GC mark stack instead of a thread-local mark stack.
600 CHECK(self->GetThreadLocalMarkStack() == nullptr);
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -0700601 if (UNLIKELY(gc_mark_stack_->IsFull())) {
602 ExpandGcMarkStack();
603 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700604 gc_mark_stack_->PushBack(to_ref);
605 } else {
606 // Otherwise, use a thread-local mark stack.
607 accounting::AtomicStack<mirror::Object>* tl_mark_stack = self->GetThreadLocalMarkStack();
608 if (UNLIKELY(tl_mark_stack == nullptr || tl_mark_stack->IsFull())) {
609 MutexLock mu(self, mark_stack_lock_);
610 // Get a new thread local mark stack.
611 accounting::AtomicStack<mirror::Object>* new_tl_mark_stack;
612 if (!pooled_mark_stacks_.empty()) {
613 // Use a pooled mark stack.
614 new_tl_mark_stack = pooled_mark_stacks_.back();
615 pooled_mark_stacks_.pop_back();
616 } else {
617 // None pooled. Create a new one.
618 new_tl_mark_stack =
619 accounting::AtomicStack<mirror::Object>::Create(
620 "thread local mark stack", 4 * KB, 4 * KB);
621 }
622 DCHECK(new_tl_mark_stack != nullptr);
623 DCHECK(new_tl_mark_stack->IsEmpty());
624 new_tl_mark_stack->PushBack(to_ref);
625 self->SetThreadLocalMarkStack(new_tl_mark_stack);
626 if (tl_mark_stack != nullptr) {
627 // Store the old full stack into a vector.
628 revoked_mark_stacks_.push_back(tl_mark_stack);
629 }
630 } else {
631 tl_mark_stack->PushBack(to_ref);
632 }
633 }
634 } else if (mark_stack_mode == kMarkStackModeShared) {
635 // Access the shared GC mark stack with a lock.
636 MutexLock mu(self, mark_stack_lock_);
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -0700637 if (UNLIKELY(gc_mark_stack_->IsFull())) {
638 ExpandGcMarkStack();
639 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700640 gc_mark_stack_->PushBack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800641 } else {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700642 CHECK_EQ(static_cast<uint32_t>(mark_stack_mode),
Hiroshi Yamauchifa755182015-09-30 20:12:11 -0700643 static_cast<uint32_t>(kMarkStackModeGcExclusive))
644 << "ref=" << to_ref
645 << " self->gc_marking=" << self->GetIsGcMarking()
646 << " cc->is_marking=" << is_marking_;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700647 CHECK(self == thread_running_gc_)
648 << "Only GC-running thread should access the mark stack "
649 << "in the GC exclusive mark stack mode";
650 // Access the GC mark stack without a lock.
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -0700651 if (UNLIKELY(gc_mark_stack_->IsFull())) {
652 ExpandGcMarkStack();
653 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700654 gc_mark_stack_->PushBack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800655 }
656}
657
658accounting::ObjectStack* ConcurrentCopying::GetAllocationStack() {
659 return heap_->allocation_stack_.get();
660}
661
662accounting::ObjectStack* ConcurrentCopying::GetLiveStack() {
663 return heap_->live_stack_.get();
664}
665
666inline mirror::Object* ConcurrentCopying::GetFwdPtr(mirror::Object* from_ref) {
667 DCHECK(region_space_->IsInFromSpace(from_ref));
668 LockWord lw = from_ref->GetLockWord(false);
669 if (lw.GetState() == LockWord::kForwardingAddress) {
670 mirror::Object* fwd_ptr = reinterpret_cast<mirror::Object*>(lw.ForwardingAddress());
671 CHECK(fwd_ptr != nullptr);
672 return fwd_ptr;
673 } else {
674 return nullptr;
675 }
676}
677
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800678// The following visitors are that used to verify that there's no
679// references to the from-space left after marking.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700680class ConcurrentCopyingVerifyNoFromSpaceRefsVisitor : public SingleRootVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800681 public:
682 explicit ConcurrentCopyingVerifyNoFromSpaceRefsVisitor(ConcurrentCopying* collector)
683 : collector_(collector) {}
684
685 void operator()(mirror::Object* ref) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700686 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800687 if (ref == nullptr) {
688 // OK.
689 return;
690 }
691 collector_->AssertToSpaceInvariant(nullptr, MemberOffset(0), ref);
692 if (kUseBakerReadBarrier) {
693 if (collector_->RegionSpace()->IsInToSpace(ref)) {
694 CHECK(ref->GetReadBarrierPointer() == nullptr)
695 << "To-space ref " << ref << " " << PrettyTypeOf(ref)
696 << " has non-white rb_ptr " << ref->GetReadBarrierPointer();
697 } else {
698 CHECK(ref->GetReadBarrierPointer() == ReadBarrier::BlackPtr() ||
699 (ref->GetReadBarrierPointer() == ReadBarrier::WhitePtr() &&
700 collector_->IsOnAllocStack(ref)))
701 << "Non-moving/unevac from space ref " << ref << " " << PrettyTypeOf(ref)
702 << " has non-black rb_ptr " << ref->GetReadBarrierPointer()
703 << " but isn't on the alloc stack (and has white rb_ptr)."
704 << " Is it in the non-moving space="
705 << (collector_->GetHeap()->GetNonMovingSpace()->HasAddress(ref));
706 }
707 }
708 }
709
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700710 void VisitRoot(mirror::Object* root, const RootInfo& info ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -0700711 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800712 DCHECK(root != nullptr);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700713 operator()(root);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800714 }
715
716 private:
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700717 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800718};
719
720class ConcurrentCopyingVerifyNoFromSpaceRefsFieldVisitor {
721 public:
722 explicit ConcurrentCopyingVerifyNoFromSpaceRefsFieldVisitor(ConcurrentCopying* collector)
723 : collector_(collector) {}
724
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700725 void operator()(mirror::Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700726 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800727 mirror::Object* ref =
728 obj->GetFieldObject<mirror::Object, kDefaultVerifyFlags, kWithoutReadBarrier>(offset);
729 ConcurrentCopyingVerifyNoFromSpaceRefsVisitor visitor(collector_);
730 visitor(ref);
731 }
732 void operator()(mirror::Class* klass, mirror::Reference* ref) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700733 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800734 CHECK(klass->IsTypeOfReferenceClass());
735 this->operator()(ref, mirror::Reference::ReferentOffset(), false);
736 }
737
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700738 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
739 SHARED_REQUIRES(Locks::mutator_lock_) {
740 if (!root->IsNull()) {
741 VisitRoot(root);
742 }
743 }
744
745 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
746 SHARED_REQUIRES(Locks::mutator_lock_) {
747 ConcurrentCopyingVerifyNoFromSpaceRefsVisitor visitor(collector_);
748 visitor(root->AsMirrorPtr());
749 }
750
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800751 private:
Mathieu Chartier97509952015-07-13 14:35:43 -0700752 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800753};
754
755class ConcurrentCopyingVerifyNoFromSpaceRefsObjectVisitor {
756 public:
757 explicit ConcurrentCopyingVerifyNoFromSpaceRefsObjectVisitor(ConcurrentCopying* collector)
758 : collector_(collector) {}
759 void operator()(mirror::Object* obj) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700760 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800761 ObjectCallback(obj, collector_);
762 }
763 static void ObjectCallback(mirror::Object* obj, void *arg)
Mathieu Chartier90443472015-07-16 20:32:27 -0700764 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800765 CHECK(obj != nullptr);
766 ConcurrentCopying* collector = reinterpret_cast<ConcurrentCopying*>(arg);
767 space::RegionSpace* region_space = collector->RegionSpace();
768 CHECK(!region_space->IsInFromSpace(obj)) << "Scanning object " << obj << " in from space";
769 ConcurrentCopyingVerifyNoFromSpaceRefsFieldVisitor visitor(collector);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -0700770 obj->VisitReferences(visitor, visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800771 if (kUseBakerReadBarrier) {
772 if (collector->RegionSpace()->IsInToSpace(obj)) {
773 CHECK(obj->GetReadBarrierPointer() == nullptr)
774 << "obj=" << obj << " non-white rb_ptr " << obj->GetReadBarrierPointer();
775 } else {
776 CHECK(obj->GetReadBarrierPointer() == ReadBarrier::BlackPtr() ||
777 (obj->GetReadBarrierPointer() == ReadBarrier::WhitePtr() &&
778 collector->IsOnAllocStack(obj)))
779 << "Non-moving space/unevac from space ref " << obj << " " << PrettyTypeOf(obj)
780 << " has non-black rb_ptr " << obj->GetReadBarrierPointer()
781 << " but isn't on the alloc stack (and has white rb_ptr). Is it in the non-moving space="
782 << (collector->GetHeap()->GetNonMovingSpace()->HasAddress(obj));
783 }
784 }
785 }
786
787 private:
788 ConcurrentCopying* const collector_;
789};
790
791// Verify there's no from-space references left after the marking phase.
792void ConcurrentCopying::VerifyNoFromSpaceReferences() {
793 Thread* self = Thread::Current();
794 DCHECK(Locks::mutator_lock_->IsExclusiveHeld(self));
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700795 // Verify all threads have is_gc_marking to be false
796 {
797 MutexLock mu(self, *Locks::thread_list_lock_);
798 std::list<Thread*> thread_list = Runtime::Current()->GetThreadList()->GetList();
799 for (Thread* thread : thread_list) {
800 CHECK(!thread->GetIsGcMarking());
801 }
802 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800803 ConcurrentCopyingVerifyNoFromSpaceRefsObjectVisitor visitor(this);
804 // Roots.
805 {
806 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700807 ConcurrentCopyingVerifyNoFromSpaceRefsVisitor ref_visitor(this);
808 Runtime::Current()->VisitRoots(&ref_visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800809 }
810 // The to-space.
811 region_space_->WalkToSpace(ConcurrentCopyingVerifyNoFromSpaceRefsObjectVisitor::ObjectCallback,
812 this);
813 // Non-moving spaces.
814 {
815 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
816 heap_->GetMarkBitmap()->Visit(visitor);
817 }
818 // The alloc stack.
819 {
820 ConcurrentCopyingVerifyNoFromSpaceRefsVisitor ref_visitor(this);
Mathieu Chartiercb535da2015-01-23 13:50:03 -0800821 for (auto* it = heap_->allocation_stack_->Begin(), *end = heap_->allocation_stack_->End();
822 it < end; ++it) {
823 mirror::Object* const obj = it->AsMirrorPtr();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800824 if (obj != nullptr && obj->GetClass() != nullptr) {
825 // TODO: need to call this only if obj is alive?
826 ref_visitor(obj);
827 visitor(obj);
828 }
829 }
830 }
831 // TODO: LOS. But only refs in LOS are classes.
832}
833
834// The following visitors are used to assert the to-space invariant.
835class ConcurrentCopyingAssertToSpaceInvariantRefsVisitor {
836 public:
837 explicit ConcurrentCopyingAssertToSpaceInvariantRefsVisitor(ConcurrentCopying* collector)
838 : collector_(collector) {}
839
840 void operator()(mirror::Object* ref) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700841 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800842 if (ref == nullptr) {
843 // OK.
844 return;
845 }
846 collector_->AssertToSpaceInvariant(nullptr, MemberOffset(0), ref);
847 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800848
849 private:
Mathieu Chartier97509952015-07-13 14:35:43 -0700850 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800851};
852
853class ConcurrentCopyingAssertToSpaceInvariantFieldVisitor {
854 public:
855 explicit ConcurrentCopyingAssertToSpaceInvariantFieldVisitor(ConcurrentCopying* collector)
856 : collector_(collector) {}
857
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700858 void operator()(mirror::Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700859 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800860 mirror::Object* ref =
861 obj->GetFieldObject<mirror::Object, kDefaultVerifyFlags, kWithoutReadBarrier>(offset);
862 ConcurrentCopyingAssertToSpaceInvariantRefsVisitor visitor(collector_);
863 visitor(ref);
864 }
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700865 void operator()(mirror::Class* klass, mirror::Reference* ref ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700866 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800867 CHECK(klass->IsTypeOfReferenceClass());
868 }
869
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700870 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
871 SHARED_REQUIRES(Locks::mutator_lock_) {
872 if (!root->IsNull()) {
873 VisitRoot(root);
874 }
875 }
876
877 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
878 SHARED_REQUIRES(Locks::mutator_lock_) {
879 ConcurrentCopyingAssertToSpaceInvariantRefsVisitor visitor(collector_);
880 visitor(root->AsMirrorPtr());
881 }
882
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800883 private:
Mathieu Chartier97509952015-07-13 14:35:43 -0700884 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800885};
886
887class ConcurrentCopyingAssertToSpaceInvariantObjectVisitor {
888 public:
889 explicit ConcurrentCopyingAssertToSpaceInvariantObjectVisitor(ConcurrentCopying* collector)
890 : collector_(collector) {}
891 void operator()(mirror::Object* obj) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700892 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800893 ObjectCallback(obj, collector_);
894 }
895 static void ObjectCallback(mirror::Object* obj, void *arg)
Mathieu Chartier90443472015-07-16 20:32:27 -0700896 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800897 CHECK(obj != nullptr);
898 ConcurrentCopying* collector = reinterpret_cast<ConcurrentCopying*>(arg);
899 space::RegionSpace* region_space = collector->RegionSpace();
900 CHECK(!region_space->IsInFromSpace(obj)) << "Scanning object " << obj << " in from space";
901 collector->AssertToSpaceInvariant(nullptr, MemberOffset(0), obj);
902 ConcurrentCopyingAssertToSpaceInvariantFieldVisitor visitor(collector);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -0700903 obj->VisitReferences(visitor, visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800904 }
905
906 private:
Mathieu Chartier97509952015-07-13 14:35:43 -0700907 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800908};
909
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700910class RevokeThreadLocalMarkStackCheckpoint : public Closure {
911 public:
Roland Levillain3887c462015-08-12 18:15:42 +0100912 RevokeThreadLocalMarkStackCheckpoint(ConcurrentCopying* concurrent_copying,
913 bool disable_weak_ref_access)
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700914 : concurrent_copying_(concurrent_copying),
915 disable_weak_ref_access_(disable_weak_ref_access) {
916 }
917
918 virtual void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
919 // Note: self is not necessarily equal to thread since thread may be suspended.
920 Thread* self = Thread::Current();
921 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
922 << thread->GetState() << " thread " << thread << " self " << self;
923 // Revoke thread local mark stacks.
924 accounting::AtomicStack<mirror::Object>* tl_mark_stack = thread->GetThreadLocalMarkStack();
925 if (tl_mark_stack != nullptr) {
926 MutexLock mu(self, concurrent_copying_->mark_stack_lock_);
927 concurrent_copying_->revoked_mark_stacks_.push_back(tl_mark_stack);
928 thread->SetThreadLocalMarkStack(nullptr);
929 }
930 // Disable weak ref access.
931 if (disable_weak_ref_access_) {
932 thread->SetWeakRefAccessEnabled(false);
933 }
934 // If thread is a running mutator, then act on behalf of the garbage collector.
935 // See the code in ThreadList::RunCheckpoint.
Mathieu Chartier10d25082015-10-28 18:36:09 -0700936 concurrent_copying_->GetBarrier().Pass(self);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700937 }
938
939 private:
940 ConcurrentCopying* const concurrent_copying_;
941 const bool disable_weak_ref_access_;
942};
943
944void ConcurrentCopying::RevokeThreadLocalMarkStacks(bool disable_weak_ref_access) {
945 Thread* self = Thread::Current();
946 RevokeThreadLocalMarkStackCheckpoint check_point(this, disable_weak_ref_access);
947 ThreadList* thread_list = Runtime::Current()->GetThreadList();
948 gc_barrier_->Init(self, 0);
949 size_t barrier_count = thread_list->RunCheckpoint(&check_point);
950 // If there are no threads to wait which implys that all the checkpoint functions are finished,
951 // then no need to release the mutator lock.
952 if (barrier_count == 0) {
953 return;
954 }
955 Locks::mutator_lock_->SharedUnlock(self);
956 {
957 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
958 gc_barrier_->Increment(self, barrier_count);
959 }
960 Locks::mutator_lock_->SharedLock(self);
961}
962
963void ConcurrentCopying::RevokeThreadLocalMarkStack(Thread* thread) {
964 Thread* self = Thread::Current();
965 CHECK_EQ(self, thread);
966 accounting::AtomicStack<mirror::Object>* tl_mark_stack = thread->GetThreadLocalMarkStack();
967 if (tl_mark_stack != nullptr) {
968 CHECK(is_marking_);
969 MutexLock mu(self, mark_stack_lock_);
970 revoked_mark_stacks_.push_back(tl_mark_stack);
971 thread->SetThreadLocalMarkStack(nullptr);
972 }
973}
974
975void ConcurrentCopying::ProcessMarkStack() {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800976 if (kVerboseMode) {
977 LOG(INFO) << "ProcessMarkStack. ";
978 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700979 bool empty_prev = false;
980 while (true) {
981 bool empty = ProcessMarkStackOnce();
982 if (empty_prev && empty) {
983 // Saw empty mark stack for a second time, done.
984 break;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800985 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700986 empty_prev = empty;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800987 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700988}
989
990bool ConcurrentCopying::ProcessMarkStackOnce() {
991 Thread* self = Thread::Current();
992 CHECK(thread_running_gc_ != nullptr);
993 CHECK(self == thread_running_gc_);
994 CHECK(self->GetThreadLocalMarkStack() == nullptr);
995 size_t count = 0;
996 MarkStackMode mark_stack_mode = mark_stack_mode_.LoadRelaxed();
997 if (mark_stack_mode == kMarkStackModeThreadLocal) {
998 // Process the thread-local mark stacks and the GC mark stack.
999 count += ProcessThreadLocalMarkStacks(false);
1000 while (!gc_mark_stack_->IsEmpty()) {
1001 mirror::Object* to_ref = gc_mark_stack_->PopBack();
1002 ProcessMarkStackRef(to_ref);
1003 ++count;
1004 }
1005 gc_mark_stack_->Reset();
1006 } else if (mark_stack_mode == kMarkStackModeShared) {
1007 // Process the shared GC mark stack with a lock.
1008 {
1009 MutexLock mu(self, mark_stack_lock_);
1010 CHECK(revoked_mark_stacks_.empty());
1011 }
1012 while (true) {
1013 std::vector<mirror::Object*> refs;
1014 {
1015 // Copy refs with lock. Note the number of refs should be small.
1016 MutexLock mu(self, mark_stack_lock_);
1017 if (gc_mark_stack_->IsEmpty()) {
1018 break;
1019 }
1020 for (StackReference<mirror::Object>* p = gc_mark_stack_->Begin();
1021 p != gc_mark_stack_->End(); ++p) {
1022 refs.push_back(p->AsMirrorPtr());
1023 }
1024 gc_mark_stack_->Reset();
1025 }
1026 for (mirror::Object* ref : refs) {
1027 ProcessMarkStackRef(ref);
1028 ++count;
1029 }
1030 }
1031 } else {
1032 CHECK_EQ(static_cast<uint32_t>(mark_stack_mode),
1033 static_cast<uint32_t>(kMarkStackModeGcExclusive));
1034 {
1035 MutexLock mu(self, mark_stack_lock_);
1036 CHECK(revoked_mark_stacks_.empty());
1037 }
1038 // Process the GC mark stack in the exclusive mode. No need to take the lock.
1039 while (!gc_mark_stack_->IsEmpty()) {
1040 mirror::Object* to_ref = gc_mark_stack_->PopBack();
1041 ProcessMarkStackRef(to_ref);
1042 ++count;
1043 }
1044 gc_mark_stack_->Reset();
1045 }
1046
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001047 // Return true if the stack was empty.
1048 return count == 0;
1049}
1050
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001051size_t ConcurrentCopying::ProcessThreadLocalMarkStacks(bool disable_weak_ref_access) {
1052 // Run a checkpoint to collect all thread local mark stacks and iterate over them all.
1053 RevokeThreadLocalMarkStacks(disable_weak_ref_access);
1054 size_t count = 0;
1055 std::vector<accounting::AtomicStack<mirror::Object>*> mark_stacks;
1056 {
1057 MutexLock mu(Thread::Current(), mark_stack_lock_);
1058 // Make a copy of the mark stack vector.
1059 mark_stacks = revoked_mark_stacks_;
1060 revoked_mark_stacks_.clear();
1061 }
1062 for (accounting::AtomicStack<mirror::Object>* mark_stack : mark_stacks) {
1063 for (StackReference<mirror::Object>* p = mark_stack->Begin(); p != mark_stack->End(); ++p) {
1064 mirror::Object* to_ref = p->AsMirrorPtr();
1065 ProcessMarkStackRef(to_ref);
1066 ++count;
1067 }
1068 {
1069 MutexLock mu(Thread::Current(), mark_stack_lock_);
1070 if (pooled_mark_stacks_.size() >= kMarkStackPoolSize) {
1071 // The pool has enough. Delete it.
1072 delete mark_stack;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001073 } else {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001074 // Otherwise, put it into the pool for later reuse.
1075 mark_stack->Reset();
1076 pooled_mark_stacks_.push_back(mark_stack);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001077 }
1078 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001079 }
1080 return count;
1081}
1082
1083void ConcurrentCopying::ProcessMarkStackRef(mirror::Object* to_ref) {
1084 DCHECK(!region_space_->IsInFromSpace(to_ref));
1085 if (kUseBakerReadBarrier) {
1086 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr())
1087 << " " << to_ref << " " << to_ref->GetReadBarrierPointer()
1088 << " is_marked=" << IsMarked(to_ref);
1089 }
1090 // Scan ref fields.
1091 Scan(to_ref);
1092 // Mark the gray ref as white or black.
1093 if (kUseBakerReadBarrier) {
1094 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr())
1095 << " " << to_ref << " " << to_ref->GetReadBarrierPointer()
1096 << " is_marked=" << IsMarked(to_ref);
1097 }
1098 if (to_ref->GetClass<kVerifyNone, kWithoutReadBarrier>()->IsTypeOfReferenceClass() &&
1099 to_ref->AsReference()->GetReferent<kWithoutReadBarrier>() != nullptr &&
1100 !IsInToSpace(to_ref->AsReference()->GetReferent<kWithoutReadBarrier>())) {
Hiroshi Yamauchi70c08d32015-09-10 16:01:30 -07001101 // Leave this Reference gray in the queue so that GetReferent() will trigger a read barrier. We
1102 // will change it to black or white later in ReferenceQueue::DequeuePendingReference().
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001103 CHECK(to_ref->AsReference()->IsEnqueued()) << "Left unenqueued ref gray " << to_ref;
1104 } else {
Hiroshi Yamauchi70c08d32015-09-10 16:01:30 -07001105 // We may occasionally leave a Reference black or white in the queue if its referent happens to
1106 // be concurrently marked after the Scan() call above has enqueued the Reference, in which case
1107 // the above IsInToSpace() evaluates to true and we change the color from gray to black or white
1108 // here in this else block.
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001109#ifdef USE_BAKER_OR_BROOKS_READ_BARRIER
1110 if (kUseBakerReadBarrier) {
1111 if (region_space_->IsInToSpace(to_ref)) {
1112 // If to-space, change from gray to white.
1113 bool success = to_ref->AtomicSetReadBarrierPointer(ReadBarrier::GrayPtr(),
1114 ReadBarrier::WhitePtr());
1115 CHECK(success) << "Must succeed as we won the race.";
1116 CHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::WhitePtr());
1117 } else {
1118 // If non-moving space/unevac from space, change from gray
1119 // to black. We can't change gray to white because it's not
1120 // safe to use CAS if two threads change values in opposite
1121 // directions (A->B and B->A). So, we change it to black to
1122 // indicate non-moving objects that have been marked
1123 // through. Note we'd need to change from black to white
1124 // later (concurrently).
1125 bool success = to_ref->AtomicSetReadBarrierPointer(ReadBarrier::GrayPtr(),
1126 ReadBarrier::BlackPtr());
1127 CHECK(success) << "Must succeed as we won the race.";
1128 CHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::BlackPtr());
1129 }
1130 }
1131#else
1132 DCHECK(!kUseBakerReadBarrier);
1133#endif
1134 }
1135 if (ReadBarrier::kEnableToSpaceInvariantChecks || kIsDebugBuild) {
1136 ConcurrentCopyingAssertToSpaceInvariantObjectVisitor visitor(this);
1137 visitor(to_ref);
1138 }
1139}
1140
1141void ConcurrentCopying::SwitchToSharedMarkStackMode() {
1142 Thread* self = Thread::Current();
1143 CHECK(thread_running_gc_ != nullptr);
1144 CHECK_EQ(self, thread_running_gc_);
1145 CHECK(self->GetThreadLocalMarkStack() == nullptr);
1146 MarkStackMode before_mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1147 CHECK_EQ(static_cast<uint32_t>(before_mark_stack_mode),
1148 static_cast<uint32_t>(kMarkStackModeThreadLocal));
1149 mark_stack_mode_.StoreRelaxed(kMarkStackModeShared);
1150 CHECK(weak_ref_access_enabled_.LoadRelaxed());
1151 weak_ref_access_enabled_.StoreRelaxed(false);
1152 QuasiAtomic::ThreadFenceForConstructor();
1153 // Process the thread local mark stacks one last time after switching to the shared mark stack
1154 // mode and disable weak ref accesses.
1155 ProcessThreadLocalMarkStacks(true);
1156 if (kVerboseMode) {
1157 LOG(INFO) << "Switched to shared mark stack mode and disabled weak ref access";
1158 }
1159}
1160
1161void ConcurrentCopying::SwitchToGcExclusiveMarkStackMode() {
1162 Thread* self = Thread::Current();
1163 CHECK(thread_running_gc_ != nullptr);
1164 CHECK_EQ(self, thread_running_gc_);
1165 CHECK(self->GetThreadLocalMarkStack() == nullptr);
1166 MarkStackMode before_mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1167 CHECK_EQ(static_cast<uint32_t>(before_mark_stack_mode),
1168 static_cast<uint32_t>(kMarkStackModeShared));
1169 mark_stack_mode_.StoreRelaxed(kMarkStackModeGcExclusive);
1170 QuasiAtomic::ThreadFenceForConstructor();
1171 if (kVerboseMode) {
1172 LOG(INFO) << "Switched to GC exclusive mark stack mode";
1173 }
1174}
1175
1176void ConcurrentCopying::CheckEmptyMarkStack() {
1177 Thread* self = Thread::Current();
1178 CHECK(thread_running_gc_ != nullptr);
1179 CHECK_EQ(self, thread_running_gc_);
1180 CHECK(self->GetThreadLocalMarkStack() == nullptr);
1181 MarkStackMode mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1182 if (mark_stack_mode == kMarkStackModeThreadLocal) {
1183 // Thread-local mark stack mode.
1184 RevokeThreadLocalMarkStacks(false);
1185 MutexLock mu(Thread::Current(), mark_stack_lock_);
1186 if (!revoked_mark_stacks_.empty()) {
1187 for (accounting::AtomicStack<mirror::Object>* mark_stack : revoked_mark_stacks_) {
1188 while (!mark_stack->IsEmpty()) {
1189 mirror::Object* obj = mark_stack->PopBack();
1190 if (kUseBakerReadBarrier) {
1191 mirror::Object* rb_ptr = obj->GetReadBarrierPointer();
1192 LOG(INFO) << "On mark queue : " << obj << " " << PrettyTypeOf(obj) << " rb_ptr=" << rb_ptr
1193 << " is_marked=" << IsMarked(obj);
1194 } else {
1195 LOG(INFO) << "On mark queue : " << obj << " " << PrettyTypeOf(obj)
1196 << " is_marked=" << IsMarked(obj);
1197 }
1198 }
1199 }
1200 LOG(FATAL) << "mark stack is not empty";
1201 }
1202 } else {
1203 // Shared, GC-exclusive, or off.
1204 MutexLock mu(Thread::Current(), mark_stack_lock_);
1205 CHECK(gc_mark_stack_->IsEmpty());
1206 CHECK(revoked_mark_stacks_.empty());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001207 }
1208}
1209
1210void ConcurrentCopying::SweepSystemWeaks(Thread* self) {
1211 TimingLogger::ScopedTiming split("SweepSystemWeaks", GetTimings());
1212 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier97509952015-07-13 14:35:43 -07001213 Runtime::Current()->SweepSystemWeaks(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001214}
1215
1216void ConcurrentCopying::Sweep(bool swap_bitmaps) {
1217 {
1218 TimingLogger::ScopedTiming t("MarkStackAsLive", GetTimings());
1219 accounting::ObjectStack* live_stack = heap_->GetLiveStack();
1220 if (kEnableFromSpaceAccountingCheck) {
1221 CHECK_GE(live_stack_freeze_size_, live_stack->Size());
1222 }
1223 heap_->MarkAllocStackAsLive(live_stack);
1224 live_stack->Reset();
1225 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001226 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001227 TimingLogger::ScopedTiming split("Sweep", GetTimings());
1228 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
1229 if (space->IsContinuousMemMapAllocSpace()) {
1230 space::ContinuousMemMapAllocSpace* alloc_space = space->AsContinuousMemMapAllocSpace();
1231 if (space == region_space_ || immune_region_.ContainsSpace(space)) {
1232 continue;
1233 }
1234 TimingLogger::ScopedTiming split2(
1235 alloc_space->IsZygoteSpace() ? "SweepZygoteSpace" : "SweepAllocSpace", GetTimings());
1236 RecordFree(alloc_space->Sweep(swap_bitmaps));
1237 }
1238 }
1239 SweepLargeObjects(swap_bitmaps);
1240}
1241
1242void ConcurrentCopying::SweepLargeObjects(bool swap_bitmaps) {
1243 TimingLogger::ScopedTiming split("SweepLargeObjects", GetTimings());
1244 RecordFreeLOS(heap_->GetLargeObjectsSpace()->Sweep(swap_bitmaps));
1245}
1246
1247class ConcurrentCopyingClearBlackPtrsVisitor {
1248 public:
1249 explicit ConcurrentCopyingClearBlackPtrsVisitor(ConcurrentCopying* cc)
1250 : collector_(cc) {}
Andreas Gampe65b798e2015-04-06 09:35:22 -07001251#ifndef USE_BAKER_OR_BROOKS_READ_BARRIER
1252 NO_RETURN
1253#endif
Mathieu Chartier90443472015-07-16 20:32:27 -07001254 void operator()(mirror::Object* obj) const SHARED_REQUIRES(Locks::mutator_lock_)
1255 SHARED_REQUIRES(Locks::heap_bitmap_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001256 DCHECK(obj != nullptr);
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08001257 DCHECK(collector_->heap_->GetMarkBitmap()->Test(obj)) << obj;
1258 DCHECK_EQ(obj->GetReadBarrierPointer(), ReadBarrier::BlackPtr()) << obj;
Hiroshi Yamauchi60f63f52015-04-23 16:12:40 -07001259 obj->AtomicSetReadBarrierPointer(ReadBarrier::BlackPtr(), ReadBarrier::WhitePtr());
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08001260 DCHECK_EQ(obj->GetReadBarrierPointer(), ReadBarrier::WhitePtr()) << obj;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001261 }
1262
1263 private:
1264 ConcurrentCopying* const collector_;
1265};
1266
1267// Clear the black ptrs in non-moving objects back to white.
1268void ConcurrentCopying::ClearBlackPtrs() {
1269 CHECK(kUseBakerReadBarrier);
1270 TimingLogger::ScopedTiming split("ClearBlackPtrs", GetTimings());
1271 ConcurrentCopyingClearBlackPtrsVisitor visitor(this);
1272 for (auto& space : heap_->GetContinuousSpaces()) {
1273 if (space == region_space_) {
1274 continue;
1275 }
1276 accounting::ContinuousSpaceBitmap* mark_bitmap = space->GetMarkBitmap();
1277 if (kVerboseMode) {
1278 LOG(INFO) << "ClearBlackPtrs: " << *space << " bitmap: " << *mark_bitmap;
1279 }
1280 mark_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()),
1281 reinterpret_cast<uintptr_t>(space->Limit()),
1282 visitor);
1283 }
1284 space::LargeObjectSpace* large_object_space = heap_->GetLargeObjectsSpace();
1285 large_object_space->GetMarkBitmap()->VisitMarkedRange(
1286 reinterpret_cast<uintptr_t>(large_object_space->Begin()),
1287 reinterpret_cast<uintptr_t>(large_object_space->End()),
1288 visitor);
1289 // Objects on the allocation stack?
1290 if (ReadBarrier::kEnableReadBarrierInvariantChecks || kIsDebugBuild) {
1291 size_t count = GetAllocationStack()->Size();
Mathieu Chartiercb535da2015-01-23 13:50:03 -08001292 auto* it = GetAllocationStack()->Begin();
1293 auto* end = GetAllocationStack()->End();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001294 for (size_t i = 0; i < count; ++i, ++it) {
Mathieu Chartiercb535da2015-01-23 13:50:03 -08001295 CHECK_LT(it, end);
1296 mirror::Object* obj = it->AsMirrorPtr();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001297 if (obj != nullptr) {
1298 // Must have been cleared above.
Mathieu Chartiercb535da2015-01-23 13:50:03 -08001299 CHECK_EQ(obj->GetReadBarrierPointer(), ReadBarrier::WhitePtr()) << obj;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001300 }
1301 }
1302 }
1303}
1304
1305void ConcurrentCopying::ReclaimPhase() {
1306 TimingLogger::ScopedTiming split("ReclaimPhase", GetTimings());
1307 if (kVerboseMode) {
1308 LOG(INFO) << "GC ReclaimPhase";
1309 }
1310 Thread* self = Thread::Current();
1311
1312 {
1313 // Double-check that the mark stack is empty.
1314 // Note: need to set this after VerifyNoFromSpaceRef().
1315 is_asserting_to_space_invariant_ = false;
1316 QuasiAtomic::ThreadFenceForConstructor();
1317 if (kVerboseMode) {
1318 LOG(INFO) << "Issue an empty check point. ";
1319 }
1320 IssueEmptyCheckpoint();
1321 // Disable the check.
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001322 is_mark_stack_push_disallowed_.StoreSequentiallyConsistent(0);
1323 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001324 }
1325
1326 {
1327 // Record freed objects.
1328 TimingLogger::ScopedTiming split2("RecordFree", GetTimings());
1329 // Don't include thread-locals that are in the to-space.
1330 uint64_t from_bytes = region_space_->GetBytesAllocatedInFromSpace();
1331 uint64_t from_objects = region_space_->GetObjectsAllocatedInFromSpace();
1332 uint64_t unevac_from_bytes = region_space_->GetBytesAllocatedInUnevacFromSpace();
1333 uint64_t unevac_from_objects = region_space_->GetObjectsAllocatedInUnevacFromSpace();
1334 uint64_t to_bytes = bytes_moved_.LoadSequentiallyConsistent();
1335 uint64_t to_objects = objects_moved_.LoadSequentiallyConsistent();
1336 if (kEnableFromSpaceAccountingCheck) {
1337 CHECK_EQ(from_space_num_objects_at_first_pause_, from_objects + unevac_from_objects);
1338 CHECK_EQ(from_space_num_bytes_at_first_pause_, from_bytes + unevac_from_bytes);
1339 }
1340 CHECK_LE(to_objects, from_objects);
1341 CHECK_LE(to_bytes, from_bytes);
1342 int64_t freed_bytes = from_bytes - to_bytes;
1343 int64_t freed_objects = from_objects - to_objects;
1344 if (kVerboseMode) {
1345 LOG(INFO) << "RecordFree:"
1346 << " from_bytes=" << from_bytes << " from_objects=" << from_objects
1347 << " unevac_from_bytes=" << unevac_from_bytes << " unevac_from_objects=" << unevac_from_objects
1348 << " to_bytes=" << to_bytes << " to_objects=" << to_objects
1349 << " freed_bytes=" << freed_bytes << " freed_objects=" << freed_objects
1350 << " from_space size=" << region_space_->FromSpaceSize()
1351 << " unevac_from_space size=" << region_space_->UnevacFromSpaceSize()
1352 << " to_space size=" << region_space_->ToSpaceSize();
1353 LOG(INFO) << "(before) num_bytes_allocated=" << heap_->num_bytes_allocated_.LoadSequentiallyConsistent();
1354 }
1355 RecordFree(ObjectBytePair(freed_objects, freed_bytes));
1356 if (kVerboseMode) {
1357 LOG(INFO) << "(after) num_bytes_allocated=" << heap_->num_bytes_allocated_.LoadSequentiallyConsistent();
1358 }
1359 }
1360
1361 {
1362 TimingLogger::ScopedTiming split3("ComputeUnevacFromSpaceLiveRatio", GetTimings());
1363 ComputeUnevacFromSpaceLiveRatio();
1364 }
1365
1366 {
1367 TimingLogger::ScopedTiming split4("ClearFromSpace", GetTimings());
1368 region_space_->ClearFromSpace();
1369 }
1370
1371 {
1372 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1373 if (kUseBakerReadBarrier) {
1374 ClearBlackPtrs();
1375 }
1376 Sweep(false);
1377 SwapBitmaps();
1378 heap_->UnBindBitmaps();
1379
1380 // Remove bitmaps for the immune spaces.
1381 while (!cc_bitmaps_.empty()) {
1382 accounting::ContinuousSpaceBitmap* cc_bitmap = cc_bitmaps_.back();
1383 cc_heap_bitmap_->RemoveContinuousSpaceBitmap(cc_bitmap);
1384 delete cc_bitmap;
1385 cc_bitmaps_.pop_back();
1386 }
1387 region_space_bitmap_ = nullptr;
1388 }
1389
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001390 CheckEmptyMarkStack();
1391
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001392 if (kVerboseMode) {
1393 LOG(INFO) << "GC end of ReclaimPhase";
1394 }
1395}
1396
1397class ConcurrentCopyingComputeUnevacFromSpaceLiveRatioVisitor {
1398 public:
1399 explicit ConcurrentCopyingComputeUnevacFromSpaceLiveRatioVisitor(ConcurrentCopying* cc)
1400 : collector_(cc) {}
Mathieu Chartier90443472015-07-16 20:32:27 -07001401 void operator()(mirror::Object* ref) const SHARED_REQUIRES(Locks::mutator_lock_)
1402 SHARED_REQUIRES(Locks::heap_bitmap_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001403 DCHECK(ref != nullptr);
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08001404 DCHECK(collector_->region_space_bitmap_->Test(ref)) << ref;
1405 DCHECK(collector_->region_space_->IsInUnevacFromSpace(ref)) << ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001406 if (kUseBakerReadBarrier) {
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08001407 DCHECK_EQ(ref->GetReadBarrierPointer(), ReadBarrier::BlackPtr()) << ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001408 // Clear the black ptr.
Hiroshi Yamauchi60f63f52015-04-23 16:12:40 -07001409 ref->AtomicSetReadBarrierPointer(ReadBarrier::BlackPtr(), ReadBarrier::WhitePtr());
1410 DCHECK_EQ(ref->GetReadBarrierPointer(), ReadBarrier::WhitePtr()) << ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001411 }
1412 size_t obj_size = ref->SizeOf();
1413 size_t alloc_size = RoundUp(obj_size, space::RegionSpace::kAlignment);
1414 collector_->region_space_->AddLiveBytes(ref, alloc_size);
1415 }
1416
1417 private:
Mathieu Chartier97509952015-07-13 14:35:43 -07001418 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001419};
1420
1421// Compute how much live objects are left in regions.
1422void ConcurrentCopying::ComputeUnevacFromSpaceLiveRatio() {
1423 region_space_->AssertAllRegionLiveBytesZeroOrCleared();
1424 ConcurrentCopyingComputeUnevacFromSpaceLiveRatioVisitor visitor(this);
1425 region_space_bitmap_->VisitMarkedRange(reinterpret_cast<uintptr_t>(region_space_->Begin()),
1426 reinterpret_cast<uintptr_t>(region_space_->Limit()),
1427 visitor);
1428}
1429
1430// Assert the to-space invariant.
1431void ConcurrentCopying::AssertToSpaceInvariant(mirror::Object* obj, MemberOffset offset,
1432 mirror::Object* ref) {
1433 CHECK(heap_->collector_type_ == kCollectorTypeCC) << static_cast<size_t>(heap_->collector_type_);
1434 if (is_asserting_to_space_invariant_) {
1435 if (region_space_->IsInToSpace(ref)) {
1436 // OK.
1437 return;
1438 } else if (region_space_->IsInUnevacFromSpace(ref)) {
1439 CHECK(region_space_bitmap_->Test(ref)) << ref;
1440 } else if (region_space_->IsInFromSpace(ref)) {
1441 // Not OK. Do extra logging.
1442 if (obj != nullptr) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001443 LogFromSpaceRefHolder(obj, offset);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001444 }
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001445 ref->GetLockWord(false).Dump(LOG(INTERNAL_FATAL));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001446 CHECK(false) << "Found from-space ref " << ref << " " << PrettyTypeOf(ref);
1447 } else {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001448 AssertToSpaceInvariantInNonMovingSpace(obj, ref);
1449 }
1450 }
1451}
1452
1453class RootPrinter {
1454 public:
1455 RootPrinter() { }
1456
1457 template <class MirrorType>
1458 ALWAYS_INLINE void VisitRootIfNonNull(mirror::CompressedReference<MirrorType>* root)
Mathieu Chartier90443472015-07-16 20:32:27 -07001459 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001460 if (!root->IsNull()) {
1461 VisitRoot(root);
1462 }
1463 }
1464
1465 template <class MirrorType>
1466 void VisitRoot(mirror::Object** root)
Mathieu Chartier90443472015-07-16 20:32:27 -07001467 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001468 LOG(INTERNAL_FATAL) << "root=" << root << " ref=" << *root;
1469 }
1470
1471 template <class MirrorType>
1472 void VisitRoot(mirror::CompressedReference<MirrorType>* root)
Mathieu Chartier90443472015-07-16 20:32:27 -07001473 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001474 LOG(INTERNAL_FATAL) << "root=" << root << " ref=" << root->AsMirrorPtr();
1475 }
1476};
1477
1478void ConcurrentCopying::AssertToSpaceInvariant(GcRootSource* gc_root_source,
1479 mirror::Object* ref) {
1480 CHECK(heap_->collector_type_ == kCollectorTypeCC) << static_cast<size_t>(heap_->collector_type_);
1481 if (is_asserting_to_space_invariant_) {
1482 if (region_space_->IsInToSpace(ref)) {
1483 // OK.
1484 return;
1485 } else if (region_space_->IsInUnevacFromSpace(ref)) {
1486 CHECK(region_space_bitmap_->Test(ref)) << ref;
1487 } else if (region_space_->IsInFromSpace(ref)) {
1488 // Not OK. Do extra logging.
1489 if (gc_root_source == nullptr) {
1490 // No info.
1491 } else if (gc_root_source->HasArtField()) {
1492 ArtField* field = gc_root_source->GetArtField();
1493 LOG(INTERNAL_FATAL) << "gc root in field " << field << " " << PrettyField(field);
1494 RootPrinter root_printer;
1495 field->VisitRoots(root_printer);
1496 } else if (gc_root_source->HasArtMethod()) {
1497 ArtMethod* method = gc_root_source->GetArtMethod();
1498 LOG(INTERNAL_FATAL) << "gc root in method " << method << " " << PrettyMethod(method);
1499 RootPrinter root_printer;
Mathieu Chartier1147b9b2015-09-14 18:50:08 -07001500 method->VisitRoots(root_printer, sizeof(void*));
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001501 }
1502 ref->GetLockWord(false).Dump(LOG(INTERNAL_FATAL));
1503 region_space_->DumpNonFreeRegions(LOG(INTERNAL_FATAL));
1504 PrintFileToLog("/proc/self/maps", LogSeverity::INTERNAL_FATAL);
1505 MemMap::DumpMaps(LOG(INTERNAL_FATAL), true);
1506 CHECK(false) << "Found from-space ref " << ref << " " << PrettyTypeOf(ref);
1507 } else {
1508 AssertToSpaceInvariantInNonMovingSpace(nullptr, ref);
1509 }
1510 }
1511}
1512
1513void ConcurrentCopying::LogFromSpaceRefHolder(mirror::Object* obj, MemberOffset offset) {
1514 if (kUseBakerReadBarrier) {
1515 LOG(INFO) << "holder=" << obj << " " << PrettyTypeOf(obj)
1516 << " holder rb_ptr=" << obj->GetReadBarrierPointer();
1517 } else {
1518 LOG(INFO) << "holder=" << obj << " " << PrettyTypeOf(obj);
1519 }
1520 if (region_space_->IsInFromSpace(obj)) {
1521 LOG(INFO) << "holder is in the from-space.";
1522 } else if (region_space_->IsInToSpace(obj)) {
1523 LOG(INFO) << "holder is in the to-space.";
1524 } else if (region_space_->IsInUnevacFromSpace(obj)) {
1525 LOG(INFO) << "holder is in the unevac from-space.";
1526 if (region_space_bitmap_->Test(obj)) {
1527 LOG(INFO) << "holder is marked in the region space bitmap.";
1528 } else {
1529 LOG(INFO) << "holder is not marked in the region space bitmap.";
1530 }
1531 } else {
1532 // In a non-moving space.
1533 if (immune_region_.ContainsObject(obj)) {
1534 LOG(INFO) << "holder is in the image or the zygote space.";
1535 accounting::ContinuousSpaceBitmap* cc_bitmap =
1536 cc_heap_bitmap_->GetContinuousSpaceBitmap(obj);
1537 CHECK(cc_bitmap != nullptr)
1538 << "An immune space object must have a bitmap.";
1539 if (cc_bitmap->Test(obj)) {
1540 LOG(INFO) << "holder is marked in the bit map.";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001541 } else {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001542 LOG(INFO) << "holder is NOT marked in the bit map.";
1543 }
1544 } else {
1545 LOG(INFO) << "holder is in a non-moving (or main) space.";
1546 accounting::ContinuousSpaceBitmap* mark_bitmap =
1547 heap_mark_bitmap_->GetContinuousSpaceBitmap(obj);
1548 accounting::LargeObjectBitmap* los_bitmap =
1549 heap_mark_bitmap_->GetLargeObjectBitmap(obj);
1550 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
1551 bool is_los = mark_bitmap == nullptr;
1552 if (!is_los && mark_bitmap->Test(obj)) {
1553 LOG(INFO) << "holder is marked in the mark bit map.";
1554 } else if (is_los && los_bitmap->Test(obj)) {
1555 LOG(INFO) << "holder is marked in the los bit map.";
1556 } else {
1557 // If ref is on the allocation stack, then it is considered
1558 // mark/alive (but not necessarily on the live stack.)
1559 if (IsOnAllocStack(obj)) {
1560 LOG(INFO) << "holder is on the alloc stack.";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001561 } else {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001562 LOG(INFO) << "holder is not marked or on the alloc stack.";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001563 }
1564 }
1565 }
1566 }
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001567 LOG(INFO) << "offset=" << offset.SizeValue();
1568}
1569
1570void ConcurrentCopying::AssertToSpaceInvariantInNonMovingSpace(mirror::Object* obj,
1571 mirror::Object* ref) {
1572 // In a non-moving spaces. Check that the ref is marked.
1573 if (immune_region_.ContainsObject(ref)) {
1574 accounting::ContinuousSpaceBitmap* cc_bitmap =
1575 cc_heap_bitmap_->GetContinuousSpaceBitmap(ref);
1576 CHECK(cc_bitmap != nullptr)
1577 << "An immune space ref must have a bitmap. " << ref;
1578 if (kUseBakerReadBarrier) {
1579 CHECK(cc_bitmap->Test(ref))
1580 << "Unmarked immune space ref. obj=" << obj << " rb_ptr="
1581 << obj->GetReadBarrierPointer() << " ref=" << ref;
1582 } else {
1583 CHECK(cc_bitmap->Test(ref))
1584 << "Unmarked immune space ref. obj=" << obj << " ref=" << ref;
1585 }
1586 } else {
1587 accounting::ContinuousSpaceBitmap* mark_bitmap =
1588 heap_mark_bitmap_->GetContinuousSpaceBitmap(ref);
1589 accounting::LargeObjectBitmap* los_bitmap =
1590 heap_mark_bitmap_->GetLargeObjectBitmap(ref);
1591 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
1592 bool is_los = mark_bitmap == nullptr;
1593 if ((!is_los && mark_bitmap->Test(ref)) ||
1594 (is_los && los_bitmap->Test(ref))) {
1595 // OK.
1596 } else {
1597 // If ref is on the allocation stack, then it may not be
1598 // marked live, but considered marked/alive (but not
1599 // necessarily on the live stack).
1600 CHECK(IsOnAllocStack(ref)) << "Unmarked ref that's not on the allocation stack. "
1601 << "obj=" << obj << " ref=" << ref;
1602 }
1603 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001604}
1605
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001606// Used to scan ref fields of an object.
1607class ConcurrentCopyingRefFieldsVisitor {
1608 public:
1609 explicit ConcurrentCopyingRefFieldsVisitor(ConcurrentCopying* collector)
1610 : collector_(collector) {}
1611
1612 void operator()(mirror::Object* obj, MemberOffset offset, bool /* is_static */)
Mathieu Chartier90443472015-07-16 20:32:27 -07001613 const ALWAYS_INLINE SHARED_REQUIRES(Locks::mutator_lock_)
1614 SHARED_REQUIRES(Locks::heap_bitmap_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001615 collector_->Process(obj, offset);
1616 }
1617
1618 void operator()(mirror::Class* klass, mirror::Reference* ref) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001619 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001620 CHECK(klass->IsTypeOfReferenceClass());
1621 collector_->DelayReferenceReferent(klass, ref);
1622 }
1623
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001624 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
1625 SHARED_REQUIRES(Locks::mutator_lock_) {
1626 if (!root->IsNull()) {
1627 VisitRoot(root);
1628 }
1629 }
1630
1631 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
1632 SHARED_REQUIRES(Locks::mutator_lock_) {
1633 collector_->MarkRoot(root);
1634 }
1635
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001636 private:
1637 ConcurrentCopying* const collector_;
1638};
1639
1640// Scan ref fields of an object.
1641void ConcurrentCopying::Scan(mirror::Object* to_ref) {
1642 DCHECK(!region_space_->IsInFromSpace(to_ref));
1643 ConcurrentCopyingRefFieldsVisitor visitor(this);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07001644 to_ref->VisitReferences(visitor, visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001645}
1646
1647// Process a field.
1648inline void ConcurrentCopying::Process(mirror::Object* obj, MemberOffset offset) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001649 mirror::Object* ref = obj->GetFieldObject<
1650 mirror::Object, kVerifyNone, kWithoutReadBarrier, false>(offset);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001651 if (ref == nullptr || region_space_->IsInToSpace(ref)) {
1652 return;
1653 }
1654 mirror::Object* to_ref = Mark(ref);
1655 if (to_ref == ref) {
1656 return;
1657 }
1658 // This may fail if the mutator writes to the field at the same time. But it's ok.
1659 mirror::Object* expected_ref = ref;
1660 mirror::Object* new_ref = to_ref;
1661 do {
1662 if (expected_ref !=
1663 obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier, false>(offset)) {
1664 // It was updated by the mutator.
1665 break;
1666 }
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001667 } while (!obj->CasFieldWeakSequentiallyConsistentObjectWithoutWriteBarrier<
1668 false, false, kVerifyNone>(offset, expected_ref, new_ref));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001669}
1670
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001671// Process some roots.
1672void ConcurrentCopying::VisitRoots(
1673 mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED) {
1674 for (size_t i = 0; i < count; ++i) {
1675 mirror::Object** root = roots[i];
1676 mirror::Object* ref = *root;
1677 if (ref == nullptr || region_space_->IsInToSpace(ref)) {
Mathieu Chartier4809d0a2015-04-07 10:39:04 -07001678 continue;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001679 }
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001680 mirror::Object* to_ref = Mark(ref);
1681 if (to_ref == ref) {
Mathieu Chartier4809d0a2015-04-07 10:39:04 -07001682 continue;
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001683 }
1684 Atomic<mirror::Object*>* addr = reinterpret_cast<Atomic<mirror::Object*>*>(root);
1685 mirror::Object* expected_ref = ref;
1686 mirror::Object* new_ref = to_ref;
1687 do {
1688 if (expected_ref != addr->LoadRelaxed()) {
1689 // It was updated by the mutator.
1690 break;
1691 }
1692 } while (!addr->CompareExchangeWeakSequentiallyConsistent(expected_ref, new_ref));
1693 }
1694}
1695
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001696void ConcurrentCopying::MarkRoot(mirror::CompressedReference<mirror::Object>* root) {
1697 DCHECK(!root->IsNull());
1698 mirror::Object* const ref = root->AsMirrorPtr();
1699 if (region_space_->IsInToSpace(ref)) {
1700 return;
1701 }
1702 mirror::Object* to_ref = Mark(ref);
1703 if (to_ref != ref) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001704 auto* addr = reinterpret_cast<Atomic<mirror::CompressedReference<mirror::Object>>*>(root);
1705 auto expected_ref = mirror::CompressedReference<mirror::Object>::FromMirrorPtr(ref);
1706 auto new_ref = mirror::CompressedReference<mirror::Object>::FromMirrorPtr(to_ref);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001707 // If the cas fails, then it was updated by the mutator.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001708 do {
1709 if (ref != addr->LoadRelaxed().AsMirrorPtr()) {
1710 // It was updated by the mutator.
1711 break;
1712 }
1713 } while (!addr->CompareExchangeWeakSequentiallyConsistent(expected_ref, new_ref));
1714 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001715}
1716
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001717void ConcurrentCopying::VisitRoots(
1718 mirror::CompressedReference<mirror::Object>** roots, size_t count,
1719 const RootInfo& info ATTRIBUTE_UNUSED) {
1720 for (size_t i = 0; i < count; ++i) {
1721 mirror::CompressedReference<mirror::Object>* const root = roots[i];
1722 if (!root->IsNull()) {
1723 MarkRoot(root);
1724 }
1725 }
1726}
1727
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001728// Fill the given memory block with a dummy object. Used to fill in a
1729// copy of objects that was lost in race.
1730void ConcurrentCopying::FillWithDummyObject(mirror::Object* dummy_obj, size_t byte_size) {
Roland Levillain14d90572015-07-16 10:52:26 +01001731 CHECK_ALIGNED(byte_size, kObjectAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001732 memset(dummy_obj, 0, byte_size);
1733 mirror::Class* int_array_class = mirror::IntArray::GetArrayClass();
1734 CHECK(int_array_class != nullptr);
1735 AssertToSpaceInvariant(nullptr, MemberOffset(0), int_array_class);
1736 size_t component_size = int_array_class->GetComponentSize();
1737 CHECK_EQ(component_size, sizeof(int32_t));
1738 size_t data_offset = mirror::Array::DataOffset(component_size).SizeValue();
1739 if (data_offset > byte_size) {
1740 // An int array is too big. Use java.lang.Object.
1741 mirror::Class* java_lang_Object = WellKnownClasses::ToClass(WellKnownClasses::java_lang_Object);
1742 AssertToSpaceInvariant(nullptr, MemberOffset(0), java_lang_Object);
1743 CHECK_EQ(byte_size, java_lang_Object->GetObjectSize());
1744 dummy_obj->SetClass(java_lang_Object);
1745 CHECK_EQ(byte_size, dummy_obj->SizeOf());
1746 } else {
1747 // Use an int array.
1748 dummy_obj->SetClass(int_array_class);
1749 CHECK(dummy_obj->IsArrayInstance());
1750 int32_t length = (byte_size - data_offset) / component_size;
1751 dummy_obj->AsArray()->SetLength(length);
1752 CHECK_EQ(dummy_obj->AsArray()->GetLength(), length)
1753 << "byte_size=" << byte_size << " length=" << length
1754 << " component_size=" << component_size << " data_offset=" << data_offset;
1755 CHECK_EQ(byte_size, dummy_obj->SizeOf())
1756 << "byte_size=" << byte_size << " length=" << length
1757 << " component_size=" << component_size << " data_offset=" << data_offset;
1758 }
1759}
1760
1761// Reuse the memory blocks that were copy of objects that were lost in race.
1762mirror::Object* ConcurrentCopying::AllocateInSkippedBlock(size_t alloc_size) {
1763 // Try to reuse the blocks that were unused due to CAS failures.
Roland Levillain14d90572015-07-16 10:52:26 +01001764 CHECK_ALIGNED(alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001765 Thread* self = Thread::Current();
1766 size_t min_object_size = RoundUp(sizeof(mirror::Object), space::RegionSpace::kAlignment);
1767 MutexLock mu(self, skipped_blocks_lock_);
1768 auto it = skipped_blocks_map_.lower_bound(alloc_size);
1769 if (it == skipped_blocks_map_.end()) {
1770 // Not found.
1771 return nullptr;
1772 }
1773 {
1774 size_t byte_size = it->first;
1775 CHECK_GE(byte_size, alloc_size);
1776 if (byte_size > alloc_size && byte_size - alloc_size < min_object_size) {
1777 // If remainder would be too small for a dummy object, retry with a larger request size.
1778 it = skipped_blocks_map_.lower_bound(alloc_size + min_object_size);
1779 if (it == skipped_blocks_map_.end()) {
1780 // Not found.
1781 return nullptr;
1782 }
Roland Levillain14d90572015-07-16 10:52:26 +01001783 CHECK_ALIGNED(it->first - alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001784 CHECK_GE(it->first - alloc_size, min_object_size)
1785 << "byte_size=" << byte_size << " it->first=" << it->first << " alloc_size=" << alloc_size;
1786 }
1787 }
1788 // Found a block.
1789 CHECK(it != skipped_blocks_map_.end());
1790 size_t byte_size = it->first;
1791 uint8_t* addr = it->second;
1792 CHECK_GE(byte_size, alloc_size);
1793 CHECK(region_space_->IsInToSpace(reinterpret_cast<mirror::Object*>(addr)));
Roland Levillain14d90572015-07-16 10:52:26 +01001794 CHECK_ALIGNED(byte_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001795 if (kVerboseMode) {
1796 LOG(INFO) << "Reusing skipped bytes : " << reinterpret_cast<void*>(addr) << ", " << byte_size;
1797 }
1798 skipped_blocks_map_.erase(it);
1799 memset(addr, 0, byte_size);
1800 if (byte_size > alloc_size) {
1801 // Return the remainder to the map.
Roland Levillain14d90572015-07-16 10:52:26 +01001802 CHECK_ALIGNED(byte_size - alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001803 CHECK_GE(byte_size - alloc_size, min_object_size);
1804 FillWithDummyObject(reinterpret_cast<mirror::Object*>(addr + alloc_size),
1805 byte_size - alloc_size);
1806 CHECK(region_space_->IsInToSpace(reinterpret_cast<mirror::Object*>(addr + alloc_size)));
1807 skipped_blocks_map_.insert(std::make_pair(byte_size - alloc_size, addr + alloc_size));
1808 }
1809 return reinterpret_cast<mirror::Object*>(addr);
1810}
1811
1812mirror::Object* ConcurrentCopying::Copy(mirror::Object* from_ref) {
1813 DCHECK(region_space_->IsInFromSpace(from_ref));
1814 // No read barrier to avoid nested RB that might violate the to-space
1815 // invariant. Note that from_ref is a from space ref so the SizeOf()
1816 // call will access the from-space meta objects, but it's ok and necessary.
1817 size_t obj_size = from_ref->SizeOf<kDefaultVerifyFlags, kWithoutReadBarrier>();
1818 size_t region_space_alloc_size = RoundUp(obj_size, space::RegionSpace::kAlignment);
1819 size_t region_space_bytes_allocated = 0U;
1820 size_t non_moving_space_bytes_allocated = 0U;
1821 size_t bytes_allocated = 0U;
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001822 size_t dummy;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001823 mirror::Object* to_ref = region_space_->AllocNonvirtual<true>(
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001824 region_space_alloc_size, &region_space_bytes_allocated, nullptr, &dummy);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001825 bytes_allocated = region_space_bytes_allocated;
1826 if (to_ref != nullptr) {
1827 DCHECK_EQ(region_space_alloc_size, region_space_bytes_allocated);
1828 }
1829 bool fall_back_to_non_moving = false;
1830 if (UNLIKELY(to_ref == nullptr)) {
1831 // Failed to allocate in the region space. Try the skipped blocks.
1832 to_ref = AllocateInSkippedBlock(region_space_alloc_size);
1833 if (to_ref != nullptr) {
1834 // Succeeded to allocate in a skipped block.
1835 if (heap_->use_tlab_) {
1836 // This is necessary for the tlab case as it's not accounted in the space.
1837 region_space_->RecordAlloc(to_ref);
1838 }
1839 bytes_allocated = region_space_alloc_size;
1840 } else {
1841 // Fall back to the non-moving space.
1842 fall_back_to_non_moving = true;
1843 if (kVerboseMode) {
1844 LOG(INFO) << "Out of memory in the to-space. Fall back to non-moving. skipped_bytes="
1845 << to_space_bytes_skipped_.LoadSequentiallyConsistent()
1846 << " skipped_objects=" << to_space_objects_skipped_.LoadSequentiallyConsistent();
1847 }
1848 fall_back_to_non_moving = true;
1849 to_ref = heap_->non_moving_space_->Alloc(Thread::Current(), obj_size,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001850 &non_moving_space_bytes_allocated, nullptr, &dummy);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001851 CHECK(to_ref != nullptr) << "Fall-back non-moving space allocation failed";
1852 bytes_allocated = non_moving_space_bytes_allocated;
1853 // Mark it in the mark bitmap.
1854 accounting::ContinuousSpaceBitmap* mark_bitmap =
1855 heap_mark_bitmap_->GetContinuousSpaceBitmap(to_ref);
1856 CHECK(mark_bitmap != nullptr);
1857 CHECK(!mark_bitmap->AtomicTestAndSet(to_ref));
1858 }
1859 }
1860 DCHECK(to_ref != nullptr);
1861
1862 // Attempt to install the forward pointer. This is in a loop as the
1863 // lock word atomic write can fail.
1864 while (true) {
1865 // Copy the object. TODO: copy only the lockword in the second iteration and on?
1866 memcpy(to_ref, from_ref, obj_size);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001867
1868 LockWord old_lock_word = to_ref->GetLockWord(false);
1869
1870 if (old_lock_word.GetState() == LockWord::kForwardingAddress) {
1871 // Lost the race. Another thread (either GC or mutator) stored
1872 // the forwarding pointer first. Make the lost copy (to_ref)
1873 // look like a valid but dead (dummy) object and keep it for
1874 // future reuse.
1875 FillWithDummyObject(to_ref, bytes_allocated);
1876 if (!fall_back_to_non_moving) {
1877 DCHECK(region_space_->IsInToSpace(to_ref));
1878 if (bytes_allocated > space::RegionSpace::kRegionSize) {
1879 // Free the large alloc.
1880 region_space_->FreeLarge(to_ref, bytes_allocated);
1881 } else {
1882 // Record the lost copy for later reuse.
1883 heap_->num_bytes_allocated_.FetchAndAddSequentiallyConsistent(bytes_allocated);
1884 to_space_bytes_skipped_.FetchAndAddSequentiallyConsistent(bytes_allocated);
1885 to_space_objects_skipped_.FetchAndAddSequentiallyConsistent(1);
1886 MutexLock mu(Thread::Current(), skipped_blocks_lock_);
1887 skipped_blocks_map_.insert(std::make_pair(bytes_allocated,
1888 reinterpret_cast<uint8_t*>(to_ref)));
1889 }
1890 } else {
1891 DCHECK(heap_->non_moving_space_->HasAddress(to_ref));
1892 DCHECK_EQ(bytes_allocated, non_moving_space_bytes_allocated);
1893 // Free the non-moving-space chunk.
1894 accounting::ContinuousSpaceBitmap* mark_bitmap =
1895 heap_mark_bitmap_->GetContinuousSpaceBitmap(to_ref);
1896 CHECK(mark_bitmap != nullptr);
1897 CHECK(mark_bitmap->Clear(to_ref));
1898 heap_->non_moving_space_->Free(Thread::Current(), to_ref);
1899 }
1900
1901 // Get the winner's forward ptr.
1902 mirror::Object* lost_fwd_ptr = to_ref;
1903 to_ref = reinterpret_cast<mirror::Object*>(old_lock_word.ForwardingAddress());
1904 CHECK(to_ref != nullptr);
1905 CHECK_NE(to_ref, lost_fwd_ptr);
1906 CHECK(region_space_->IsInToSpace(to_ref) || heap_->non_moving_space_->HasAddress(to_ref));
1907 CHECK_NE(to_ref->GetLockWord(false).GetState(), LockWord::kForwardingAddress);
1908 return to_ref;
1909 }
1910
Hiroshi Yamauchi60f63f52015-04-23 16:12:40 -07001911 // Set the gray ptr.
1912 if (kUseBakerReadBarrier) {
1913 to_ref->SetReadBarrierPointer(ReadBarrier::GrayPtr());
1914 }
1915
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001916 LockWord new_lock_word = LockWord::FromForwardingAddress(reinterpret_cast<size_t>(to_ref));
1917
1918 // Try to atomically write the fwd ptr.
1919 bool success = from_ref->CasLockWordWeakSequentiallyConsistent(old_lock_word, new_lock_word);
1920 if (LIKELY(success)) {
1921 // The CAS succeeded.
1922 objects_moved_.FetchAndAddSequentiallyConsistent(1);
1923 bytes_moved_.FetchAndAddSequentiallyConsistent(region_space_alloc_size);
1924 if (LIKELY(!fall_back_to_non_moving)) {
1925 DCHECK(region_space_->IsInToSpace(to_ref));
1926 } else {
1927 DCHECK(heap_->non_moving_space_->HasAddress(to_ref));
1928 DCHECK_EQ(bytes_allocated, non_moving_space_bytes_allocated);
1929 }
1930 if (kUseBakerReadBarrier) {
1931 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr());
1932 }
1933 DCHECK(GetFwdPtr(from_ref) == to_ref);
1934 CHECK_NE(to_ref->GetLockWord(false).GetState(), LockWord::kForwardingAddress);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001935 PushOntoMarkStack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001936 return to_ref;
1937 } else {
1938 // The CAS failed. It may have lost the race or may have failed
1939 // due to monitor/hashcode ops. Either way, retry.
1940 }
1941 }
1942}
1943
1944mirror::Object* ConcurrentCopying::IsMarked(mirror::Object* from_ref) {
1945 DCHECK(from_ref != nullptr);
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08001946 space::RegionSpace::RegionType rtype = region_space_->GetRegionType(from_ref);
1947 if (rtype == space::RegionSpace::RegionType::kRegionTypeToSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001948 // It's already marked.
1949 return from_ref;
1950 }
1951 mirror::Object* to_ref;
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08001952 if (rtype == space::RegionSpace::RegionType::kRegionTypeFromSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001953 to_ref = GetFwdPtr(from_ref);
1954 DCHECK(to_ref == nullptr || region_space_->IsInToSpace(to_ref) ||
1955 heap_->non_moving_space_->HasAddress(to_ref))
1956 << "from_ref=" << from_ref << " to_ref=" << to_ref;
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08001957 } else if (rtype == space::RegionSpace::RegionType::kRegionTypeUnevacFromSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001958 if (region_space_bitmap_->Test(from_ref)) {
1959 to_ref = from_ref;
1960 } else {
1961 to_ref = nullptr;
1962 }
1963 } else {
1964 // from_ref is in a non-moving space.
1965 if (immune_region_.ContainsObject(from_ref)) {
1966 accounting::ContinuousSpaceBitmap* cc_bitmap =
1967 cc_heap_bitmap_->GetContinuousSpaceBitmap(from_ref);
1968 DCHECK(cc_bitmap != nullptr)
1969 << "An immune space object must have a bitmap";
1970 if (kIsDebugBuild) {
1971 DCHECK(heap_mark_bitmap_->GetContinuousSpaceBitmap(from_ref)->Test(from_ref))
1972 << "Immune space object must be already marked";
1973 }
1974 if (cc_bitmap->Test(from_ref)) {
1975 // Already marked.
1976 to_ref = from_ref;
1977 } else {
1978 // Newly marked.
1979 to_ref = nullptr;
1980 }
1981 } else {
1982 // Non-immune non-moving space. Use the mark bitmap.
1983 accounting::ContinuousSpaceBitmap* mark_bitmap =
1984 heap_mark_bitmap_->GetContinuousSpaceBitmap(from_ref);
1985 accounting::LargeObjectBitmap* los_bitmap =
1986 heap_mark_bitmap_->GetLargeObjectBitmap(from_ref);
1987 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
1988 bool is_los = mark_bitmap == nullptr;
1989 if (!is_los && mark_bitmap->Test(from_ref)) {
1990 // Already marked.
1991 to_ref = from_ref;
1992 } else if (is_los && los_bitmap->Test(from_ref)) {
1993 // Already marked in LOS.
1994 to_ref = from_ref;
1995 } else {
1996 // Not marked.
1997 if (IsOnAllocStack(from_ref)) {
1998 // If on the allocation stack, it's considered marked.
1999 to_ref = from_ref;
2000 } else {
2001 // Not marked.
2002 to_ref = nullptr;
2003 }
2004 }
2005 }
2006 }
2007 return to_ref;
2008}
2009
2010bool ConcurrentCopying::IsOnAllocStack(mirror::Object* ref) {
2011 QuasiAtomic::ThreadFenceAcquire();
2012 accounting::ObjectStack* alloc_stack = GetAllocationStack();
Mathieu Chartiercb535da2015-01-23 13:50:03 -08002013 return alloc_stack->Contains(ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002014}
2015
2016mirror::Object* ConcurrentCopying::Mark(mirror::Object* from_ref) {
2017 if (from_ref == nullptr) {
2018 return nullptr;
2019 }
2020 DCHECK(from_ref != nullptr);
2021 DCHECK(heap_->collector_type_ == kCollectorTypeCC);
Hiroshi Yamauchi60f63f52015-04-23 16:12:40 -07002022 if (kUseBakerReadBarrier && !is_active_) {
2023 // In the lock word forward address state, the read barrier bits
2024 // in the lock word are part of the stored forwarding address and
2025 // invalid. This is usually OK as the from-space copy of objects
2026 // aren't accessed by mutators due to the to-space
2027 // invariant. However, during the dex2oat image writing relocation
2028 // and the zygote compaction, objects can be in the forward
2029 // address state (to store the forward/relocation addresses) and
2030 // they can still be accessed and the invalid read barrier bits
2031 // are consulted. If they look like gray but aren't really, the
2032 // read barriers slow path can trigger when it shouldn't. To guard
2033 // against this, return here if the CC collector isn't running.
2034 return from_ref;
2035 }
2036 DCHECK(region_space_ != nullptr) << "Read barrier slow path taken when CC isn't running?";
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08002037 space::RegionSpace::RegionType rtype = region_space_->GetRegionType(from_ref);
2038 if (rtype == space::RegionSpace::RegionType::kRegionTypeToSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002039 // It's already marked.
2040 return from_ref;
2041 }
2042 mirror::Object* to_ref;
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08002043 if (rtype == space::RegionSpace::RegionType::kRegionTypeFromSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002044 to_ref = GetFwdPtr(from_ref);
2045 if (kUseBakerReadBarrier) {
2046 DCHECK(to_ref != ReadBarrier::GrayPtr()) << "from_ref=" << from_ref << " to_ref=" << to_ref;
2047 }
2048 if (to_ref == nullptr) {
2049 // It isn't marked yet. Mark it by copying it to the to-space.
2050 to_ref = Copy(from_ref);
2051 }
2052 DCHECK(region_space_->IsInToSpace(to_ref) || heap_->non_moving_space_->HasAddress(to_ref))
2053 << "from_ref=" << from_ref << " to_ref=" << to_ref;
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08002054 } else if (rtype == space::RegionSpace::RegionType::kRegionTypeUnevacFromSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002055 // This may or may not succeed, which is ok.
2056 if (kUseBakerReadBarrier) {
2057 from_ref->AtomicSetReadBarrierPointer(ReadBarrier::WhitePtr(), ReadBarrier::GrayPtr());
2058 }
2059 if (region_space_bitmap_->AtomicTestAndSet(from_ref)) {
2060 // Already marked.
2061 to_ref = from_ref;
2062 } else {
2063 // Newly marked.
2064 to_ref = from_ref;
2065 if (kUseBakerReadBarrier) {
2066 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr());
2067 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002068 PushOntoMarkStack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002069 }
2070 } else {
2071 // from_ref is in a non-moving space.
2072 DCHECK(!region_space_->HasAddress(from_ref)) << from_ref;
2073 if (immune_region_.ContainsObject(from_ref)) {
2074 accounting::ContinuousSpaceBitmap* cc_bitmap =
2075 cc_heap_bitmap_->GetContinuousSpaceBitmap(from_ref);
2076 DCHECK(cc_bitmap != nullptr)
2077 << "An immune space object must have a bitmap";
2078 if (kIsDebugBuild) {
2079 DCHECK(heap_mark_bitmap_->GetContinuousSpaceBitmap(from_ref)->Test(from_ref))
2080 << "Immune space object must be already marked";
2081 }
2082 // This may or may not succeed, which is ok.
2083 if (kUseBakerReadBarrier) {
2084 from_ref->AtomicSetReadBarrierPointer(ReadBarrier::WhitePtr(), ReadBarrier::GrayPtr());
2085 }
2086 if (cc_bitmap->AtomicTestAndSet(from_ref)) {
2087 // Already marked.
2088 to_ref = from_ref;
2089 } else {
2090 // Newly marked.
2091 to_ref = from_ref;
2092 if (kUseBakerReadBarrier) {
2093 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr());
2094 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002095 PushOntoMarkStack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002096 }
2097 } else {
2098 // Use the mark bitmap.
2099 accounting::ContinuousSpaceBitmap* mark_bitmap =
2100 heap_mark_bitmap_->GetContinuousSpaceBitmap(from_ref);
2101 accounting::LargeObjectBitmap* los_bitmap =
2102 heap_mark_bitmap_->GetLargeObjectBitmap(from_ref);
2103 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
2104 bool is_los = mark_bitmap == nullptr;
2105 if (!is_los && mark_bitmap->Test(from_ref)) {
2106 // Already marked.
2107 to_ref = from_ref;
2108 if (kUseBakerReadBarrier) {
2109 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr() ||
2110 to_ref->GetReadBarrierPointer() == ReadBarrier::BlackPtr());
2111 }
2112 } else if (is_los && los_bitmap->Test(from_ref)) {
2113 // Already marked in LOS.
2114 to_ref = from_ref;
2115 if (kUseBakerReadBarrier) {
2116 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr() ||
2117 to_ref->GetReadBarrierPointer() == ReadBarrier::BlackPtr());
2118 }
2119 } else {
2120 // Not marked.
2121 if (IsOnAllocStack(from_ref)) {
2122 // If it's on the allocation stack, it's considered marked. Keep it white.
2123 to_ref = from_ref;
2124 // Objects on the allocation stack need not be marked.
2125 if (!is_los) {
2126 DCHECK(!mark_bitmap->Test(to_ref));
2127 } else {
2128 DCHECK(!los_bitmap->Test(to_ref));
2129 }
2130 if (kUseBakerReadBarrier) {
2131 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::WhitePtr());
2132 }
2133 } else {
2134 // Not marked or on the allocation stack. Try to mark it.
2135 // This may or may not succeed, which is ok.
2136 if (kUseBakerReadBarrier) {
2137 from_ref->AtomicSetReadBarrierPointer(ReadBarrier::WhitePtr(), ReadBarrier::GrayPtr());
2138 }
2139 if (!is_los && mark_bitmap->AtomicTestAndSet(from_ref)) {
2140 // Already marked.
2141 to_ref = from_ref;
2142 } else if (is_los && los_bitmap->AtomicTestAndSet(from_ref)) {
2143 // Already marked in LOS.
2144 to_ref = from_ref;
2145 } else {
2146 // Newly marked.
2147 to_ref = from_ref;
2148 if (kUseBakerReadBarrier) {
2149 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr());
2150 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002151 PushOntoMarkStack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002152 }
2153 }
2154 }
2155 }
2156 }
2157 return to_ref;
2158}
2159
2160void ConcurrentCopying::FinishPhase() {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002161 {
2162 MutexLock mu(Thread::Current(), mark_stack_lock_);
2163 CHECK_EQ(pooled_mark_stacks_.size(), kMarkStackPoolSize);
2164 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002165 region_space_ = nullptr;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002166 {
2167 MutexLock mu(Thread::Current(), skipped_blocks_lock_);
2168 skipped_blocks_map_.clear();
2169 }
2170 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
2171 heap_->ClearMarkedObjects();
2172}
2173
Mathieu Chartier97509952015-07-13 14:35:43 -07002174bool ConcurrentCopying::IsMarkedHeapReference(mirror::HeapReference<mirror::Object>* field) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002175 mirror::Object* from_ref = field->AsMirrorPtr();
Mathieu Chartier97509952015-07-13 14:35:43 -07002176 mirror::Object* to_ref = IsMarked(from_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002177 if (to_ref == nullptr) {
2178 return false;
2179 }
2180 if (from_ref != to_ref) {
2181 QuasiAtomic::ThreadFenceRelease();
2182 field->Assign(to_ref);
2183 QuasiAtomic::ThreadFenceSequentiallyConsistent();
2184 }
2185 return true;
2186}
2187
Mathieu Chartier97509952015-07-13 14:35:43 -07002188mirror::Object* ConcurrentCopying::MarkObject(mirror::Object* from_ref) {
2189 return Mark(from_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002190}
2191
2192void ConcurrentCopying::DelayReferenceReferent(mirror::Class* klass, mirror::Reference* reference) {
Mathieu Chartier97509952015-07-13 14:35:43 -07002193 heap_->GetReferenceProcessor()->DelayReferenceReferent(klass, reference, this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002194}
2195
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002196void ConcurrentCopying::ProcessReferences(Thread* self) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002197 TimingLogger::ScopedTiming split("ProcessReferences", GetTimings());
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002198 // 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 -08002199 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
2200 GetHeap()->GetReferenceProcessor()->ProcessReferences(
Mathieu Chartier97509952015-07-13 14:35:43 -07002201 true /*concurrent*/, GetTimings(), GetCurrentIteration()->GetClearSoftReferences(), this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002202}
2203
2204void ConcurrentCopying::RevokeAllThreadLocalBuffers() {
2205 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
2206 region_space_->RevokeAllThreadLocalBuffers();
2207}
2208
Hiroshi Yamauchid5307ec2014-03-27 21:07:51 -07002209} // namespace collector
2210} // namespace gc
2211} // namespace art