blob: 0a7a69f37e5ee1e116b68052efb23c917ce7a8c1 [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"
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080021#include "gc/accounting/heap_bitmap-inl.h"
22#include "gc/accounting/space_bitmap-inl.h"
Mathieu Chartier3cf22532015-07-09 15:15:09 -070023#include "gc/reference_processor.h"
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080024#include "gc/space/image_space.h"
25#include "gc/space/space.h"
26#include "intern_table.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070027#include "mirror/class-inl.h"
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080028#include "mirror/object-inl.h"
29#include "scoped_thread_state_change.h"
30#include "thread-inl.h"
31#include "thread_list.h"
32#include "well_known_classes.h"
33
Hiroshi Yamauchid5307ec2014-03-27 21:07:51 -070034namespace art {
35namespace gc {
36namespace collector {
37
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080038ConcurrentCopying::ConcurrentCopying(Heap* heap, const std::string& name_prefix)
39 : GarbageCollector(heap,
40 name_prefix + (name_prefix.empty() ? "" : " ") +
41 "concurrent copying + mark sweep"),
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070042 region_space_(nullptr), gc_barrier_(new Barrier(0)),
43 gc_mark_stack_(accounting::ObjectStack::Create("concurrent copying gc mark stack",
44 2 * MB, 2 * MB)),
45 mark_stack_lock_("concurrent copying mark stack lock", kMarkSweepMarkStackLock),
46 thread_running_gc_(nullptr),
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080047 is_marking_(false), is_active_(false), is_asserting_to_space_invariant_(false),
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070048 heap_mark_bitmap_(nullptr), live_stack_freeze_size_(0), mark_stack_mode_(kMarkStackModeOff),
49 weak_ref_access_enabled_(true),
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080050 skipped_blocks_lock_("concurrent copying bytes blocks lock", kMarkSweepMarkStackLock),
51 rb_table_(heap_->GetReadBarrierTable()),
52 force_evacuate_all_(false) {
53 static_assert(space::RegionSpace::kRegionSize == accounting::ReadBarrierTable::kRegionSize,
54 "The region space size and the read barrier table region size must match");
55 cc_heap_bitmap_.reset(new accounting::HeapBitmap(heap));
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070056 Thread* self = Thread::Current();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080057 {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080058 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
59 // Cache this so that we won't have to lock heap_bitmap_lock_ in
60 // Mark() which could cause a nested lock on heap_bitmap_lock_
61 // when GC causes a RB while doing GC or a lock order violation
62 // (class_linker_lock_ and heap_bitmap_lock_).
63 heap_mark_bitmap_ = heap->GetMarkBitmap();
64 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070065 {
66 MutexLock mu(self, mark_stack_lock_);
67 for (size_t i = 0; i < kMarkStackPoolSize; ++i) {
68 accounting::AtomicStack<mirror::Object>* mark_stack =
69 accounting::AtomicStack<mirror::Object>::Create(
70 "thread local mark stack", kMarkStackSize, kMarkStackSize);
71 pooled_mark_stacks_.push_back(mark_stack);
72 }
73 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080074}
75
Mathieu Chartierb19ccb12015-07-15 10:24:16 -070076void ConcurrentCopying::MarkHeapReference(mirror::HeapReference<mirror::Object>* from_ref) {
77 // Used for preserving soft references, should be OK to not have a CAS here since there should be
78 // no other threads which can trigger read barriers on the same referent during reference
79 // processing.
80 from_ref->Assign(Mark(from_ref->AsMirrorPtr()));
Mathieu Chartier81187812015-07-15 14:24:07 -070081 DCHECK(!from_ref->IsNull());
Mathieu Chartier97509952015-07-13 14:35:43 -070082}
83
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080084ConcurrentCopying::~ConcurrentCopying() {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070085 STLDeleteElements(&pooled_mark_stacks_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080086}
87
88void ConcurrentCopying::RunPhases() {
89 CHECK(kUseBakerReadBarrier || kUseTableLookupReadBarrier);
90 CHECK(!is_active_);
91 is_active_ = true;
92 Thread* self = Thread::Current();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070093 thread_running_gc_ = self;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080094 Locks::mutator_lock_->AssertNotHeld(self);
95 {
96 ReaderMutexLock mu(self, *Locks::mutator_lock_);
97 InitializePhase();
98 }
99 FlipThreadRoots();
100 {
101 ReaderMutexLock mu(self, *Locks::mutator_lock_);
102 MarkingPhase();
103 }
104 // Verify no from space refs. This causes a pause.
105 if (kEnableNoFromSpaceRefsVerification || kIsDebugBuild) {
106 TimingLogger::ScopedTiming split("(Paused)VerifyNoFromSpaceReferences", GetTimings());
107 ScopedPause pause(this);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700108 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800109 if (kVerboseMode) {
110 LOG(INFO) << "Verifying no from-space refs";
111 }
112 VerifyNoFromSpaceReferences();
Mathieu Chartier720e71a2015-04-06 17:10:58 -0700113 if (kVerboseMode) {
114 LOG(INFO) << "Done verifying no from-space refs";
115 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700116 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800117 }
118 {
119 ReaderMutexLock mu(self, *Locks::mutator_lock_);
120 ReclaimPhase();
121 }
122 FinishPhase();
123 CHECK(is_active_);
124 is_active_ = false;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700125 thread_running_gc_ = nullptr;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800126}
127
128void ConcurrentCopying::BindBitmaps() {
129 Thread* self = Thread::Current();
130 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
131 // Mark all of the spaces we never collect as immune.
132 for (const auto& space : heap_->GetContinuousSpaces()) {
133 if (space->GetGcRetentionPolicy() == space::kGcRetentionPolicyNeverCollect
134 || space->GetGcRetentionPolicy() == space::kGcRetentionPolicyFullCollect) {
135 CHECK(space->IsZygoteSpace() || space->IsImageSpace());
136 CHECK(immune_region_.AddContinuousSpace(space)) << "Failed to add space " << *space;
137 const char* bitmap_name = space->IsImageSpace() ? "cc image space bitmap" :
138 "cc zygote space bitmap";
139 // TODO: try avoiding using bitmaps for image/zygote to save space.
140 accounting::ContinuousSpaceBitmap* bitmap =
141 accounting::ContinuousSpaceBitmap::Create(bitmap_name, space->Begin(), space->Capacity());
142 cc_heap_bitmap_->AddContinuousSpaceBitmap(bitmap);
143 cc_bitmaps_.push_back(bitmap);
144 } else if (space == region_space_) {
145 accounting::ContinuousSpaceBitmap* bitmap =
146 accounting::ContinuousSpaceBitmap::Create("cc region space bitmap",
147 space->Begin(), space->Capacity());
148 cc_heap_bitmap_->AddContinuousSpaceBitmap(bitmap);
149 cc_bitmaps_.push_back(bitmap);
150 region_space_bitmap_ = bitmap;
151 }
152 }
153}
154
155void ConcurrentCopying::InitializePhase() {
156 TimingLogger::ScopedTiming split("InitializePhase", GetTimings());
157 if (kVerboseMode) {
158 LOG(INFO) << "GC InitializePhase";
159 LOG(INFO) << "Region-space : " << reinterpret_cast<void*>(region_space_->Begin()) << "-"
160 << reinterpret_cast<void*>(region_space_->Limit());
161 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700162 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800163 immune_region_.Reset();
164 bytes_moved_.StoreRelaxed(0);
165 objects_moved_.StoreRelaxed(0);
166 if (GetCurrentIteration()->GetGcCause() == kGcCauseExplicit ||
167 GetCurrentIteration()->GetGcCause() == kGcCauseForNativeAlloc ||
168 GetCurrentIteration()->GetClearSoftReferences()) {
169 force_evacuate_all_ = true;
170 } else {
171 force_evacuate_all_ = false;
172 }
173 BindBitmaps();
174 if (kVerboseMode) {
175 LOG(INFO) << "force_evacuate_all=" << force_evacuate_all_;
176 LOG(INFO) << "Immune region: " << immune_region_.Begin() << "-" << immune_region_.End();
177 LOG(INFO) << "GC end of InitializePhase";
178 }
179}
180
181// Used to switch the thread roots of a thread from from-space refs to to-space refs.
182class ThreadFlipVisitor : public Closure {
183 public:
Roland Levillain3887c462015-08-12 18:15:42 +0100184 ThreadFlipVisitor(ConcurrentCopying* concurrent_copying, bool use_tlab)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800185 : concurrent_copying_(concurrent_copying), use_tlab_(use_tlab) {
186 }
187
Mathieu Chartier90443472015-07-16 20:32:27 -0700188 virtual void Run(Thread* thread) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800189 // Note: self is not necessarily equal to thread since thread may be suspended.
190 Thread* self = Thread::Current();
191 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
192 << thread->GetState() << " thread " << thread << " self " << self;
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700193 thread->SetIsGcMarking(true);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800194 if (use_tlab_ && thread->HasTlab()) {
195 if (ConcurrentCopying::kEnableFromSpaceAccountingCheck) {
196 // This must come before the revoke.
197 size_t thread_local_objects = thread->GetThreadLocalObjectsAllocated();
198 concurrent_copying_->region_space_->RevokeThreadLocalBuffers(thread);
199 reinterpret_cast<Atomic<size_t>*>(&concurrent_copying_->from_space_num_objects_at_first_pause_)->
200 FetchAndAddSequentiallyConsistent(thread_local_objects);
201 } else {
202 concurrent_copying_->region_space_->RevokeThreadLocalBuffers(thread);
203 }
204 }
205 if (kUseThreadLocalAllocationStack) {
206 thread->RevokeThreadLocalAllocationStack();
207 }
208 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700209 thread->VisitRoots(concurrent_copying_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800210 concurrent_copying_->GetBarrier().Pass(self);
211 }
212
213 private:
214 ConcurrentCopying* const concurrent_copying_;
215 const bool use_tlab_;
216};
217
218// Called back from Runtime::FlipThreadRoots() during a pause.
219class FlipCallback : public Closure {
220 public:
221 explicit FlipCallback(ConcurrentCopying* concurrent_copying)
222 : concurrent_copying_(concurrent_copying) {
223 }
224
Mathieu Chartier90443472015-07-16 20:32:27 -0700225 virtual void Run(Thread* thread) OVERRIDE REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800226 ConcurrentCopying* cc = concurrent_copying_;
227 TimingLogger::ScopedTiming split("(Paused)FlipCallback", cc->GetTimings());
228 // Note: self is not necessarily equal to thread since thread may be suspended.
229 Thread* self = Thread::Current();
230 CHECK(thread == self);
231 Locks::mutator_lock_->AssertExclusiveHeld(self);
232 cc->region_space_->SetFromSpace(cc->rb_table_, cc->force_evacuate_all_);
Mathieu Chartiera4f6af92015-08-11 17:35:25 -0700233 cc->SwapStacks();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800234 if (ConcurrentCopying::kEnableFromSpaceAccountingCheck) {
235 cc->RecordLiveStackFreezeSize(self);
236 cc->from_space_num_objects_at_first_pause_ = cc->region_space_->GetObjectsAllocated();
237 cc->from_space_num_bytes_at_first_pause_ = cc->region_space_->GetBytesAllocated();
238 }
239 cc->is_marking_ = true;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700240 cc->mark_stack_mode_.StoreRelaxed(ConcurrentCopying::kMarkStackModeThreadLocal);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800241 if (UNLIKELY(Runtime::Current()->IsActiveTransaction())) {
Mathieu Chartier184c9dc2015-03-05 13:20:54 -0800242 CHECK(Runtime::Current()->IsAotCompiler());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800243 TimingLogger::ScopedTiming split2("(Paused)VisitTransactionRoots", cc->GetTimings());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700244 Runtime::Current()->VisitTransactionRoots(cc);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800245 }
246 }
247
248 private:
249 ConcurrentCopying* const concurrent_copying_;
250};
251
252// Switch threads that from from-space to to-space refs. Forward/mark the thread roots.
253void ConcurrentCopying::FlipThreadRoots() {
254 TimingLogger::ScopedTiming split("FlipThreadRoots", GetTimings());
255 if (kVerboseMode) {
256 LOG(INFO) << "time=" << region_space_->Time();
257 region_space_->DumpNonFreeRegions(LOG(INFO));
258 }
259 Thread* self = Thread::Current();
260 Locks::mutator_lock_->AssertNotHeld(self);
261 gc_barrier_->Init(self, 0);
262 ThreadFlipVisitor thread_flip_visitor(this, heap_->use_tlab_);
263 FlipCallback flip_callback(this);
Hiroshi Yamauchi76f55b02015-08-21 16:10:39 -0700264 heap_->ThreadFlipBegin(self); // Sync with JNI critical calls.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800265 size_t barrier_count = Runtime::Current()->FlipThreadRoots(
266 &thread_flip_visitor, &flip_callback, this);
Hiroshi Yamauchi76f55b02015-08-21 16:10:39 -0700267 heap_->ThreadFlipEnd(self);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800268 {
269 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
270 gc_barrier_->Increment(self, barrier_count);
271 }
272 is_asserting_to_space_invariant_ = true;
273 QuasiAtomic::ThreadFenceForConstructor();
274 if (kVerboseMode) {
275 LOG(INFO) << "time=" << region_space_->Time();
276 region_space_->DumpNonFreeRegions(LOG(INFO));
277 LOG(INFO) << "GC end of FlipThreadRoots";
278 }
279}
280
Mathieu Chartiera4f6af92015-08-11 17:35:25 -0700281void ConcurrentCopying::SwapStacks() {
282 heap_->SwapStacks();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800283}
284
285void ConcurrentCopying::RecordLiveStackFreezeSize(Thread* self) {
286 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
287 live_stack_freeze_size_ = heap_->GetLiveStack()->Size();
288}
289
290// Used to visit objects in the immune spaces.
291class ConcurrentCopyingImmuneSpaceObjVisitor {
292 public:
293 explicit ConcurrentCopyingImmuneSpaceObjVisitor(ConcurrentCopying* cc)
294 : collector_(cc) {}
295
Mathieu Chartier90443472015-07-16 20:32:27 -0700296 void operator()(mirror::Object* obj) const SHARED_REQUIRES(Locks::mutator_lock_)
297 SHARED_REQUIRES(Locks::heap_bitmap_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800298 DCHECK(obj != nullptr);
299 DCHECK(collector_->immune_region_.ContainsObject(obj));
300 accounting::ContinuousSpaceBitmap* cc_bitmap =
301 collector_->cc_heap_bitmap_->GetContinuousSpaceBitmap(obj);
302 DCHECK(cc_bitmap != nullptr)
303 << "An immune space object must have a bitmap";
304 if (kIsDebugBuild) {
305 DCHECK(collector_->heap_->GetMarkBitmap()->Test(obj))
306 << "Immune space object must be already marked";
307 }
308 // This may or may not succeed, which is ok.
309 if (kUseBakerReadBarrier) {
310 obj->AtomicSetReadBarrierPointer(ReadBarrier::WhitePtr(), ReadBarrier::GrayPtr());
311 }
312 if (cc_bitmap->AtomicTestAndSet(obj)) {
313 // Already marked. Do nothing.
314 } else {
315 // Newly marked. Set the gray bit and push it onto the mark stack.
316 CHECK(!kUseBakerReadBarrier || obj->GetReadBarrierPointer() == ReadBarrier::GrayPtr());
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700317 collector_->PushOntoMarkStack(obj);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800318 }
319 }
320
321 private:
Mathieu Chartier97509952015-07-13 14:35:43 -0700322 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800323};
324
325class EmptyCheckpoint : public Closure {
326 public:
327 explicit EmptyCheckpoint(ConcurrentCopying* concurrent_copying)
328 : concurrent_copying_(concurrent_copying) {
329 }
330
331 virtual void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
332 // Note: self is not necessarily equal to thread since thread may be suspended.
333 Thread* self = Thread::Current();
334 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
335 << thread->GetState() << " thread " << thread << " self " << self;
Lei Lidd9943d2015-02-02 14:24:44 +0800336 // If thread is a running mutator, then act on behalf of the garbage collector.
337 // See the code in ThreadList::RunCheckpoint.
338 if (thread->GetState() == kRunnable) {
339 concurrent_copying_->GetBarrier().Pass(self);
340 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800341 }
342
343 private:
344 ConcurrentCopying* const concurrent_copying_;
345};
346
347// Concurrently mark roots that are guarded by read barriers and process the mark stack.
348void ConcurrentCopying::MarkingPhase() {
349 TimingLogger::ScopedTiming split("MarkingPhase", GetTimings());
350 if (kVerboseMode) {
351 LOG(INFO) << "GC MarkingPhase";
352 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700353 CHECK(weak_ref_access_enabled_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800354 {
355 // Mark the image root. The WB-based collectors do not need to
356 // scan the image objects from roots by relying on the card table,
357 // but it's necessary for the RB to-space invariant to hold.
358 TimingLogger::ScopedTiming split1("VisitImageRoots", GetTimings());
359 gc::space::ImageSpace* image = heap_->GetImageSpace();
360 if (image != nullptr) {
361 mirror::ObjectArray<mirror::Object>* image_root = image->GetImageHeader().GetImageRoots();
362 mirror::Object* marked_image_root = Mark(image_root);
363 CHECK_EQ(image_root, marked_image_root) << "An image object does not move";
364 if (ReadBarrier::kEnableToSpaceInvariantChecks) {
365 AssertToSpaceInvariant(nullptr, MemberOffset(0), marked_image_root);
366 }
367 }
368 }
Man Cao41656de2015-07-06 18:53:15 -0700369 // TODO: Other garbage collectors uses Runtime::VisitConcurrentRoots(), refactor this part
370 // to also use the same function.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800371 {
372 TimingLogger::ScopedTiming split2("VisitConstantRoots", GetTimings());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700373 Runtime::Current()->VisitConstantRoots(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800374 }
375 {
376 TimingLogger::ScopedTiming split3("VisitInternTableRoots", GetTimings());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700377 Runtime::Current()->GetInternTable()->VisitRoots(this, kVisitRootFlagAllRoots);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800378 }
379 {
380 TimingLogger::ScopedTiming split4("VisitClassLinkerRoots", GetTimings());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700381 Runtime::Current()->GetClassLinker()->VisitRoots(this, kVisitRootFlagAllRoots);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800382 }
383 {
384 // TODO: don't visit the transaction roots if it's not active.
385 TimingLogger::ScopedTiming split5("VisitNonThreadRoots", GetTimings());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700386 Runtime::Current()->VisitNonThreadRoots(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800387 }
Man Cao41656de2015-07-06 18:53:15 -0700388 Runtime::Current()->GetHeap()->VisitAllocationRecords(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800389
390 // Immune spaces.
391 for (auto& space : heap_->GetContinuousSpaces()) {
392 if (immune_region_.ContainsSpace(space)) {
393 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
394 accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
395 ConcurrentCopyingImmuneSpaceObjVisitor visitor(this);
396 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()),
397 reinterpret_cast<uintptr_t>(space->Limit()),
398 visitor);
399 }
400 }
401
402 Thread* self = Thread::Current();
403 {
404 TimingLogger::ScopedTiming split6("ProcessMarkStack", GetTimings());
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700405 // We transition through three mark stack modes (thread-local, shared, GC-exclusive). The
406 // primary reasons are the fact that we need to use a checkpoint to process thread-local mark
407 // stacks, but after we disable weak refs accesses, we can't use a checkpoint due to a deadlock
408 // issue because running threads potentially blocking at WaitHoldingLocks, and that once we
409 // reach the point where we process weak references, we can avoid using a lock when accessing
410 // the GC mark stack, which makes mark stack processing more efficient.
411
412 // Process the mark stack once in the thread local stack mode. This marks most of the live
413 // objects, aside from weak ref accesses with read barriers (Reference::GetReferent() and system
414 // weaks) that may happen concurrently while we processing the mark stack and newly mark/gray
415 // objects and push refs on the mark stack.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800416 ProcessMarkStack();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700417 // Switch to the shared mark stack mode. That is, revoke and process thread-local mark stacks
418 // for the last time before transitioning to the shared mark stack mode, which would process new
419 // refs that may have been concurrently pushed onto the mark stack during the ProcessMarkStack()
420 // call above. At the same time, disable weak ref accesses using a per-thread flag. It's
421 // important to do these together in a single checkpoint so that we can ensure that mutators
422 // won't newly gray objects and push new refs onto the mark stack due to weak ref accesses and
423 // mutators safely transition to the shared mark stack mode (without leaving unprocessed refs on
424 // the thread-local mark stacks), without a race. This is why we use a thread-local weak ref
425 // access flag Thread::tls32_.weak_ref_access_enabled_ instead of the global ones.
426 SwitchToSharedMarkStackMode();
427 CHECK(!self->GetWeakRefAccessEnabled());
428 // Now that weak refs accesses are disabled, once we exhaust the shared mark stack again here
429 // (which may be non-empty if there were refs found on thread-local mark stacks during the above
430 // SwitchToSharedMarkStackMode() call), we won't have new refs to process, that is, mutators
431 // (via read barriers) have no way to produce any more refs to process. Marking converges once
432 // before we process weak refs below.
433 ProcessMarkStack();
434 CheckEmptyMarkStack();
435 // Switch to the GC exclusive mark stack mode so that we can process the mark stack without a
436 // lock from this point on.
437 SwitchToGcExclusiveMarkStackMode();
438 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800439 if (kVerboseMode) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800440 LOG(INFO) << "ProcessReferences";
441 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700442 // Process weak references. This may produce new refs to process and have them processed via
Mathieu Chartier97509952015-07-13 14:35:43 -0700443 // ProcessMarkStack (in the GC exclusive mark stack mode).
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700444 ProcessReferences(self);
445 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800446 if (kVerboseMode) {
447 LOG(INFO) << "SweepSystemWeaks";
448 }
449 SweepSystemWeaks(self);
450 if (kVerboseMode) {
451 LOG(INFO) << "SweepSystemWeaks done";
452 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700453 // Process the mark stack here one last time because the above SweepSystemWeaks() call may have
454 // marked some objects (strings alive) as hash_set::Erase() can call the hash function for
455 // arbitrary elements in the weak intern table in InternTable::Table::SweepWeaks().
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800456 ProcessMarkStack();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700457 CheckEmptyMarkStack();
458 // Re-enable weak ref accesses.
459 ReenableWeakRefAccess(self);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -0700460 // Free data for class loaders that we unloaded.
461 Runtime::Current()->GetClassLinker()->CleanupClassLoaders();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700462 // Marking is done. Disable marking.
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700463 DisableMarking();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700464 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800465 }
466
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700467 CHECK(weak_ref_access_enabled_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800468 if (kVerboseMode) {
469 LOG(INFO) << "GC end of MarkingPhase";
470 }
471}
472
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700473void ConcurrentCopying::ReenableWeakRefAccess(Thread* self) {
474 if (kVerboseMode) {
475 LOG(INFO) << "ReenableWeakRefAccess";
476 }
477 weak_ref_access_enabled_.StoreRelaxed(true); // This is for new threads.
478 QuasiAtomic::ThreadFenceForConstructor();
479 // Iterate all threads (don't need to or can't use a checkpoint) and re-enable weak ref access.
480 {
481 MutexLock mu(self, *Locks::thread_list_lock_);
482 std::list<Thread*> thread_list = Runtime::Current()->GetThreadList()->GetList();
483 for (Thread* thread : thread_list) {
484 thread->SetWeakRefAccessEnabled(true);
485 }
486 }
487 // Unblock blocking threads.
488 GetHeap()->GetReferenceProcessor()->BroadcastForSlowPath(self);
489 Runtime::Current()->BroadcastForNewSystemWeaks();
490}
491
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700492class DisableMarkingCheckpoint : public Closure {
493 public:
494 explicit DisableMarkingCheckpoint(ConcurrentCopying* concurrent_copying)
495 : concurrent_copying_(concurrent_copying) {
496 }
497
498 void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
499 // Note: self is not necessarily equal to thread since thread may be suspended.
500 Thread* self = Thread::Current();
501 DCHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
502 << thread->GetState() << " thread " << thread << " self " << self;
503 // Disable the thread-local is_gc_marking flag.
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -0700504 // Note a thread that has just started right before this checkpoint may have already this flag
505 // set to false, which is ok.
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700506 thread->SetIsGcMarking(false);
507 // If thread is a running mutator, then act on behalf of the garbage collector.
508 // See the code in ThreadList::RunCheckpoint.
509 if (thread->GetState() == kRunnable) {
510 concurrent_copying_->GetBarrier().Pass(self);
511 }
512 }
513
514 private:
515 ConcurrentCopying* const concurrent_copying_;
516};
517
518void ConcurrentCopying::IssueDisableMarkingCheckpoint() {
519 Thread* self = Thread::Current();
520 DisableMarkingCheckpoint check_point(this);
521 ThreadList* thread_list = Runtime::Current()->GetThreadList();
522 gc_barrier_->Init(self, 0);
523 size_t barrier_count = thread_list->RunCheckpoint(&check_point);
524 // If there are no threads to wait which implies that all the checkpoint functions are finished,
525 // then no need to release the mutator lock.
526 if (barrier_count == 0) {
527 return;
528 }
529 // Release locks then wait for all mutator threads to pass the barrier.
530 Locks::mutator_lock_->SharedUnlock(self);
531 {
532 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
533 gc_barrier_->Increment(self, barrier_count);
534 }
535 Locks::mutator_lock_->SharedLock(self);
536}
537
538void ConcurrentCopying::DisableMarking() {
539 // Change the global is_marking flag to false. Do a fence before doing a checkpoint to update the
540 // thread-local flags so that a new thread starting up will get the correct is_marking flag.
541 is_marking_ = false;
542 QuasiAtomic::ThreadFenceForConstructor();
543 // Use a checkpoint to turn off the thread-local is_gc_marking flags and to ensure no threads are
544 // still in the middle of a read barrier which may have a from-space ref cached in a local
545 // variable.
546 IssueDisableMarkingCheckpoint();
547 if (kUseTableLookupReadBarrier) {
548 heap_->rb_table_->ClearAll();
549 DCHECK(heap_->rb_table_->IsAllCleared());
550 }
551 is_mark_stack_push_disallowed_.StoreSequentiallyConsistent(1);
552 mark_stack_mode_.StoreSequentiallyConsistent(kMarkStackModeOff);
553}
554
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800555void ConcurrentCopying::IssueEmptyCheckpoint() {
556 Thread* self = Thread::Current();
557 EmptyCheckpoint check_point(this);
558 ThreadList* thread_list = Runtime::Current()->GetThreadList();
559 gc_barrier_->Init(self, 0);
560 size_t barrier_count = thread_list->RunCheckpoint(&check_point);
Lei Lidd9943d2015-02-02 14:24:44 +0800561 // If there are no threads to wait which implys that all the checkpoint functions are finished,
562 // then no need to release the mutator lock.
563 if (barrier_count == 0) {
564 return;
565 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800566 // Release locks then wait for all mutator threads to pass the barrier.
567 Locks::mutator_lock_->SharedUnlock(self);
568 {
569 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
570 gc_barrier_->Increment(self, barrier_count);
571 }
572 Locks::mutator_lock_->SharedLock(self);
573}
574
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800575void ConcurrentCopying::PushOntoMarkStack(mirror::Object* to_ref) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700576 CHECK_EQ(is_mark_stack_push_disallowed_.LoadRelaxed(), 0)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800577 << " " << to_ref << " " << PrettyTypeOf(to_ref);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700578 Thread* self = Thread::Current(); // TODO: pass self as an argument from call sites?
579 CHECK(thread_running_gc_ != nullptr);
580 MarkStackMode mark_stack_mode = mark_stack_mode_.LoadRelaxed();
581 if (mark_stack_mode == kMarkStackModeThreadLocal) {
582 if (self == thread_running_gc_) {
583 // If GC-running thread, use the GC mark stack instead of a thread-local mark stack.
584 CHECK(self->GetThreadLocalMarkStack() == nullptr);
585 CHECK(!gc_mark_stack_->IsFull());
586 gc_mark_stack_->PushBack(to_ref);
587 } else {
588 // Otherwise, use a thread-local mark stack.
589 accounting::AtomicStack<mirror::Object>* tl_mark_stack = self->GetThreadLocalMarkStack();
590 if (UNLIKELY(tl_mark_stack == nullptr || tl_mark_stack->IsFull())) {
591 MutexLock mu(self, mark_stack_lock_);
592 // Get a new thread local mark stack.
593 accounting::AtomicStack<mirror::Object>* new_tl_mark_stack;
594 if (!pooled_mark_stacks_.empty()) {
595 // Use a pooled mark stack.
596 new_tl_mark_stack = pooled_mark_stacks_.back();
597 pooled_mark_stacks_.pop_back();
598 } else {
599 // None pooled. Create a new one.
600 new_tl_mark_stack =
601 accounting::AtomicStack<mirror::Object>::Create(
602 "thread local mark stack", 4 * KB, 4 * KB);
603 }
604 DCHECK(new_tl_mark_stack != nullptr);
605 DCHECK(new_tl_mark_stack->IsEmpty());
606 new_tl_mark_stack->PushBack(to_ref);
607 self->SetThreadLocalMarkStack(new_tl_mark_stack);
608 if (tl_mark_stack != nullptr) {
609 // Store the old full stack into a vector.
610 revoked_mark_stacks_.push_back(tl_mark_stack);
611 }
612 } else {
613 tl_mark_stack->PushBack(to_ref);
614 }
615 }
616 } else if (mark_stack_mode == kMarkStackModeShared) {
617 // Access the shared GC mark stack with a lock.
618 MutexLock mu(self, mark_stack_lock_);
619 CHECK(!gc_mark_stack_->IsFull());
620 gc_mark_stack_->PushBack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800621 } else {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700622 CHECK_EQ(static_cast<uint32_t>(mark_stack_mode),
Hiroshi Yamauchifa755182015-09-30 20:12:11 -0700623 static_cast<uint32_t>(kMarkStackModeGcExclusive))
624 << "ref=" << to_ref
625 << " self->gc_marking=" << self->GetIsGcMarking()
626 << " cc->is_marking=" << is_marking_;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700627 CHECK(self == thread_running_gc_)
628 << "Only GC-running thread should access the mark stack "
629 << "in the GC exclusive mark stack mode";
630 // Access the GC mark stack without a lock.
631 CHECK(!gc_mark_stack_->IsFull());
632 gc_mark_stack_->PushBack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800633 }
634}
635
636accounting::ObjectStack* ConcurrentCopying::GetAllocationStack() {
637 return heap_->allocation_stack_.get();
638}
639
640accounting::ObjectStack* ConcurrentCopying::GetLiveStack() {
641 return heap_->live_stack_.get();
642}
643
644inline mirror::Object* ConcurrentCopying::GetFwdPtr(mirror::Object* from_ref) {
645 DCHECK(region_space_->IsInFromSpace(from_ref));
646 LockWord lw = from_ref->GetLockWord(false);
647 if (lw.GetState() == LockWord::kForwardingAddress) {
648 mirror::Object* fwd_ptr = reinterpret_cast<mirror::Object*>(lw.ForwardingAddress());
649 CHECK(fwd_ptr != nullptr);
650 return fwd_ptr;
651 } else {
652 return nullptr;
653 }
654}
655
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800656// The following visitors are that used to verify that there's no
657// references to the from-space left after marking.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700658class ConcurrentCopyingVerifyNoFromSpaceRefsVisitor : public SingleRootVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800659 public:
660 explicit ConcurrentCopyingVerifyNoFromSpaceRefsVisitor(ConcurrentCopying* collector)
661 : collector_(collector) {}
662
663 void operator()(mirror::Object* ref) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700664 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800665 if (ref == nullptr) {
666 // OK.
667 return;
668 }
669 collector_->AssertToSpaceInvariant(nullptr, MemberOffset(0), ref);
670 if (kUseBakerReadBarrier) {
671 if (collector_->RegionSpace()->IsInToSpace(ref)) {
672 CHECK(ref->GetReadBarrierPointer() == nullptr)
673 << "To-space ref " << ref << " " << PrettyTypeOf(ref)
674 << " has non-white rb_ptr " << ref->GetReadBarrierPointer();
675 } else {
676 CHECK(ref->GetReadBarrierPointer() == ReadBarrier::BlackPtr() ||
677 (ref->GetReadBarrierPointer() == ReadBarrier::WhitePtr() &&
678 collector_->IsOnAllocStack(ref)))
679 << "Non-moving/unevac from space ref " << ref << " " << PrettyTypeOf(ref)
680 << " has non-black rb_ptr " << ref->GetReadBarrierPointer()
681 << " but isn't on the alloc stack (and has white rb_ptr)."
682 << " Is it in the non-moving space="
683 << (collector_->GetHeap()->GetNonMovingSpace()->HasAddress(ref));
684 }
685 }
686 }
687
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700688 void VisitRoot(mirror::Object* root, const RootInfo& info ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -0700689 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800690 DCHECK(root != nullptr);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700691 operator()(root);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800692 }
693
694 private:
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700695 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800696};
697
698class ConcurrentCopyingVerifyNoFromSpaceRefsFieldVisitor {
699 public:
700 explicit ConcurrentCopyingVerifyNoFromSpaceRefsFieldVisitor(ConcurrentCopying* collector)
701 : collector_(collector) {}
702
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700703 void operator()(mirror::Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700704 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800705 mirror::Object* ref =
706 obj->GetFieldObject<mirror::Object, kDefaultVerifyFlags, kWithoutReadBarrier>(offset);
707 ConcurrentCopyingVerifyNoFromSpaceRefsVisitor visitor(collector_);
708 visitor(ref);
709 }
710 void operator()(mirror::Class* klass, mirror::Reference* ref) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700711 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800712 CHECK(klass->IsTypeOfReferenceClass());
713 this->operator()(ref, mirror::Reference::ReferentOffset(), false);
714 }
715
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700716 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
717 SHARED_REQUIRES(Locks::mutator_lock_) {
718 if (!root->IsNull()) {
719 VisitRoot(root);
720 }
721 }
722
723 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
724 SHARED_REQUIRES(Locks::mutator_lock_) {
725 ConcurrentCopyingVerifyNoFromSpaceRefsVisitor visitor(collector_);
726 visitor(root->AsMirrorPtr());
727 }
728
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800729 private:
Mathieu Chartier97509952015-07-13 14:35:43 -0700730 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800731};
732
733class ConcurrentCopyingVerifyNoFromSpaceRefsObjectVisitor {
734 public:
735 explicit ConcurrentCopyingVerifyNoFromSpaceRefsObjectVisitor(ConcurrentCopying* collector)
736 : collector_(collector) {}
737 void operator()(mirror::Object* obj) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700738 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800739 ObjectCallback(obj, collector_);
740 }
741 static void ObjectCallback(mirror::Object* obj, void *arg)
Mathieu Chartier90443472015-07-16 20:32:27 -0700742 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800743 CHECK(obj != nullptr);
744 ConcurrentCopying* collector = reinterpret_cast<ConcurrentCopying*>(arg);
745 space::RegionSpace* region_space = collector->RegionSpace();
746 CHECK(!region_space->IsInFromSpace(obj)) << "Scanning object " << obj << " in from space";
747 ConcurrentCopyingVerifyNoFromSpaceRefsFieldVisitor visitor(collector);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -0700748 obj->VisitReferences(visitor, visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800749 if (kUseBakerReadBarrier) {
750 if (collector->RegionSpace()->IsInToSpace(obj)) {
751 CHECK(obj->GetReadBarrierPointer() == nullptr)
752 << "obj=" << obj << " non-white rb_ptr " << obj->GetReadBarrierPointer();
753 } else {
754 CHECK(obj->GetReadBarrierPointer() == ReadBarrier::BlackPtr() ||
755 (obj->GetReadBarrierPointer() == ReadBarrier::WhitePtr() &&
756 collector->IsOnAllocStack(obj)))
757 << "Non-moving space/unevac from space ref " << obj << " " << PrettyTypeOf(obj)
758 << " has non-black rb_ptr " << obj->GetReadBarrierPointer()
759 << " but isn't on the alloc stack (and has white rb_ptr). Is it in the non-moving space="
760 << (collector->GetHeap()->GetNonMovingSpace()->HasAddress(obj));
761 }
762 }
763 }
764
765 private:
766 ConcurrentCopying* const collector_;
767};
768
769// Verify there's no from-space references left after the marking phase.
770void ConcurrentCopying::VerifyNoFromSpaceReferences() {
771 Thread* self = Thread::Current();
772 DCHECK(Locks::mutator_lock_->IsExclusiveHeld(self));
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700773 // Verify all threads have is_gc_marking to be false
774 {
775 MutexLock mu(self, *Locks::thread_list_lock_);
776 std::list<Thread*> thread_list = Runtime::Current()->GetThreadList()->GetList();
777 for (Thread* thread : thread_list) {
778 CHECK(!thread->GetIsGcMarking());
779 }
780 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800781 ConcurrentCopyingVerifyNoFromSpaceRefsObjectVisitor visitor(this);
782 // Roots.
783 {
784 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700785 ConcurrentCopyingVerifyNoFromSpaceRefsVisitor ref_visitor(this);
786 Runtime::Current()->VisitRoots(&ref_visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800787 }
788 // The to-space.
789 region_space_->WalkToSpace(ConcurrentCopyingVerifyNoFromSpaceRefsObjectVisitor::ObjectCallback,
790 this);
791 // Non-moving spaces.
792 {
793 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
794 heap_->GetMarkBitmap()->Visit(visitor);
795 }
796 // The alloc stack.
797 {
798 ConcurrentCopyingVerifyNoFromSpaceRefsVisitor ref_visitor(this);
Mathieu Chartiercb535da2015-01-23 13:50:03 -0800799 for (auto* it = heap_->allocation_stack_->Begin(), *end = heap_->allocation_stack_->End();
800 it < end; ++it) {
801 mirror::Object* const obj = it->AsMirrorPtr();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800802 if (obj != nullptr && obj->GetClass() != nullptr) {
803 // TODO: need to call this only if obj is alive?
804 ref_visitor(obj);
805 visitor(obj);
806 }
807 }
808 }
809 // TODO: LOS. But only refs in LOS are classes.
810}
811
812// The following visitors are used to assert the to-space invariant.
813class ConcurrentCopyingAssertToSpaceInvariantRefsVisitor {
814 public:
815 explicit ConcurrentCopyingAssertToSpaceInvariantRefsVisitor(ConcurrentCopying* collector)
816 : collector_(collector) {}
817
818 void operator()(mirror::Object* ref) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700819 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800820 if (ref == nullptr) {
821 // OK.
822 return;
823 }
824 collector_->AssertToSpaceInvariant(nullptr, MemberOffset(0), ref);
825 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800826
827 private:
Mathieu Chartier97509952015-07-13 14:35:43 -0700828 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800829};
830
831class ConcurrentCopyingAssertToSpaceInvariantFieldVisitor {
832 public:
833 explicit ConcurrentCopyingAssertToSpaceInvariantFieldVisitor(ConcurrentCopying* collector)
834 : collector_(collector) {}
835
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700836 void operator()(mirror::Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700837 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800838 mirror::Object* ref =
839 obj->GetFieldObject<mirror::Object, kDefaultVerifyFlags, kWithoutReadBarrier>(offset);
840 ConcurrentCopyingAssertToSpaceInvariantRefsVisitor visitor(collector_);
841 visitor(ref);
842 }
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700843 void operator()(mirror::Class* klass, mirror::Reference* ref ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700844 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800845 CHECK(klass->IsTypeOfReferenceClass());
846 }
847
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700848 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
849 SHARED_REQUIRES(Locks::mutator_lock_) {
850 if (!root->IsNull()) {
851 VisitRoot(root);
852 }
853 }
854
855 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
856 SHARED_REQUIRES(Locks::mutator_lock_) {
857 ConcurrentCopyingAssertToSpaceInvariantRefsVisitor visitor(collector_);
858 visitor(root->AsMirrorPtr());
859 }
860
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800861 private:
Mathieu Chartier97509952015-07-13 14:35:43 -0700862 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800863};
864
865class ConcurrentCopyingAssertToSpaceInvariantObjectVisitor {
866 public:
867 explicit ConcurrentCopyingAssertToSpaceInvariantObjectVisitor(ConcurrentCopying* collector)
868 : collector_(collector) {}
869 void operator()(mirror::Object* obj) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700870 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800871 ObjectCallback(obj, collector_);
872 }
873 static void ObjectCallback(mirror::Object* obj, void *arg)
Mathieu Chartier90443472015-07-16 20:32:27 -0700874 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800875 CHECK(obj != nullptr);
876 ConcurrentCopying* collector = reinterpret_cast<ConcurrentCopying*>(arg);
877 space::RegionSpace* region_space = collector->RegionSpace();
878 CHECK(!region_space->IsInFromSpace(obj)) << "Scanning object " << obj << " in from space";
879 collector->AssertToSpaceInvariant(nullptr, MemberOffset(0), obj);
880 ConcurrentCopyingAssertToSpaceInvariantFieldVisitor visitor(collector);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -0700881 obj->VisitReferences(visitor, visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800882 }
883
884 private:
Mathieu Chartier97509952015-07-13 14:35:43 -0700885 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800886};
887
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700888class RevokeThreadLocalMarkStackCheckpoint : public Closure {
889 public:
Roland Levillain3887c462015-08-12 18:15:42 +0100890 RevokeThreadLocalMarkStackCheckpoint(ConcurrentCopying* concurrent_copying,
891 bool disable_weak_ref_access)
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700892 : concurrent_copying_(concurrent_copying),
893 disable_weak_ref_access_(disable_weak_ref_access) {
894 }
895
896 virtual void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
897 // Note: self is not necessarily equal to thread since thread may be suspended.
898 Thread* self = Thread::Current();
899 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
900 << thread->GetState() << " thread " << thread << " self " << self;
901 // Revoke thread local mark stacks.
902 accounting::AtomicStack<mirror::Object>* tl_mark_stack = thread->GetThreadLocalMarkStack();
903 if (tl_mark_stack != nullptr) {
904 MutexLock mu(self, concurrent_copying_->mark_stack_lock_);
905 concurrent_copying_->revoked_mark_stacks_.push_back(tl_mark_stack);
906 thread->SetThreadLocalMarkStack(nullptr);
907 }
908 // Disable weak ref access.
909 if (disable_weak_ref_access_) {
910 thread->SetWeakRefAccessEnabled(false);
911 }
912 // If thread is a running mutator, then act on behalf of the garbage collector.
913 // See the code in ThreadList::RunCheckpoint.
914 if (thread->GetState() == kRunnable) {
915 concurrent_copying_->GetBarrier().Pass(self);
916 }
917 }
918
919 private:
920 ConcurrentCopying* const concurrent_copying_;
921 const bool disable_weak_ref_access_;
922};
923
924void ConcurrentCopying::RevokeThreadLocalMarkStacks(bool disable_weak_ref_access) {
925 Thread* self = Thread::Current();
926 RevokeThreadLocalMarkStackCheckpoint check_point(this, disable_weak_ref_access);
927 ThreadList* thread_list = Runtime::Current()->GetThreadList();
928 gc_barrier_->Init(self, 0);
929 size_t barrier_count = thread_list->RunCheckpoint(&check_point);
930 // If there are no threads to wait which implys that all the checkpoint functions are finished,
931 // then no need to release the mutator lock.
932 if (barrier_count == 0) {
933 return;
934 }
935 Locks::mutator_lock_->SharedUnlock(self);
936 {
937 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
938 gc_barrier_->Increment(self, barrier_count);
939 }
940 Locks::mutator_lock_->SharedLock(self);
941}
942
943void ConcurrentCopying::RevokeThreadLocalMarkStack(Thread* thread) {
944 Thread* self = Thread::Current();
945 CHECK_EQ(self, thread);
946 accounting::AtomicStack<mirror::Object>* tl_mark_stack = thread->GetThreadLocalMarkStack();
947 if (tl_mark_stack != nullptr) {
948 CHECK(is_marking_);
949 MutexLock mu(self, mark_stack_lock_);
950 revoked_mark_stacks_.push_back(tl_mark_stack);
951 thread->SetThreadLocalMarkStack(nullptr);
952 }
953}
954
955void ConcurrentCopying::ProcessMarkStack() {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800956 if (kVerboseMode) {
957 LOG(INFO) << "ProcessMarkStack. ";
958 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700959 bool empty_prev = false;
960 while (true) {
961 bool empty = ProcessMarkStackOnce();
962 if (empty_prev && empty) {
963 // Saw empty mark stack for a second time, done.
964 break;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800965 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700966 empty_prev = empty;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800967 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700968}
969
970bool ConcurrentCopying::ProcessMarkStackOnce() {
971 Thread* self = Thread::Current();
972 CHECK(thread_running_gc_ != nullptr);
973 CHECK(self == thread_running_gc_);
974 CHECK(self->GetThreadLocalMarkStack() == nullptr);
975 size_t count = 0;
976 MarkStackMode mark_stack_mode = mark_stack_mode_.LoadRelaxed();
977 if (mark_stack_mode == kMarkStackModeThreadLocal) {
978 // Process the thread-local mark stacks and the GC mark stack.
979 count += ProcessThreadLocalMarkStacks(false);
980 while (!gc_mark_stack_->IsEmpty()) {
981 mirror::Object* to_ref = gc_mark_stack_->PopBack();
982 ProcessMarkStackRef(to_ref);
983 ++count;
984 }
985 gc_mark_stack_->Reset();
986 } else if (mark_stack_mode == kMarkStackModeShared) {
987 // Process the shared GC mark stack with a lock.
988 {
989 MutexLock mu(self, mark_stack_lock_);
990 CHECK(revoked_mark_stacks_.empty());
991 }
992 while (true) {
993 std::vector<mirror::Object*> refs;
994 {
995 // Copy refs with lock. Note the number of refs should be small.
996 MutexLock mu(self, mark_stack_lock_);
997 if (gc_mark_stack_->IsEmpty()) {
998 break;
999 }
1000 for (StackReference<mirror::Object>* p = gc_mark_stack_->Begin();
1001 p != gc_mark_stack_->End(); ++p) {
1002 refs.push_back(p->AsMirrorPtr());
1003 }
1004 gc_mark_stack_->Reset();
1005 }
1006 for (mirror::Object* ref : refs) {
1007 ProcessMarkStackRef(ref);
1008 ++count;
1009 }
1010 }
1011 } else {
1012 CHECK_EQ(static_cast<uint32_t>(mark_stack_mode),
1013 static_cast<uint32_t>(kMarkStackModeGcExclusive));
1014 {
1015 MutexLock mu(self, mark_stack_lock_);
1016 CHECK(revoked_mark_stacks_.empty());
1017 }
1018 // Process the GC mark stack in the exclusive mode. No need to take the lock.
1019 while (!gc_mark_stack_->IsEmpty()) {
1020 mirror::Object* to_ref = gc_mark_stack_->PopBack();
1021 ProcessMarkStackRef(to_ref);
1022 ++count;
1023 }
1024 gc_mark_stack_->Reset();
1025 }
1026
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001027 // Return true if the stack was empty.
1028 return count == 0;
1029}
1030
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001031size_t ConcurrentCopying::ProcessThreadLocalMarkStacks(bool disable_weak_ref_access) {
1032 // Run a checkpoint to collect all thread local mark stacks and iterate over them all.
1033 RevokeThreadLocalMarkStacks(disable_weak_ref_access);
1034 size_t count = 0;
1035 std::vector<accounting::AtomicStack<mirror::Object>*> mark_stacks;
1036 {
1037 MutexLock mu(Thread::Current(), mark_stack_lock_);
1038 // Make a copy of the mark stack vector.
1039 mark_stacks = revoked_mark_stacks_;
1040 revoked_mark_stacks_.clear();
1041 }
1042 for (accounting::AtomicStack<mirror::Object>* mark_stack : mark_stacks) {
1043 for (StackReference<mirror::Object>* p = mark_stack->Begin(); p != mark_stack->End(); ++p) {
1044 mirror::Object* to_ref = p->AsMirrorPtr();
1045 ProcessMarkStackRef(to_ref);
1046 ++count;
1047 }
1048 {
1049 MutexLock mu(Thread::Current(), mark_stack_lock_);
1050 if (pooled_mark_stacks_.size() >= kMarkStackPoolSize) {
1051 // The pool has enough. Delete it.
1052 delete mark_stack;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001053 } else {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001054 // Otherwise, put it into the pool for later reuse.
1055 mark_stack->Reset();
1056 pooled_mark_stacks_.push_back(mark_stack);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001057 }
1058 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001059 }
1060 return count;
1061}
1062
1063void ConcurrentCopying::ProcessMarkStackRef(mirror::Object* to_ref) {
1064 DCHECK(!region_space_->IsInFromSpace(to_ref));
1065 if (kUseBakerReadBarrier) {
1066 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr())
1067 << " " << to_ref << " " << to_ref->GetReadBarrierPointer()
1068 << " is_marked=" << IsMarked(to_ref);
1069 }
1070 // Scan ref fields.
1071 Scan(to_ref);
1072 // Mark the gray ref as white or black.
1073 if (kUseBakerReadBarrier) {
1074 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr())
1075 << " " << to_ref << " " << to_ref->GetReadBarrierPointer()
1076 << " is_marked=" << IsMarked(to_ref);
1077 }
1078 if (to_ref->GetClass<kVerifyNone, kWithoutReadBarrier>()->IsTypeOfReferenceClass() &&
1079 to_ref->AsReference()->GetReferent<kWithoutReadBarrier>() != nullptr &&
1080 !IsInToSpace(to_ref->AsReference()->GetReferent<kWithoutReadBarrier>())) {
Hiroshi Yamauchi70c08d32015-09-10 16:01:30 -07001081 // Leave this Reference gray in the queue so that GetReferent() will trigger a read barrier. We
1082 // will change it to black or white later in ReferenceQueue::DequeuePendingReference().
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001083 CHECK(to_ref->AsReference()->IsEnqueued()) << "Left unenqueued ref gray " << to_ref;
1084 } else {
Hiroshi Yamauchi70c08d32015-09-10 16:01:30 -07001085 // We may occasionally leave a Reference black or white in the queue if its referent happens to
1086 // be concurrently marked after the Scan() call above has enqueued the Reference, in which case
1087 // the above IsInToSpace() evaluates to true and we change the color from gray to black or white
1088 // here in this else block.
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001089#ifdef USE_BAKER_OR_BROOKS_READ_BARRIER
1090 if (kUseBakerReadBarrier) {
1091 if (region_space_->IsInToSpace(to_ref)) {
1092 // If to-space, change from gray to white.
1093 bool success = to_ref->AtomicSetReadBarrierPointer(ReadBarrier::GrayPtr(),
1094 ReadBarrier::WhitePtr());
1095 CHECK(success) << "Must succeed as we won the race.";
1096 CHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::WhitePtr());
1097 } else {
1098 // If non-moving space/unevac from space, change from gray
1099 // to black. We can't change gray to white because it's not
1100 // safe to use CAS if two threads change values in opposite
1101 // directions (A->B and B->A). So, we change it to black to
1102 // indicate non-moving objects that have been marked
1103 // through. Note we'd need to change from black to white
1104 // later (concurrently).
1105 bool success = to_ref->AtomicSetReadBarrierPointer(ReadBarrier::GrayPtr(),
1106 ReadBarrier::BlackPtr());
1107 CHECK(success) << "Must succeed as we won the race.";
1108 CHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::BlackPtr());
1109 }
1110 }
1111#else
1112 DCHECK(!kUseBakerReadBarrier);
1113#endif
1114 }
1115 if (ReadBarrier::kEnableToSpaceInvariantChecks || kIsDebugBuild) {
1116 ConcurrentCopyingAssertToSpaceInvariantObjectVisitor visitor(this);
1117 visitor(to_ref);
1118 }
1119}
1120
1121void ConcurrentCopying::SwitchToSharedMarkStackMode() {
1122 Thread* self = Thread::Current();
1123 CHECK(thread_running_gc_ != nullptr);
1124 CHECK_EQ(self, thread_running_gc_);
1125 CHECK(self->GetThreadLocalMarkStack() == nullptr);
1126 MarkStackMode before_mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1127 CHECK_EQ(static_cast<uint32_t>(before_mark_stack_mode),
1128 static_cast<uint32_t>(kMarkStackModeThreadLocal));
1129 mark_stack_mode_.StoreRelaxed(kMarkStackModeShared);
1130 CHECK(weak_ref_access_enabled_.LoadRelaxed());
1131 weak_ref_access_enabled_.StoreRelaxed(false);
1132 QuasiAtomic::ThreadFenceForConstructor();
1133 // Process the thread local mark stacks one last time after switching to the shared mark stack
1134 // mode and disable weak ref accesses.
1135 ProcessThreadLocalMarkStacks(true);
1136 if (kVerboseMode) {
1137 LOG(INFO) << "Switched to shared mark stack mode and disabled weak ref access";
1138 }
1139}
1140
1141void ConcurrentCopying::SwitchToGcExclusiveMarkStackMode() {
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>(kMarkStackModeShared));
1149 mark_stack_mode_.StoreRelaxed(kMarkStackModeGcExclusive);
1150 QuasiAtomic::ThreadFenceForConstructor();
1151 if (kVerboseMode) {
1152 LOG(INFO) << "Switched to GC exclusive mark stack mode";
1153 }
1154}
1155
1156void ConcurrentCopying::CheckEmptyMarkStack() {
1157 Thread* self = Thread::Current();
1158 CHECK(thread_running_gc_ != nullptr);
1159 CHECK_EQ(self, thread_running_gc_);
1160 CHECK(self->GetThreadLocalMarkStack() == nullptr);
1161 MarkStackMode mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1162 if (mark_stack_mode == kMarkStackModeThreadLocal) {
1163 // Thread-local mark stack mode.
1164 RevokeThreadLocalMarkStacks(false);
1165 MutexLock mu(Thread::Current(), mark_stack_lock_);
1166 if (!revoked_mark_stacks_.empty()) {
1167 for (accounting::AtomicStack<mirror::Object>* mark_stack : revoked_mark_stacks_) {
1168 while (!mark_stack->IsEmpty()) {
1169 mirror::Object* obj = mark_stack->PopBack();
1170 if (kUseBakerReadBarrier) {
1171 mirror::Object* rb_ptr = obj->GetReadBarrierPointer();
1172 LOG(INFO) << "On mark queue : " << obj << " " << PrettyTypeOf(obj) << " rb_ptr=" << rb_ptr
1173 << " is_marked=" << IsMarked(obj);
1174 } else {
1175 LOG(INFO) << "On mark queue : " << obj << " " << PrettyTypeOf(obj)
1176 << " is_marked=" << IsMarked(obj);
1177 }
1178 }
1179 }
1180 LOG(FATAL) << "mark stack is not empty";
1181 }
1182 } else {
1183 // Shared, GC-exclusive, or off.
1184 MutexLock mu(Thread::Current(), mark_stack_lock_);
1185 CHECK(gc_mark_stack_->IsEmpty());
1186 CHECK(revoked_mark_stacks_.empty());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001187 }
1188}
1189
1190void ConcurrentCopying::SweepSystemWeaks(Thread* self) {
1191 TimingLogger::ScopedTiming split("SweepSystemWeaks", GetTimings());
1192 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier97509952015-07-13 14:35:43 -07001193 Runtime::Current()->SweepSystemWeaks(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001194}
1195
1196void ConcurrentCopying::Sweep(bool swap_bitmaps) {
1197 {
1198 TimingLogger::ScopedTiming t("MarkStackAsLive", GetTimings());
1199 accounting::ObjectStack* live_stack = heap_->GetLiveStack();
1200 if (kEnableFromSpaceAccountingCheck) {
1201 CHECK_GE(live_stack_freeze_size_, live_stack->Size());
1202 }
1203 heap_->MarkAllocStackAsLive(live_stack);
1204 live_stack->Reset();
1205 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001206 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001207 TimingLogger::ScopedTiming split("Sweep", GetTimings());
1208 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
1209 if (space->IsContinuousMemMapAllocSpace()) {
1210 space::ContinuousMemMapAllocSpace* alloc_space = space->AsContinuousMemMapAllocSpace();
1211 if (space == region_space_ || immune_region_.ContainsSpace(space)) {
1212 continue;
1213 }
1214 TimingLogger::ScopedTiming split2(
1215 alloc_space->IsZygoteSpace() ? "SweepZygoteSpace" : "SweepAllocSpace", GetTimings());
1216 RecordFree(alloc_space->Sweep(swap_bitmaps));
1217 }
1218 }
1219 SweepLargeObjects(swap_bitmaps);
1220}
1221
1222void ConcurrentCopying::SweepLargeObjects(bool swap_bitmaps) {
1223 TimingLogger::ScopedTiming split("SweepLargeObjects", GetTimings());
1224 RecordFreeLOS(heap_->GetLargeObjectsSpace()->Sweep(swap_bitmaps));
1225}
1226
1227class ConcurrentCopyingClearBlackPtrsVisitor {
1228 public:
1229 explicit ConcurrentCopyingClearBlackPtrsVisitor(ConcurrentCopying* cc)
1230 : collector_(cc) {}
Andreas Gampe65b798e2015-04-06 09:35:22 -07001231#ifndef USE_BAKER_OR_BROOKS_READ_BARRIER
1232 NO_RETURN
1233#endif
Mathieu Chartier90443472015-07-16 20:32:27 -07001234 void operator()(mirror::Object* obj) const SHARED_REQUIRES(Locks::mutator_lock_)
1235 SHARED_REQUIRES(Locks::heap_bitmap_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001236 DCHECK(obj != nullptr);
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08001237 DCHECK(collector_->heap_->GetMarkBitmap()->Test(obj)) << obj;
1238 DCHECK_EQ(obj->GetReadBarrierPointer(), ReadBarrier::BlackPtr()) << obj;
Hiroshi Yamauchi60f63f52015-04-23 16:12:40 -07001239 obj->AtomicSetReadBarrierPointer(ReadBarrier::BlackPtr(), ReadBarrier::WhitePtr());
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08001240 DCHECK_EQ(obj->GetReadBarrierPointer(), ReadBarrier::WhitePtr()) << obj;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001241 }
1242
1243 private:
1244 ConcurrentCopying* const collector_;
1245};
1246
1247// Clear the black ptrs in non-moving objects back to white.
1248void ConcurrentCopying::ClearBlackPtrs() {
1249 CHECK(kUseBakerReadBarrier);
1250 TimingLogger::ScopedTiming split("ClearBlackPtrs", GetTimings());
1251 ConcurrentCopyingClearBlackPtrsVisitor visitor(this);
1252 for (auto& space : heap_->GetContinuousSpaces()) {
1253 if (space == region_space_) {
1254 continue;
1255 }
1256 accounting::ContinuousSpaceBitmap* mark_bitmap = space->GetMarkBitmap();
1257 if (kVerboseMode) {
1258 LOG(INFO) << "ClearBlackPtrs: " << *space << " bitmap: " << *mark_bitmap;
1259 }
1260 mark_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()),
1261 reinterpret_cast<uintptr_t>(space->Limit()),
1262 visitor);
1263 }
1264 space::LargeObjectSpace* large_object_space = heap_->GetLargeObjectsSpace();
1265 large_object_space->GetMarkBitmap()->VisitMarkedRange(
1266 reinterpret_cast<uintptr_t>(large_object_space->Begin()),
1267 reinterpret_cast<uintptr_t>(large_object_space->End()),
1268 visitor);
1269 // Objects on the allocation stack?
1270 if (ReadBarrier::kEnableReadBarrierInvariantChecks || kIsDebugBuild) {
1271 size_t count = GetAllocationStack()->Size();
Mathieu Chartiercb535da2015-01-23 13:50:03 -08001272 auto* it = GetAllocationStack()->Begin();
1273 auto* end = GetAllocationStack()->End();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001274 for (size_t i = 0; i < count; ++i, ++it) {
Mathieu Chartiercb535da2015-01-23 13:50:03 -08001275 CHECK_LT(it, end);
1276 mirror::Object* obj = it->AsMirrorPtr();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001277 if (obj != nullptr) {
1278 // Must have been cleared above.
Mathieu Chartiercb535da2015-01-23 13:50:03 -08001279 CHECK_EQ(obj->GetReadBarrierPointer(), ReadBarrier::WhitePtr()) << obj;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001280 }
1281 }
1282 }
1283}
1284
1285void ConcurrentCopying::ReclaimPhase() {
1286 TimingLogger::ScopedTiming split("ReclaimPhase", GetTimings());
1287 if (kVerboseMode) {
1288 LOG(INFO) << "GC ReclaimPhase";
1289 }
1290 Thread* self = Thread::Current();
1291
1292 {
1293 // Double-check that the mark stack is empty.
1294 // Note: need to set this after VerifyNoFromSpaceRef().
1295 is_asserting_to_space_invariant_ = false;
1296 QuasiAtomic::ThreadFenceForConstructor();
1297 if (kVerboseMode) {
1298 LOG(INFO) << "Issue an empty check point. ";
1299 }
1300 IssueEmptyCheckpoint();
1301 // Disable the check.
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001302 is_mark_stack_push_disallowed_.StoreSequentiallyConsistent(0);
1303 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001304 }
1305
1306 {
1307 // Record freed objects.
1308 TimingLogger::ScopedTiming split2("RecordFree", GetTimings());
1309 // Don't include thread-locals that are in the to-space.
1310 uint64_t from_bytes = region_space_->GetBytesAllocatedInFromSpace();
1311 uint64_t from_objects = region_space_->GetObjectsAllocatedInFromSpace();
1312 uint64_t unevac_from_bytes = region_space_->GetBytesAllocatedInUnevacFromSpace();
1313 uint64_t unevac_from_objects = region_space_->GetObjectsAllocatedInUnevacFromSpace();
1314 uint64_t to_bytes = bytes_moved_.LoadSequentiallyConsistent();
1315 uint64_t to_objects = objects_moved_.LoadSequentiallyConsistent();
1316 if (kEnableFromSpaceAccountingCheck) {
1317 CHECK_EQ(from_space_num_objects_at_first_pause_, from_objects + unevac_from_objects);
1318 CHECK_EQ(from_space_num_bytes_at_first_pause_, from_bytes + unevac_from_bytes);
1319 }
1320 CHECK_LE(to_objects, from_objects);
1321 CHECK_LE(to_bytes, from_bytes);
1322 int64_t freed_bytes = from_bytes - to_bytes;
1323 int64_t freed_objects = from_objects - to_objects;
1324 if (kVerboseMode) {
1325 LOG(INFO) << "RecordFree:"
1326 << " from_bytes=" << from_bytes << " from_objects=" << from_objects
1327 << " unevac_from_bytes=" << unevac_from_bytes << " unevac_from_objects=" << unevac_from_objects
1328 << " to_bytes=" << to_bytes << " to_objects=" << to_objects
1329 << " freed_bytes=" << freed_bytes << " freed_objects=" << freed_objects
1330 << " from_space size=" << region_space_->FromSpaceSize()
1331 << " unevac_from_space size=" << region_space_->UnevacFromSpaceSize()
1332 << " to_space size=" << region_space_->ToSpaceSize();
1333 LOG(INFO) << "(before) num_bytes_allocated=" << heap_->num_bytes_allocated_.LoadSequentiallyConsistent();
1334 }
1335 RecordFree(ObjectBytePair(freed_objects, freed_bytes));
1336 if (kVerboseMode) {
1337 LOG(INFO) << "(after) num_bytes_allocated=" << heap_->num_bytes_allocated_.LoadSequentiallyConsistent();
1338 }
1339 }
1340
1341 {
1342 TimingLogger::ScopedTiming split3("ComputeUnevacFromSpaceLiveRatio", GetTimings());
1343 ComputeUnevacFromSpaceLiveRatio();
1344 }
1345
1346 {
1347 TimingLogger::ScopedTiming split4("ClearFromSpace", GetTimings());
1348 region_space_->ClearFromSpace();
1349 }
1350
1351 {
1352 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1353 if (kUseBakerReadBarrier) {
1354 ClearBlackPtrs();
1355 }
1356 Sweep(false);
1357 SwapBitmaps();
1358 heap_->UnBindBitmaps();
1359
1360 // Remove bitmaps for the immune spaces.
1361 while (!cc_bitmaps_.empty()) {
1362 accounting::ContinuousSpaceBitmap* cc_bitmap = cc_bitmaps_.back();
1363 cc_heap_bitmap_->RemoveContinuousSpaceBitmap(cc_bitmap);
1364 delete cc_bitmap;
1365 cc_bitmaps_.pop_back();
1366 }
1367 region_space_bitmap_ = nullptr;
1368 }
1369
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001370 CheckEmptyMarkStack();
1371
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001372 if (kVerboseMode) {
1373 LOG(INFO) << "GC end of ReclaimPhase";
1374 }
1375}
1376
1377class ConcurrentCopyingComputeUnevacFromSpaceLiveRatioVisitor {
1378 public:
1379 explicit ConcurrentCopyingComputeUnevacFromSpaceLiveRatioVisitor(ConcurrentCopying* cc)
1380 : collector_(cc) {}
Mathieu Chartier90443472015-07-16 20:32:27 -07001381 void operator()(mirror::Object* ref) const SHARED_REQUIRES(Locks::mutator_lock_)
1382 SHARED_REQUIRES(Locks::heap_bitmap_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001383 DCHECK(ref != nullptr);
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08001384 DCHECK(collector_->region_space_bitmap_->Test(ref)) << ref;
1385 DCHECK(collector_->region_space_->IsInUnevacFromSpace(ref)) << ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001386 if (kUseBakerReadBarrier) {
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08001387 DCHECK_EQ(ref->GetReadBarrierPointer(), ReadBarrier::BlackPtr()) << ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001388 // Clear the black ptr.
Hiroshi Yamauchi60f63f52015-04-23 16:12:40 -07001389 ref->AtomicSetReadBarrierPointer(ReadBarrier::BlackPtr(), ReadBarrier::WhitePtr());
1390 DCHECK_EQ(ref->GetReadBarrierPointer(), ReadBarrier::WhitePtr()) << ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001391 }
1392 size_t obj_size = ref->SizeOf();
1393 size_t alloc_size = RoundUp(obj_size, space::RegionSpace::kAlignment);
1394 collector_->region_space_->AddLiveBytes(ref, alloc_size);
1395 }
1396
1397 private:
Mathieu Chartier97509952015-07-13 14:35:43 -07001398 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001399};
1400
1401// Compute how much live objects are left in regions.
1402void ConcurrentCopying::ComputeUnevacFromSpaceLiveRatio() {
1403 region_space_->AssertAllRegionLiveBytesZeroOrCleared();
1404 ConcurrentCopyingComputeUnevacFromSpaceLiveRatioVisitor visitor(this);
1405 region_space_bitmap_->VisitMarkedRange(reinterpret_cast<uintptr_t>(region_space_->Begin()),
1406 reinterpret_cast<uintptr_t>(region_space_->Limit()),
1407 visitor);
1408}
1409
1410// Assert the to-space invariant.
1411void ConcurrentCopying::AssertToSpaceInvariant(mirror::Object* obj, MemberOffset offset,
1412 mirror::Object* ref) {
1413 CHECK(heap_->collector_type_ == kCollectorTypeCC) << static_cast<size_t>(heap_->collector_type_);
1414 if (is_asserting_to_space_invariant_) {
1415 if (region_space_->IsInToSpace(ref)) {
1416 // OK.
1417 return;
1418 } else if (region_space_->IsInUnevacFromSpace(ref)) {
1419 CHECK(region_space_bitmap_->Test(ref)) << ref;
1420 } else if (region_space_->IsInFromSpace(ref)) {
1421 // Not OK. Do extra logging.
1422 if (obj != nullptr) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001423 LogFromSpaceRefHolder(obj, offset);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001424 }
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001425 ref->GetLockWord(false).Dump(LOG(INTERNAL_FATAL));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001426 CHECK(false) << "Found from-space ref " << ref << " " << PrettyTypeOf(ref);
1427 } else {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001428 AssertToSpaceInvariantInNonMovingSpace(obj, ref);
1429 }
1430 }
1431}
1432
1433class RootPrinter {
1434 public:
1435 RootPrinter() { }
1436
1437 template <class MirrorType>
1438 ALWAYS_INLINE void VisitRootIfNonNull(mirror::CompressedReference<MirrorType>* root)
Mathieu Chartier90443472015-07-16 20:32:27 -07001439 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001440 if (!root->IsNull()) {
1441 VisitRoot(root);
1442 }
1443 }
1444
1445 template <class MirrorType>
1446 void VisitRoot(mirror::Object** root)
Mathieu Chartier90443472015-07-16 20:32:27 -07001447 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001448 LOG(INTERNAL_FATAL) << "root=" << root << " ref=" << *root;
1449 }
1450
1451 template <class MirrorType>
1452 void VisitRoot(mirror::CompressedReference<MirrorType>* root)
Mathieu Chartier90443472015-07-16 20:32:27 -07001453 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001454 LOG(INTERNAL_FATAL) << "root=" << root << " ref=" << root->AsMirrorPtr();
1455 }
1456};
1457
1458void ConcurrentCopying::AssertToSpaceInvariant(GcRootSource* gc_root_source,
1459 mirror::Object* ref) {
1460 CHECK(heap_->collector_type_ == kCollectorTypeCC) << static_cast<size_t>(heap_->collector_type_);
1461 if (is_asserting_to_space_invariant_) {
1462 if (region_space_->IsInToSpace(ref)) {
1463 // OK.
1464 return;
1465 } else if (region_space_->IsInUnevacFromSpace(ref)) {
1466 CHECK(region_space_bitmap_->Test(ref)) << ref;
1467 } else if (region_space_->IsInFromSpace(ref)) {
1468 // Not OK. Do extra logging.
1469 if (gc_root_source == nullptr) {
1470 // No info.
1471 } else if (gc_root_source->HasArtField()) {
1472 ArtField* field = gc_root_source->GetArtField();
1473 LOG(INTERNAL_FATAL) << "gc root in field " << field << " " << PrettyField(field);
1474 RootPrinter root_printer;
1475 field->VisitRoots(root_printer);
1476 } else if (gc_root_source->HasArtMethod()) {
1477 ArtMethod* method = gc_root_source->GetArtMethod();
1478 LOG(INTERNAL_FATAL) << "gc root in method " << method << " " << PrettyMethod(method);
1479 RootPrinter root_printer;
Mathieu Chartier1147b9b2015-09-14 18:50:08 -07001480 method->VisitRoots(root_printer, sizeof(void*));
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001481 }
1482 ref->GetLockWord(false).Dump(LOG(INTERNAL_FATAL));
1483 region_space_->DumpNonFreeRegions(LOG(INTERNAL_FATAL));
1484 PrintFileToLog("/proc/self/maps", LogSeverity::INTERNAL_FATAL);
1485 MemMap::DumpMaps(LOG(INTERNAL_FATAL), true);
1486 CHECK(false) << "Found from-space ref " << ref << " " << PrettyTypeOf(ref);
1487 } else {
1488 AssertToSpaceInvariantInNonMovingSpace(nullptr, ref);
1489 }
1490 }
1491}
1492
1493void ConcurrentCopying::LogFromSpaceRefHolder(mirror::Object* obj, MemberOffset offset) {
1494 if (kUseBakerReadBarrier) {
1495 LOG(INFO) << "holder=" << obj << " " << PrettyTypeOf(obj)
1496 << " holder rb_ptr=" << obj->GetReadBarrierPointer();
1497 } else {
1498 LOG(INFO) << "holder=" << obj << " " << PrettyTypeOf(obj);
1499 }
1500 if (region_space_->IsInFromSpace(obj)) {
1501 LOG(INFO) << "holder is in the from-space.";
1502 } else if (region_space_->IsInToSpace(obj)) {
1503 LOG(INFO) << "holder is in the to-space.";
1504 } else if (region_space_->IsInUnevacFromSpace(obj)) {
1505 LOG(INFO) << "holder is in the unevac from-space.";
1506 if (region_space_bitmap_->Test(obj)) {
1507 LOG(INFO) << "holder is marked in the region space bitmap.";
1508 } else {
1509 LOG(INFO) << "holder is not marked in the region space bitmap.";
1510 }
1511 } else {
1512 // In a non-moving space.
1513 if (immune_region_.ContainsObject(obj)) {
1514 LOG(INFO) << "holder is in the image or the zygote space.";
1515 accounting::ContinuousSpaceBitmap* cc_bitmap =
1516 cc_heap_bitmap_->GetContinuousSpaceBitmap(obj);
1517 CHECK(cc_bitmap != nullptr)
1518 << "An immune space object must have a bitmap.";
1519 if (cc_bitmap->Test(obj)) {
1520 LOG(INFO) << "holder is marked in the bit map.";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001521 } else {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001522 LOG(INFO) << "holder is NOT marked in the bit map.";
1523 }
1524 } else {
1525 LOG(INFO) << "holder is in a non-moving (or main) space.";
1526 accounting::ContinuousSpaceBitmap* mark_bitmap =
1527 heap_mark_bitmap_->GetContinuousSpaceBitmap(obj);
1528 accounting::LargeObjectBitmap* los_bitmap =
1529 heap_mark_bitmap_->GetLargeObjectBitmap(obj);
1530 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
1531 bool is_los = mark_bitmap == nullptr;
1532 if (!is_los && mark_bitmap->Test(obj)) {
1533 LOG(INFO) << "holder is marked in the mark bit map.";
1534 } else if (is_los && los_bitmap->Test(obj)) {
1535 LOG(INFO) << "holder is marked in the los bit map.";
1536 } else {
1537 // If ref is on the allocation stack, then it is considered
1538 // mark/alive (but not necessarily on the live stack.)
1539 if (IsOnAllocStack(obj)) {
1540 LOG(INFO) << "holder is on the alloc stack.";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001541 } else {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001542 LOG(INFO) << "holder is not marked or on the alloc stack.";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001543 }
1544 }
1545 }
1546 }
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001547 LOG(INFO) << "offset=" << offset.SizeValue();
1548}
1549
1550void ConcurrentCopying::AssertToSpaceInvariantInNonMovingSpace(mirror::Object* obj,
1551 mirror::Object* ref) {
1552 // In a non-moving spaces. Check that the ref is marked.
1553 if (immune_region_.ContainsObject(ref)) {
1554 accounting::ContinuousSpaceBitmap* cc_bitmap =
1555 cc_heap_bitmap_->GetContinuousSpaceBitmap(ref);
1556 CHECK(cc_bitmap != nullptr)
1557 << "An immune space ref must have a bitmap. " << ref;
1558 if (kUseBakerReadBarrier) {
1559 CHECK(cc_bitmap->Test(ref))
1560 << "Unmarked immune space ref. obj=" << obj << " rb_ptr="
1561 << obj->GetReadBarrierPointer() << " ref=" << ref;
1562 } else {
1563 CHECK(cc_bitmap->Test(ref))
1564 << "Unmarked immune space ref. obj=" << obj << " ref=" << ref;
1565 }
1566 } else {
1567 accounting::ContinuousSpaceBitmap* mark_bitmap =
1568 heap_mark_bitmap_->GetContinuousSpaceBitmap(ref);
1569 accounting::LargeObjectBitmap* los_bitmap =
1570 heap_mark_bitmap_->GetLargeObjectBitmap(ref);
1571 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
1572 bool is_los = mark_bitmap == nullptr;
1573 if ((!is_los && mark_bitmap->Test(ref)) ||
1574 (is_los && los_bitmap->Test(ref))) {
1575 // OK.
1576 } else {
1577 // If ref is on the allocation stack, then it may not be
1578 // marked live, but considered marked/alive (but not
1579 // necessarily on the live stack).
1580 CHECK(IsOnAllocStack(ref)) << "Unmarked ref that's not on the allocation stack. "
1581 << "obj=" << obj << " ref=" << ref;
1582 }
1583 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001584}
1585
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001586// Used to scan ref fields of an object.
1587class ConcurrentCopyingRefFieldsVisitor {
1588 public:
1589 explicit ConcurrentCopyingRefFieldsVisitor(ConcurrentCopying* collector)
1590 : collector_(collector) {}
1591
1592 void operator()(mirror::Object* obj, MemberOffset offset, bool /* is_static */)
Mathieu Chartier90443472015-07-16 20:32:27 -07001593 const ALWAYS_INLINE SHARED_REQUIRES(Locks::mutator_lock_)
1594 SHARED_REQUIRES(Locks::heap_bitmap_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001595 collector_->Process(obj, offset);
1596 }
1597
1598 void operator()(mirror::Class* klass, mirror::Reference* ref) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001599 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001600 CHECK(klass->IsTypeOfReferenceClass());
1601 collector_->DelayReferenceReferent(klass, ref);
1602 }
1603
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001604 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
1605 SHARED_REQUIRES(Locks::mutator_lock_) {
1606 if (!root->IsNull()) {
1607 VisitRoot(root);
1608 }
1609 }
1610
1611 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
1612 SHARED_REQUIRES(Locks::mutator_lock_) {
1613 collector_->MarkRoot(root);
1614 }
1615
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001616 private:
1617 ConcurrentCopying* const collector_;
1618};
1619
1620// Scan ref fields of an object.
1621void ConcurrentCopying::Scan(mirror::Object* to_ref) {
1622 DCHECK(!region_space_->IsInFromSpace(to_ref));
1623 ConcurrentCopyingRefFieldsVisitor visitor(this);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07001624 to_ref->VisitReferences(visitor, visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001625}
1626
1627// Process a field.
1628inline void ConcurrentCopying::Process(mirror::Object* obj, MemberOffset offset) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001629 mirror::Object* ref = obj->GetFieldObject<
1630 mirror::Object, kVerifyNone, kWithoutReadBarrier, false>(offset);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001631 if (ref == nullptr || region_space_->IsInToSpace(ref)) {
1632 return;
1633 }
1634 mirror::Object* to_ref = Mark(ref);
1635 if (to_ref == ref) {
1636 return;
1637 }
1638 // This may fail if the mutator writes to the field at the same time. But it's ok.
1639 mirror::Object* expected_ref = ref;
1640 mirror::Object* new_ref = to_ref;
1641 do {
1642 if (expected_ref !=
1643 obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier, false>(offset)) {
1644 // It was updated by the mutator.
1645 break;
1646 }
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001647 } while (!obj->CasFieldWeakSequentiallyConsistentObjectWithoutWriteBarrier<
1648 false, false, kVerifyNone>(offset, expected_ref, new_ref));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001649}
1650
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001651// Process some roots.
1652void ConcurrentCopying::VisitRoots(
1653 mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED) {
1654 for (size_t i = 0; i < count; ++i) {
1655 mirror::Object** root = roots[i];
1656 mirror::Object* ref = *root;
1657 if (ref == nullptr || region_space_->IsInToSpace(ref)) {
Mathieu Chartier4809d0a2015-04-07 10:39:04 -07001658 continue;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001659 }
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001660 mirror::Object* to_ref = Mark(ref);
1661 if (to_ref == ref) {
Mathieu Chartier4809d0a2015-04-07 10:39:04 -07001662 continue;
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001663 }
1664 Atomic<mirror::Object*>* addr = reinterpret_cast<Atomic<mirror::Object*>*>(root);
1665 mirror::Object* expected_ref = ref;
1666 mirror::Object* new_ref = to_ref;
1667 do {
1668 if (expected_ref != addr->LoadRelaxed()) {
1669 // It was updated by the mutator.
1670 break;
1671 }
1672 } while (!addr->CompareExchangeWeakSequentiallyConsistent(expected_ref, new_ref));
1673 }
1674}
1675
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001676void ConcurrentCopying::MarkRoot(mirror::CompressedReference<mirror::Object>* root) {
1677 DCHECK(!root->IsNull());
1678 mirror::Object* const ref = root->AsMirrorPtr();
1679 if (region_space_->IsInToSpace(ref)) {
1680 return;
1681 }
1682 mirror::Object* to_ref = Mark(ref);
1683 if (to_ref != ref) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001684 auto* addr = reinterpret_cast<Atomic<mirror::CompressedReference<mirror::Object>>*>(root);
1685 auto expected_ref = mirror::CompressedReference<mirror::Object>::FromMirrorPtr(ref);
1686 auto new_ref = mirror::CompressedReference<mirror::Object>::FromMirrorPtr(to_ref);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001687 // If the cas fails, then it was updated by the mutator.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001688 do {
1689 if (ref != addr->LoadRelaxed().AsMirrorPtr()) {
1690 // It was updated by the mutator.
1691 break;
1692 }
1693 } while (!addr->CompareExchangeWeakSequentiallyConsistent(expected_ref, new_ref));
1694 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001695}
1696
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001697void ConcurrentCopying::VisitRoots(
1698 mirror::CompressedReference<mirror::Object>** roots, size_t count,
1699 const RootInfo& info ATTRIBUTE_UNUSED) {
1700 for (size_t i = 0; i < count; ++i) {
1701 mirror::CompressedReference<mirror::Object>* const root = roots[i];
1702 if (!root->IsNull()) {
1703 MarkRoot(root);
1704 }
1705 }
1706}
1707
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001708// Fill the given memory block with a dummy object. Used to fill in a
1709// copy of objects that was lost in race.
1710void ConcurrentCopying::FillWithDummyObject(mirror::Object* dummy_obj, size_t byte_size) {
Roland Levillain14d90572015-07-16 10:52:26 +01001711 CHECK_ALIGNED(byte_size, kObjectAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001712 memset(dummy_obj, 0, byte_size);
1713 mirror::Class* int_array_class = mirror::IntArray::GetArrayClass();
1714 CHECK(int_array_class != nullptr);
1715 AssertToSpaceInvariant(nullptr, MemberOffset(0), int_array_class);
1716 size_t component_size = int_array_class->GetComponentSize();
1717 CHECK_EQ(component_size, sizeof(int32_t));
1718 size_t data_offset = mirror::Array::DataOffset(component_size).SizeValue();
1719 if (data_offset > byte_size) {
1720 // An int array is too big. Use java.lang.Object.
1721 mirror::Class* java_lang_Object = WellKnownClasses::ToClass(WellKnownClasses::java_lang_Object);
1722 AssertToSpaceInvariant(nullptr, MemberOffset(0), java_lang_Object);
1723 CHECK_EQ(byte_size, java_lang_Object->GetObjectSize());
1724 dummy_obj->SetClass(java_lang_Object);
1725 CHECK_EQ(byte_size, dummy_obj->SizeOf());
1726 } else {
1727 // Use an int array.
1728 dummy_obj->SetClass(int_array_class);
1729 CHECK(dummy_obj->IsArrayInstance());
1730 int32_t length = (byte_size - data_offset) / component_size;
1731 dummy_obj->AsArray()->SetLength(length);
1732 CHECK_EQ(dummy_obj->AsArray()->GetLength(), length)
1733 << "byte_size=" << byte_size << " length=" << length
1734 << " component_size=" << component_size << " data_offset=" << data_offset;
1735 CHECK_EQ(byte_size, dummy_obj->SizeOf())
1736 << "byte_size=" << byte_size << " length=" << length
1737 << " component_size=" << component_size << " data_offset=" << data_offset;
1738 }
1739}
1740
1741// Reuse the memory blocks that were copy of objects that were lost in race.
1742mirror::Object* ConcurrentCopying::AllocateInSkippedBlock(size_t alloc_size) {
1743 // Try to reuse the blocks that were unused due to CAS failures.
Roland Levillain14d90572015-07-16 10:52:26 +01001744 CHECK_ALIGNED(alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001745 Thread* self = Thread::Current();
1746 size_t min_object_size = RoundUp(sizeof(mirror::Object), space::RegionSpace::kAlignment);
1747 MutexLock mu(self, skipped_blocks_lock_);
1748 auto it = skipped_blocks_map_.lower_bound(alloc_size);
1749 if (it == skipped_blocks_map_.end()) {
1750 // Not found.
1751 return nullptr;
1752 }
1753 {
1754 size_t byte_size = it->first;
1755 CHECK_GE(byte_size, alloc_size);
1756 if (byte_size > alloc_size && byte_size - alloc_size < min_object_size) {
1757 // If remainder would be too small for a dummy object, retry with a larger request size.
1758 it = skipped_blocks_map_.lower_bound(alloc_size + min_object_size);
1759 if (it == skipped_blocks_map_.end()) {
1760 // Not found.
1761 return nullptr;
1762 }
Roland Levillain14d90572015-07-16 10:52:26 +01001763 CHECK_ALIGNED(it->first - alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001764 CHECK_GE(it->first - alloc_size, min_object_size)
1765 << "byte_size=" << byte_size << " it->first=" << it->first << " alloc_size=" << alloc_size;
1766 }
1767 }
1768 // Found a block.
1769 CHECK(it != skipped_blocks_map_.end());
1770 size_t byte_size = it->first;
1771 uint8_t* addr = it->second;
1772 CHECK_GE(byte_size, alloc_size);
1773 CHECK(region_space_->IsInToSpace(reinterpret_cast<mirror::Object*>(addr)));
Roland Levillain14d90572015-07-16 10:52:26 +01001774 CHECK_ALIGNED(byte_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001775 if (kVerboseMode) {
1776 LOG(INFO) << "Reusing skipped bytes : " << reinterpret_cast<void*>(addr) << ", " << byte_size;
1777 }
1778 skipped_blocks_map_.erase(it);
1779 memset(addr, 0, byte_size);
1780 if (byte_size > alloc_size) {
1781 // Return the remainder to the map.
Roland Levillain14d90572015-07-16 10:52:26 +01001782 CHECK_ALIGNED(byte_size - alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001783 CHECK_GE(byte_size - alloc_size, min_object_size);
1784 FillWithDummyObject(reinterpret_cast<mirror::Object*>(addr + alloc_size),
1785 byte_size - alloc_size);
1786 CHECK(region_space_->IsInToSpace(reinterpret_cast<mirror::Object*>(addr + alloc_size)));
1787 skipped_blocks_map_.insert(std::make_pair(byte_size - alloc_size, addr + alloc_size));
1788 }
1789 return reinterpret_cast<mirror::Object*>(addr);
1790}
1791
1792mirror::Object* ConcurrentCopying::Copy(mirror::Object* from_ref) {
1793 DCHECK(region_space_->IsInFromSpace(from_ref));
1794 // No read barrier to avoid nested RB that might violate the to-space
1795 // invariant. Note that from_ref is a from space ref so the SizeOf()
1796 // call will access the from-space meta objects, but it's ok and necessary.
1797 size_t obj_size = from_ref->SizeOf<kDefaultVerifyFlags, kWithoutReadBarrier>();
1798 size_t region_space_alloc_size = RoundUp(obj_size, space::RegionSpace::kAlignment);
1799 size_t region_space_bytes_allocated = 0U;
1800 size_t non_moving_space_bytes_allocated = 0U;
1801 size_t bytes_allocated = 0U;
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001802 size_t dummy;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001803 mirror::Object* to_ref = region_space_->AllocNonvirtual<true>(
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001804 region_space_alloc_size, &region_space_bytes_allocated, nullptr, &dummy);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001805 bytes_allocated = region_space_bytes_allocated;
1806 if (to_ref != nullptr) {
1807 DCHECK_EQ(region_space_alloc_size, region_space_bytes_allocated);
1808 }
1809 bool fall_back_to_non_moving = false;
1810 if (UNLIKELY(to_ref == nullptr)) {
1811 // Failed to allocate in the region space. Try the skipped blocks.
1812 to_ref = AllocateInSkippedBlock(region_space_alloc_size);
1813 if (to_ref != nullptr) {
1814 // Succeeded to allocate in a skipped block.
1815 if (heap_->use_tlab_) {
1816 // This is necessary for the tlab case as it's not accounted in the space.
1817 region_space_->RecordAlloc(to_ref);
1818 }
1819 bytes_allocated = region_space_alloc_size;
1820 } else {
1821 // Fall back to the non-moving space.
1822 fall_back_to_non_moving = true;
1823 if (kVerboseMode) {
1824 LOG(INFO) << "Out of memory in the to-space. Fall back to non-moving. skipped_bytes="
1825 << to_space_bytes_skipped_.LoadSequentiallyConsistent()
1826 << " skipped_objects=" << to_space_objects_skipped_.LoadSequentiallyConsistent();
1827 }
1828 fall_back_to_non_moving = true;
1829 to_ref = heap_->non_moving_space_->Alloc(Thread::Current(), obj_size,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001830 &non_moving_space_bytes_allocated, nullptr, &dummy);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001831 CHECK(to_ref != nullptr) << "Fall-back non-moving space allocation failed";
1832 bytes_allocated = non_moving_space_bytes_allocated;
1833 // Mark it in the mark bitmap.
1834 accounting::ContinuousSpaceBitmap* mark_bitmap =
1835 heap_mark_bitmap_->GetContinuousSpaceBitmap(to_ref);
1836 CHECK(mark_bitmap != nullptr);
1837 CHECK(!mark_bitmap->AtomicTestAndSet(to_ref));
1838 }
1839 }
1840 DCHECK(to_ref != nullptr);
1841
1842 // Attempt to install the forward pointer. This is in a loop as the
1843 // lock word atomic write can fail.
1844 while (true) {
1845 // Copy the object. TODO: copy only the lockword in the second iteration and on?
1846 memcpy(to_ref, from_ref, obj_size);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001847
1848 LockWord old_lock_word = to_ref->GetLockWord(false);
1849
1850 if (old_lock_word.GetState() == LockWord::kForwardingAddress) {
1851 // Lost the race. Another thread (either GC or mutator) stored
1852 // the forwarding pointer first. Make the lost copy (to_ref)
1853 // look like a valid but dead (dummy) object and keep it for
1854 // future reuse.
1855 FillWithDummyObject(to_ref, bytes_allocated);
1856 if (!fall_back_to_non_moving) {
1857 DCHECK(region_space_->IsInToSpace(to_ref));
1858 if (bytes_allocated > space::RegionSpace::kRegionSize) {
1859 // Free the large alloc.
1860 region_space_->FreeLarge(to_ref, bytes_allocated);
1861 } else {
1862 // Record the lost copy for later reuse.
1863 heap_->num_bytes_allocated_.FetchAndAddSequentiallyConsistent(bytes_allocated);
1864 to_space_bytes_skipped_.FetchAndAddSequentiallyConsistent(bytes_allocated);
1865 to_space_objects_skipped_.FetchAndAddSequentiallyConsistent(1);
1866 MutexLock mu(Thread::Current(), skipped_blocks_lock_);
1867 skipped_blocks_map_.insert(std::make_pair(bytes_allocated,
1868 reinterpret_cast<uint8_t*>(to_ref)));
1869 }
1870 } else {
1871 DCHECK(heap_->non_moving_space_->HasAddress(to_ref));
1872 DCHECK_EQ(bytes_allocated, non_moving_space_bytes_allocated);
1873 // Free the non-moving-space chunk.
1874 accounting::ContinuousSpaceBitmap* mark_bitmap =
1875 heap_mark_bitmap_->GetContinuousSpaceBitmap(to_ref);
1876 CHECK(mark_bitmap != nullptr);
1877 CHECK(mark_bitmap->Clear(to_ref));
1878 heap_->non_moving_space_->Free(Thread::Current(), to_ref);
1879 }
1880
1881 // Get the winner's forward ptr.
1882 mirror::Object* lost_fwd_ptr = to_ref;
1883 to_ref = reinterpret_cast<mirror::Object*>(old_lock_word.ForwardingAddress());
1884 CHECK(to_ref != nullptr);
1885 CHECK_NE(to_ref, lost_fwd_ptr);
1886 CHECK(region_space_->IsInToSpace(to_ref) || heap_->non_moving_space_->HasAddress(to_ref));
1887 CHECK_NE(to_ref->GetLockWord(false).GetState(), LockWord::kForwardingAddress);
1888 return to_ref;
1889 }
1890
Hiroshi Yamauchi60f63f52015-04-23 16:12:40 -07001891 // Set the gray ptr.
1892 if (kUseBakerReadBarrier) {
1893 to_ref->SetReadBarrierPointer(ReadBarrier::GrayPtr());
1894 }
1895
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001896 LockWord new_lock_word = LockWord::FromForwardingAddress(reinterpret_cast<size_t>(to_ref));
1897
1898 // Try to atomically write the fwd ptr.
1899 bool success = from_ref->CasLockWordWeakSequentiallyConsistent(old_lock_word, new_lock_word);
1900 if (LIKELY(success)) {
1901 // The CAS succeeded.
1902 objects_moved_.FetchAndAddSequentiallyConsistent(1);
1903 bytes_moved_.FetchAndAddSequentiallyConsistent(region_space_alloc_size);
1904 if (LIKELY(!fall_back_to_non_moving)) {
1905 DCHECK(region_space_->IsInToSpace(to_ref));
1906 } else {
1907 DCHECK(heap_->non_moving_space_->HasAddress(to_ref));
1908 DCHECK_EQ(bytes_allocated, non_moving_space_bytes_allocated);
1909 }
1910 if (kUseBakerReadBarrier) {
1911 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr());
1912 }
1913 DCHECK(GetFwdPtr(from_ref) == to_ref);
1914 CHECK_NE(to_ref->GetLockWord(false).GetState(), LockWord::kForwardingAddress);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001915 PushOntoMarkStack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001916 return to_ref;
1917 } else {
1918 // The CAS failed. It may have lost the race or may have failed
1919 // due to monitor/hashcode ops. Either way, retry.
1920 }
1921 }
1922}
1923
1924mirror::Object* ConcurrentCopying::IsMarked(mirror::Object* from_ref) {
1925 DCHECK(from_ref != nullptr);
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08001926 space::RegionSpace::RegionType rtype = region_space_->GetRegionType(from_ref);
1927 if (rtype == space::RegionSpace::RegionType::kRegionTypeToSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001928 // It's already marked.
1929 return from_ref;
1930 }
1931 mirror::Object* to_ref;
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08001932 if (rtype == space::RegionSpace::RegionType::kRegionTypeFromSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001933 to_ref = GetFwdPtr(from_ref);
1934 DCHECK(to_ref == nullptr || region_space_->IsInToSpace(to_ref) ||
1935 heap_->non_moving_space_->HasAddress(to_ref))
1936 << "from_ref=" << from_ref << " to_ref=" << to_ref;
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08001937 } else if (rtype == space::RegionSpace::RegionType::kRegionTypeUnevacFromSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001938 if (region_space_bitmap_->Test(from_ref)) {
1939 to_ref = from_ref;
1940 } else {
1941 to_ref = nullptr;
1942 }
1943 } else {
1944 // from_ref is in a non-moving space.
1945 if (immune_region_.ContainsObject(from_ref)) {
1946 accounting::ContinuousSpaceBitmap* cc_bitmap =
1947 cc_heap_bitmap_->GetContinuousSpaceBitmap(from_ref);
1948 DCHECK(cc_bitmap != nullptr)
1949 << "An immune space object must have a bitmap";
1950 if (kIsDebugBuild) {
1951 DCHECK(heap_mark_bitmap_->GetContinuousSpaceBitmap(from_ref)->Test(from_ref))
1952 << "Immune space object must be already marked";
1953 }
1954 if (cc_bitmap->Test(from_ref)) {
1955 // Already marked.
1956 to_ref = from_ref;
1957 } else {
1958 // Newly marked.
1959 to_ref = nullptr;
1960 }
1961 } else {
1962 // Non-immune non-moving space. Use the mark bitmap.
1963 accounting::ContinuousSpaceBitmap* mark_bitmap =
1964 heap_mark_bitmap_->GetContinuousSpaceBitmap(from_ref);
1965 accounting::LargeObjectBitmap* los_bitmap =
1966 heap_mark_bitmap_->GetLargeObjectBitmap(from_ref);
1967 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
1968 bool is_los = mark_bitmap == nullptr;
1969 if (!is_los && mark_bitmap->Test(from_ref)) {
1970 // Already marked.
1971 to_ref = from_ref;
1972 } else if (is_los && los_bitmap->Test(from_ref)) {
1973 // Already marked in LOS.
1974 to_ref = from_ref;
1975 } else {
1976 // Not marked.
1977 if (IsOnAllocStack(from_ref)) {
1978 // If on the allocation stack, it's considered marked.
1979 to_ref = from_ref;
1980 } else {
1981 // Not marked.
1982 to_ref = nullptr;
1983 }
1984 }
1985 }
1986 }
1987 return to_ref;
1988}
1989
1990bool ConcurrentCopying::IsOnAllocStack(mirror::Object* ref) {
1991 QuasiAtomic::ThreadFenceAcquire();
1992 accounting::ObjectStack* alloc_stack = GetAllocationStack();
Mathieu Chartiercb535da2015-01-23 13:50:03 -08001993 return alloc_stack->Contains(ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001994}
1995
1996mirror::Object* ConcurrentCopying::Mark(mirror::Object* from_ref) {
1997 if (from_ref == nullptr) {
1998 return nullptr;
1999 }
2000 DCHECK(from_ref != nullptr);
2001 DCHECK(heap_->collector_type_ == kCollectorTypeCC);
Hiroshi Yamauchi60f63f52015-04-23 16:12:40 -07002002 if (kUseBakerReadBarrier && !is_active_) {
2003 // In the lock word forward address state, the read barrier bits
2004 // in the lock word are part of the stored forwarding address and
2005 // invalid. This is usually OK as the from-space copy of objects
2006 // aren't accessed by mutators due to the to-space
2007 // invariant. However, during the dex2oat image writing relocation
2008 // and the zygote compaction, objects can be in the forward
2009 // address state (to store the forward/relocation addresses) and
2010 // they can still be accessed and the invalid read barrier bits
2011 // are consulted. If they look like gray but aren't really, the
2012 // read barriers slow path can trigger when it shouldn't. To guard
2013 // against this, return here if the CC collector isn't running.
2014 return from_ref;
2015 }
2016 DCHECK(region_space_ != nullptr) << "Read barrier slow path taken when CC isn't running?";
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08002017 space::RegionSpace::RegionType rtype = region_space_->GetRegionType(from_ref);
2018 if (rtype == space::RegionSpace::RegionType::kRegionTypeToSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002019 // It's already marked.
2020 return from_ref;
2021 }
2022 mirror::Object* to_ref;
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08002023 if (rtype == space::RegionSpace::RegionType::kRegionTypeFromSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002024 to_ref = GetFwdPtr(from_ref);
2025 if (kUseBakerReadBarrier) {
2026 DCHECK(to_ref != ReadBarrier::GrayPtr()) << "from_ref=" << from_ref << " to_ref=" << to_ref;
2027 }
2028 if (to_ref == nullptr) {
2029 // It isn't marked yet. Mark it by copying it to the to-space.
2030 to_ref = Copy(from_ref);
2031 }
2032 DCHECK(region_space_->IsInToSpace(to_ref) || heap_->non_moving_space_->HasAddress(to_ref))
2033 << "from_ref=" << from_ref << " to_ref=" << to_ref;
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08002034 } else if (rtype == space::RegionSpace::RegionType::kRegionTypeUnevacFromSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002035 // This may or may not succeed, which is ok.
2036 if (kUseBakerReadBarrier) {
2037 from_ref->AtomicSetReadBarrierPointer(ReadBarrier::WhitePtr(), ReadBarrier::GrayPtr());
2038 }
2039 if (region_space_bitmap_->AtomicTestAndSet(from_ref)) {
2040 // Already marked.
2041 to_ref = from_ref;
2042 } else {
2043 // Newly marked.
2044 to_ref = from_ref;
2045 if (kUseBakerReadBarrier) {
2046 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr());
2047 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002048 PushOntoMarkStack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002049 }
2050 } else {
2051 // from_ref is in a non-moving space.
2052 DCHECK(!region_space_->HasAddress(from_ref)) << from_ref;
2053 if (immune_region_.ContainsObject(from_ref)) {
2054 accounting::ContinuousSpaceBitmap* cc_bitmap =
2055 cc_heap_bitmap_->GetContinuousSpaceBitmap(from_ref);
2056 DCHECK(cc_bitmap != nullptr)
2057 << "An immune space object must have a bitmap";
2058 if (kIsDebugBuild) {
2059 DCHECK(heap_mark_bitmap_->GetContinuousSpaceBitmap(from_ref)->Test(from_ref))
2060 << "Immune space object must be already marked";
2061 }
2062 // This may or may not succeed, which is ok.
2063 if (kUseBakerReadBarrier) {
2064 from_ref->AtomicSetReadBarrierPointer(ReadBarrier::WhitePtr(), ReadBarrier::GrayPtr());
2065 }
2066 if (cc_bitmap->AtomicTestAndSet(from_ref)) {
2067 // Already marked.
2068 to_ref = from_ref;
2069 } else {
2070 // Newly marked.
2071 to_ref = from_ref;
2072 if (kUseBakerReadBarrier) {
2073 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr());
2074 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002075 PushOntoMarkStack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002076 }
2077 } else {
2078 // Use the mark bitmap.
2079 accounting::ContinuousSpaceBitmap* mark_bitmap =
2080 heap_mark_bitmap_->GetContinuousSpaceBitmap(from_ref);
2081 accounting::LargeObjectBitmap* los_bitmap =
2082 heap_mark_bitmap_->GetLargeObjectBitmap(from_ref);
2083 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
2084 bool is_los = mark_bitmap == nullptr;
2085 if (!is_los && mark_bitmap->Test(from_ref)) {
2086 // Already marked.
2087 to_ref = from_ref;
2088 if (kUseBakerReadBarrier) {
2089 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr() ||
2090 to_ref->GetReadBarrierPointer() == ReadBarrier::BlackPtr());
2091 }
2092 } else if (is_los && los_bitmap->Test(from_ref)) {
2093 // Already marked in LOS.
2094 to_ref = from_ref;
2095 if (kUseBakerReadBarrier) {
2096 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr() ||
2097 to_ref->GetReadBarrierPointer() == ReadBarrier::BlackPtr());
2098 }
2099 } else {
2100 // Not marked.
2101 if (IsOnAllocStack(from_ref)) {
2102 // If it's on the allocation stack, it's considered marked. Keep it white.
2103 to_ref = from_ref;
2104 // Objects on the allocation stack need not be marked.
2105 if (!is_los) {
2106 DCHECK(!mark_bitmap->Test(to_ref));
2107 } else {
2108 DCHECK(!los_bitmap->Test(to_ref));
2109 }
2110 if (kUseBakerReadBarrier) {
2111 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::WhitePtr());
2112 }
2113 } else {
2114 // Not marked or on the allocation stack. Try to mark it.
2115 // This may or may not succeed, which is ok.
2116 if (kUseBakerReadBarrier) {
2117 from_ref->AtomicSetReadBarrierPointer(ReadBarrier::WhitePtr(), ReadBarrier::GrayPtr());
2118 }
2119 if (!is_los && mark_bitmap->AtomicTestAndSet(from_ref)) {
2120 // Already marked.
2121 to_ref = from_ref;
2122 } else if (is_los && los_bitmap->AtomicTestAndSet(from_ref)) {
2123 // Already marked in LOS.
2124 to_ref = from_ref;
2125 } else {
2126 // Newly marked.
2127 to_ref = from_ref;
2128 if (kUseBakerReadBarrier) {
2129 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr());
2130 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002131 PushOntoMarkStack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002132 }
2133 }
2134 }
2135 }
2136 }
2137 return to_ref;
2138}
2139
2140void ConcurrentCopying::FinishPhase() {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002141 {
2142 MutexLock mu(Thread::Current(), mark_stack_lock_);
2143 CHECK_EQ(pooled_mark_stacks_.size(), kMarkStackPoolSize);
2144 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002145 region_space_ = nullptr;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002146 {
2147 MutexLock mu(Thread::Current(), skipped_blocks_lock_);
2148 skipped_blocks_map_.clear();
2149 }
2150 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
2151 heap_->ClearMarkedObjects();
2152}
2153
Mathieu Chartier97509952015-07-13 14:35:43 -07002154bool ConcurrentCopying::IsMarkedHeapReference(mirror::HeapReference<mirror::Object>* field) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002155 mirror::Object* from_ref = field->AsMirrorPtr();
Mathieu Chartier97509952015-07-13 14:35:43 -07002156 mirror::Object* to_ref = IsMarked(from_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002157 if (to_ref == nullptr) {
2158 return false;
2159 }
2160 if (from_ref != to_ref) {
2161 QuasiAtomic::ThreadFenceRelease();
2162 field->Assign(to_ref);
2163 QuasiAtomic::ThreadFenceSequentiallyConsistent();
2164 }
2165 return true;
2166}
2167
Mathieu Chartier97509952015-07-13 14:35:43 -07002168mirror::Object* ConcurrentCopying::MarkObject(mirror::Object* from_ref) {
2169 return Mark(from_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002170}
2171
2172void ConcurrentCopying::DelayReferenceReferent(mirror::Class* klass, mirror::Reference* reference) {
Mathieu Chartier97509952015-07-13 14:35:43 -07002173 heap_->GetReferenceProcessor()->DelayReferenceReferent(klass, reference, this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002174}
2175
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002176void ConcurrentCopying::ProcessReferences(Thread* self) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002177 TimingLogger::ScopedTiming split("ProcessReferences", GetTimings());
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002178 // 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 -08002179 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
2180 GetHeap()->GetReferenceProcessor()->ProcessReferences(
Mathieu Chartier97509952015-07-13 14:35:43 -07002181 true /*concurrent*/, GetTimings(), GetCurrentIteration()->GetClearSoftReferences(), this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002182}
2183
2184void ConcurrentCopying::RevokeAllThreadLocalBuffers() {
2185 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
2186 region_space_->RevokeAllThreadLocalBuffers();
2187}
2188
Hiroshi Yamauchid5307ec2014-03-27 21:07:51 -07002189} // namespace collector
2190} // namespace gc
2191} // namespace art