blob: a5bc60a9124e8225e2206a938368f88893e32750 [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);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700460 // Marking is done. Disable marking.
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700461 DisableMarking();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700462 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800463 }
464
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700465 CHECK(weak_ref_access_enabled_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800466 if (kVerboseMode) {
467 LOG(INFO) << "GC end of MarkingPhase";
468 }
469}
470
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700471void ConcurrentCopying::ReenableWeakRefAccess(Thread* self) {
472 if (kVerboseMode) {
473 LOG(INFO) << "ReenableWeakRefAccess";
474 }
475 weak_ref_access_enabled_.StoreRelaxed(true); // This is for new threads.
476 QuasiAtomic::ThreadFenceForConstructor();
477 // Iterate all threads (don't need to or can't use a checkpoint) and re-enable weak ref access.
478 {
479 MutexLock mu(self, *Locks::thread_list_lock_);
480 std::list<Thread*> thread_list = Runtime::Current()->GetThreadList()->GetList();
481 for (Thread* thread : thread_list) {
482 thread->SetWeakRefAccessEnabled(true);
483 }
484 }
485 // Unblock blocking threads.
486 GetHeap()->GetReferenceProcessor()->BroadcastForSlowPath(self);
487 Runtime::Current()->BroadcastForNewSystemWeaks();
488}
489
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700490class DisableMarkingCheckpoint : public Closure {
491 public:
492 explicit DisableMarkingCheckpoint(ConcurrentCopying* concurrent_copying)
493 : concurrent_copying_(concurrent_copying) {
494 }
495
496 void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
497 // Note: self is not necessarily equal to thread since thread may be suspended.
498 Thread* self = Thread::Current();
499 DCHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
500 << thread->GetState() << " thread " << thread << " self " << self;
501 // Disable the thread-local is_gc_marking flag.
502 DCHECK(thread->GetIsGcMarking());
503 thread->SetIsGcMarking(false);
504 // If thread is a running mutator, then act on behalf of the garbage collector.
505 // See the code in ThreadList::RunCheckpoint.
506 if (thread->GetState() == kRunnable) {
507 concurrent_copying_->GetBarrier().Pass(self);
508 }
509 }
510
511 private:
512 ConcurrentCopying* const concurrent_copying_;
513};
514
515void ConcurrentCopying::IssueDisableMarkingCheckpoint() {
516 Thread* self = Thread::Current();
517 DisableMarkingCheckpoint check_point(this);
518 ThreadList* thread_list = Runtime::Current()->GetThreadList();
519 gc_barrier_->Init(self, 0);
520 size_t barrier_count = thread_list->RunCheckpoint(&check_point);
521 // If there are no threads to wait which implies that all the checkpoint functions are finished,
522 // then no need to release the mutator lock.
523 if (barrier_count == 0) {
524 return;
525 }
526 // Release locks then wait for all mutator threads to pass the barrier.
527 Locks::mutator_lock_->SharedUnlock(self);
528 {
529 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
530 gc_barrier_->Increment(self, barrier_count);
531 }
532 Locks::mutator_lock_->SharedLock(self);
533}
534
535void ConcurrentCopying::DisableMarking() {
536 // Change the global is_marking flag to false. Do a fence before doing a checkpoint to update the
537 // thread-local flags so that a new thread starting up will get the correct is_marking flag.
538 is_marking_ = false;
539 QuasiAtomic::ThreadFenceForConstructor();
540 // Use a checkpoint to turn off the thread-local is_gc_marking flags and to ensure no threads are
541 // still in the middle of a read barrier which may have a from-space ref cached in a local
542 // variable.
543 IssueDisableMarkingCheckpoint();
544 if (kUseTableLookupReadBarrier) {
545 heap_->rb_table_->ClearAll();
546 DCHECK(heap_->rb_table_->IsAllCleared());
547 }
548 is_mark_stack_push_disallowed_.StoreSequentiallyConsistent(1);
549 mark_stack_mode_.StoreSequentiallyConsistent(kMarkStackModeOff);
550}
551
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800552void ConcurrentCopying::IssueEmptyCheckpoint() {
553 Thread* self = Thread::Current();
554 EmptyCheckpoint check_point(this);
555 ThreadList* thread_list = Runtime::Current()->GetThreadList();
556 gc_barrier_->Init(self, 0);
557 size_t barrier_count = thread_list->RunCheckpoint(&check_point);
Lei Lidd9943d2015-02-02 14:24:44 +0800558 // If there are no threads to wait which implys that all the checkpoint functions are finished,
559 // then no need to release the mutator lock.
560 if (barrier_count == 0) {
561 return;
562 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800563 // Release locks then wait for all mutator threads to pass the barrier.
564 Locks::mutator_lock_->SharedUnlock(self);
565 {
566 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
567 gc_barrier_->Increment(self, barrier_count);
568 }
569 Locks::mutator_lock_->SharedLock(self);
570}
571
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800572void ConcurrentCopying::PushOntoMarkStack(mirror::Object* to_ref) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700573 CHECK_EQ(is_mark_stack_push_disallowed_.LoadRelaxed(), 0)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800574 << " " << to_ref << " " << PrettyTypeOf(to_ref);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700575 Thread* self = Thread::Current(); // TODO: pass self as an argument from call sites?
576 CHECK(thread_running_gc_ != nullptr);
577 MarkStackMode mark_stack_mode = mark_stack_mode_.LoadRelaxed();
578 if (mark_stack_mode == kMarkStackModeThreadLocal) {
579 if (self == thread_running_gc_) {
580 // If GC-running thread, use the GC mark stack instead of a thread-local mark stack.
581 CHECK(self->GetThreadLocalMarkStack() == nullptr);
582 CHECK(!gc_mark_stack_->IsFull());
583 gc_mark_stack_->PushBack(to_ref);
584 } else {
585 // Otherwise, use a thread-local mark stack.
586 accounting::AtomicStack<mirror::Object>* tl_mark_stack = self->GetThreadLocalMarkStack();
587 if (UNLIKELY(tl_mark_stack == nullptr || tl_mark_stack->IsFull())) {
588 MutexLock mu(self, mark_stack_lock_);
589 // Get a new thread local mark stack.
590 accounting::AtomicStack<mirror::Object>* new_tl_mark_stack;
591 if (!pooled_mark_stacks_.empty()) {
592 // Use a pooled mark stack.
593 new_tl_mark_stack = pooled_mark_stacks_.back();
594 pooled_mark_stacks_.pop_back();
595 } else {
596 // None pooled. Create a new one.
597 new_tl_mark_stack =
598 accounting::AtomicStack<mirror::Object>::Create(
599 "thread local mark stack", 4 * KB, 4 * KB);
600 }
601 DCHECK(new_tl_mark_stack != nullptr);
602 DCHECK(new_tl_mark_stack->IsEmpty());
603 new_tl_mark_stack->PushBack(to_ref);
604 self->SetThreadLocalMarkStack(new_tl_mark_stack);
605 if (tl_mark_stack != nullptr) {
606 // Store the old full stack into a vector.
607 revoked_mark_stacks_.push_back(tl_mark_stack);
608 }
609 } else {
610 tl_mark_stack->PushBack(to_ref);
611 }
612 }
613 } else if (mark_stack_mode == kMarkStackModeShared) {
614 // Access the shared GC mark stack with a lock.
615 MutexLock mu(self, mark_stack_lock_);
616 CHECK(!gc_mark_stack_->IsFull());
617 gc_mark_stack_->PushBack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800618 } else {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700619 CHECK_EQ(static_cast<uint32_t>(mark_stack_mode),
620 static_cast<uint32_t>(kMarkStackModeGcExclusive));
621 CHECK(self == thread_running_gc_)
622 << "Only GC-running thread should access the mark stack "
623 << "in the GC exclusive mark stack mode";
624 // Access the GC mark stack without a lock.
625 CHECK(!gc_mark_stack_->IsFull());
626 gc_mark_stack_->PushBack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800627 }
628}
629
630accounting::ObjectStack* ConcurrentCopying::GetAllocationStack() {
631 return heap_->allocation_stack_.get();
632}
633
634accounting::ObjectStack* ConcurrentCopying::GetLiveStack() {
635 return heap_->live_stack_.get();
636}
637
638inline mirror::Object* ConcurrentCopying::GetFwdPtr(mirror::Object* from_ref) {
639 DCHECK(region_space_->IsInFromSpace(from_ref));
640 LockWord lw = from_ref->GetLockWord(false);
641 if (lw.GetState() == LockWord::kForwardingAddress) {
642 mirror::Object* fwd_ptr = reinterpret_cast<mirror::Object*>(lw.ForwardingAddress());
643 CHECK(fwd_ptr != nullptr);
644 return fwd_ptr;
645 } else {
646 return nullptr;
647 }
648}
649
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800650// The following visitors are that used to verify that there's no
651// references to the from-space left after marking.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700652class ConcurrentCopyingVerifyNoFromSpaceRefsVisitor : public SingleRootVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800653 public:
654 explicit ConcurrentCopyingVerifyNoFromSpaceRefsVisitor(ConcurrentCopying* collector)
655 : collector_(collector) {}
656
657 void operator()(mirror::Object* ref) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700658 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800659 if (ref == nullptr) {
660 // OK.
661 return;
662 }
663 collector_->AssertToSpaceInvariant(nullptr, MemberOffset(0), ref);
664 if (kUseBakerReadBarrier) {
665 if (collector_->RegionSpace()->IsInToSpace(ref)) {
666 CHECK(ref->GetReadBarrierPointer() == nullptr)
667 << "To-space ref " << ref << " " << PrettyTypeOf(ref)
668 << " has non-white rb_ptr " << ref->GetReadBarrierPointer();
669 } else {
670 CHECK(ref->GetReadBarrierPointer() == ReadBarrier::BlackPtr() ||
671 (ref->GetReadBarrierPointer() == ReadBarrier::WhitePtr() &&
672 collector_->IsOnAllocStack(ref)))
673 << "Non-moving/unevac from space ref " << ref << " " << PrettyTypeOf(ref)
674 << " has non-black rb_ptr " << ref->GetReadBarrierPointer()
675 << " but isn't on the alloc stack (and has white rb_ptr)."
676 << " Is it in the non-moving space="
677 << (collector_->GetHeap()->GetNonMovingSpace()->HasAddress(ref));
678 }
679 }
680 }
681
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700682 void VisitRoot(mirror::Object* root, const RootInfo& info ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -0700683 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800684 DCHECK(root != nullptr);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700685 operator()(root);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800686 }
687
688 private:
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700689 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800690};
691
692class ConcurrentCopyingVerifyNoFromSpaceRefsFieldVisitor {
693 public:
694 explicit ConcurrentCopyingVerifyNoFromSpaceRefsFieldVisitor(ConcurrentCopying* collector)
695 : collector_(collector) {}
696
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700697 void operator()(mirror::Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700698 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800699 mirror::Object* ref =
700 obj->GetFieldObject<mirror::Object, kDefaultVerifyFlags, kWithoutReadBarrier>(offset);
701 ConcurrentCopyingVerifyNoFromSpaceRefsVisitor visitor(collector_);
702 visitor(ref);
703 }
704 void operator()(mirror::Class* klass, mirror::Reference* ref) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700705 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800706 CHECK(klass->IsTypeOfReferenceClass());
707 this->operator()(ref, mirror::Reference::ReferentOffset(), false);
708 }
709
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700710 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
711 SHARED_REQUIRES(Locks::mutator_lock_) {
712 if (!root->IsNull()) {
713 VisitRoot(root);
714 }
715 }
716
717 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
718 SHARED_REQUIRES(Locks::mutator_lock_) {
719 ConcurrentCopyingVerifyNoFromSpaceRefsVisitor visitor(collector_);
720 visitor(root->AsMirrorPtr());
721 }
722
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800723 private:
Mathieu Chartier97509952015-07-13 14:35:43 -0700724 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800725};
726
727class ConcurrentCopyingVerifyNoFromSpaceRefsObjectVisitor {
728 public:
729 explicit ConcurrentCopyingVerifyNoFromSpaceRefsObjectVisitor(ConcurrentCopying* collector)
730 : collector_(collector) {}
731 void operator()(mirror::Object* obj) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700732 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800733 ObjectCallback(obj, collector_);
734 }
735 static void ObjectCallback(mirror::Object* obj, void *arg)
Mathieu Chartier90443472015-07-16 20:32:27 -0700736 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800737 CHECK(obj != nullptr);
738 ConcurrentCopying* collector = reinterpret_cast<ConcurrentCopying*>(arg);
739 space::RegionSpace* region_space = collector->RegionSpace();
740 CHECK(!region_space->IsInFromSpace(obj)) << "Scanning object " << obj << " in from space";
741 ConcurrentCopyingVerifyNoFromSpaceRefsFieldVisitor visitor(collector);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -0700742 obj->VisitReferences(visitor, visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800743 if (kUseBakerReadBarrier) {
744 if (collector->RegionSpace()->IsInToSpace(obj)) {
745 CHECK(obj->GetReadBarrierPointer() == nullptr)
746 << "obj=" << obj << " non-white rb_ptr " << obj->GetReadBarrierPointer();
747 } else {
748 CHECK(obj->GetReadBarrierPointer() == ReadBarrier::BlackPtr() ||
749 (obj->GetReadBarrierPointer() == ReadBarrier::WhitePtr() &&
750 collector->IsOnAllocStack(obj)))
751 << "Non-moving space/unevac from space ref " << obj << " " << PrettyTypeOf(obj)
752 << " has non-black rb_ptr " << obj->GetReadBarrierPointer()
753 << " but isn't on the alloc stack (and has white rb_ptr). Is it in the non-moving space="
754 << (collector->GetHeap()->GetNonMovingSpace()->HasAddress(obj));
755 }
756 }
757 }
758
759 private:
760 ConcurrentCopying* const collector_;
761};
762
763// Verify there's no from-space references left after the marking phase.
764void ConcurrentCopying::VerifyNoFromSpaceReferences() {
765 Thread* self = Thread::Current();
766 DCHECK(Locks::mutator_lock_->IsExclusiveHeld(self));
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700767 // Verify all threads have is_gc_marking to be false
768 {
769 MutexLock mu(self, *Locks::thread_list_lock_);
770 std::list<Thread*> thread_list = Runtime::Current()->GetThreadList()->GetList();
771 for (Thread* thread : thread_list) {
772 CHECK(!thread->GetIsGcMarking());
773 }
774 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800775 ConcurrentCopyingVerifyNoFromSpaceRefsObjectVisitor visitor(this);
776 // Roots.
777 {
778 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700779 ConcurrentCopyingVerifyNoFromSpaceRefsVisitor ref_visitor(this);
780 Runtime::Current()->VisitRoots(&ref_visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800781 }
782 // The to-space.
783 region_space_->WalkToSpace(ConcurrentCopyingVerifyNoFromSpaceRefsObjectVisitor::ObjectCallback,
784 this);
785 // Non-moving spaces.
786 {
787 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
788 heap_->GetMarkBitmap()->Visit(visitor);
789 }
790 // The alloc stack.
791 {
792 ConcurrentCopyingVerifyNoFromSpaceRefsVisitor ref_visitor(this);
Mathieu Chartiercb535da2015-01-23 13:50:03 -0800793 for (auto* it = heap_->allocation_stack_->Begin(), *end = heap_->allocation_stack_->End();
794 it < end; ++it) {
795 mirror::Object* const obj = it->AsMirrorPtr();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800796 if (obj != nullptr && obj->GetClass() != nullptr) {
797 // TODO: need to call this only if obj is alive?
798 ref_visitor(obj);
799 visitor(obj);
800 }
801 }
802 }
803 // TODO: LOS. But only refs in LOS are classes.
804}
805
806// The following visitors are used to assert the to-space invariant.
807class ConcurrentCopyingAssertToSpaceInvariantRefsVisitor {
808 public:
809 explicit ConcurrentCopyingAssertToSpaceInvariantRefsVisitor(ConcurrentCopying* collector)
810 : collector_(collector) {}
811
812 void operator()(mirror::Object* ref) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700813 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800814 if (ref == nullptr) {
815 // OK.
816 return;
817 }
818 collector_->AssertToSpaceInvariant(nullptr, MemberOffset(0), ref);
819 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800820
821 private:
Mathieu Chartier97509952015-07-13 14:35:43 -0700822 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800823};
824
825class ConcurrentCopyingAssertToSpaceInvariantFieldVisitor {
826 public:
827 explicit ConcurrentCopyingAssertToSpaceInvariantFieldVisitor(ConcurrentCopying* collector)
828 : collector_(collector) {}
829
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700830 void operator()(mirror::Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700831 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800832 mirror::Object* ref =
833 obj->GetFieldObject<mirror::Object, kDefaultVerifyFlags, kWithoutReadBarrier>(offset);
834 ConcurrentCopyingAssertToSpaceInvariantRefsVisitor visitor(collector_);
835 visitor(ref);
836 }
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700837 void operator()(mirror::Class* klass, mirror::Reference* ref ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700838 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800839 CHECK(klass->IsTypeOfReferenceClass());
840 }
841
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700842 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
843 SHARED_REQUIRES(Locks::mutator_lock_) {
844 if (!root->IsNull()) {
845 VisitRoot(root);
846 }
847 }
848
849 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
850 SHARED_REQUIRES(Locks::mutator_lock_) {
851 ConcurrentCopyingAssertToSpaceInvariantRefsVisitor visitor(collector_);
852 visitor(root->AsMirrorPtr());
853 }
854
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800855 private:
Mathieu Chartier97509952015-07-13 14:35:43 -0700856 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800857};
858
859class ConcurrentCopyingAssertToSpaceInvariantObjectVisitor {
860 public:
861 explicit ConcurrentCopyingAssertToSpaceInvariantObjectVisitor(ConcurrentCopying* collector)
862 : collector_(collector) {}
863 void operator()(mirror::Object* obj) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700864 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800865 ObjectCallback(obj, collector_);
866 }
867 static void ObjectCallback(mirror::Object* obj, void *arg)
Mathieu Chartier90443472015-07-16 20:32:27 -0700868 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800869 CHECK(obj != nullptr);
870 ConcurrentCopying* collector = reinterpret_cast<ConcurrentCopying*>(arg);
871 space::RegionSpace* region_space = collector->RegionSpace();
872 CHECK(!region_space->IsInFromSpace(obj)) << "Scanning object " << obj << " in from space";
873 collector->AssertToSpaceInvariant(nullptr, MemberOffset(0), obj);
874 ConcurrentCopyingAssertToSpaceInvariantFieldVisitor visitor(collector);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -0700875 obj->VisitReferences(visitor, visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800876 }
877
878 private:
Mathieu Chartier97509952015-07-13 14:35:43 -0700879 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800880};
881
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700882class RevokeThreadLocalMarkStackCheckpoint : public Closure {
883 public:
Roland Levillain3887c462015-08-12 18:15:42 +0100884 RevokeThreadLocalMarkStackCheckpoint(ConcurrentCopying* concurrent_copying,
885 bool disable_weak_ref_access)
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700886 : concurrent_copying_(concurrent_copying),
887 disable_weak_ref_access_(disable_weak_ref_access) {
888 }
889
890 virtual void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
891 // Note: self is not necessarily equal to thread since thread may be suspended.
892 Thread* self = Thread::Current();
893 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
894 << thread->GetState() << " thread " << thread << " self " << self;
895 // Revoke thread local mark stacks.
896 accounting::AtomicStack<mirror::Object>* tl_mark_stack = thread->GetThreadLocalMarkStack();
897 if (tl_mark_stack != nullptr) {
898 MutexLock mu(self, concurrent_copying_->mark_stack_lock_);
899 concurrent_copying_->revoked_mark_stacks_.push_back(tl_mark_stack);
900 thread->SetThreadLocalMarkStack(nullptr);
901 }
902 // Disable weak ref access.
903 if (disable_weak_ref_access_) {
904 thread->SetWeakRefAccessEnabled(false);
905 }
906 // If thread is a running mutator, then act on behalf of the garbage collector.
907 // See the code in ThreadList::RunCheckpoint.
908 if (thread->GetState() == kRunnable) {
909 concurrent_copying_->GetBarrier().Pass(self);
910 }
911 }
912
913 private:
914 ConcurrentCopying* const concurrent_copying_;
915 const bool disable_weak_ref_access_;
916};
917
918void ConcurrentCopying::RevokeThreadLocalMarkStacks(bool disable_weak_ref_access) {
919 Thread* self = Thread::Current();
920 RevokeThreadLocalMarkStackCheckpoint check_point(this, disable_weak_ref_access);
921 ThreadList* thread_list = Runtime::Current()->GetThreadList();
922 gc_barrier_->Init(self, 0);
923 size_t barrier_count = thread_list->RunCheckpoint(&check_point);
924 // If there are no threads to wait which implys that all the checkpoint functions are finished,
925 // then no need to release the mutator lock.
926 if (barrier_count == 0) {
927 return;
928 }
929 Locks::mutator_lock_->SharedUnlock(self);
930 {
931 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
932 gc_barrier_->Increment(self, barrier_count);
933 }
934 Locks::mutator_lock_->SharedLock(self);
935}
936
937void ConcurrentCopying::RevokeThreadLocalMarkStack(Thread* thread) {
938 Thread* self = Thread::Current();
939 CHECK_EQ(self, thread);
940 accounting::AtomicStack<mirror::Object>* tl_mark_stack = thread->GetThreadLocalMarkStack();
941 if (tl_mark_stack != nullptr) {
942 CHECK(is_marking_);
943 MutexLock mu(self, mark_stack_lock_);
944 revoked_mark_stacks_.push_back(tl_mark_stack);
945 thread->SetThreadLocalMarkStack(nullptr);
946 }
947}
948
949void ConcurrentCopying::ProcessMarkStack() {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800950 if (kVerboseMode) {
951 LOG(INFO) << "ProcessMarkStack. ";
952 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700953 bool empty_prev = false;
954 while (true) {
955 bool empty = ProcessMarkStackOnce();
956 if (empty_prev && empty) {
957 // Saw empty mark stack for a second time, done.
958 break;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800959 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700960 empty_prev = empty;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800961 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700962}
963
964bool ConcurrentCopying::ProcessMarkStackOnce() {
965 Thread* self = Thread::Current();
966 CHECK(thread_running_gc_ != nullptr);
967 CHECK(self == thread_running_gc_);
968 CHECK(self->GetThreadLocalMarkStack() == nullptr);
969 size_t count = 0;
970 MarkStackMode mark_stack_mode = mark_stack_mode_.LoadRelaxed();
971 if (mark_stack_mode == kMarkStackModeThreadLocal) {
972 // Process the thread-local mark stacks and the GC mark stack.
973 count += ProcessThreadLocalMarkStacks(false);
974 while (!gc_mark_stack_->IsEmpty()) {
975 mirror::Object* to_ref = gc_mark_stack_->PopBack();
976 ProcessMarkStackRef(to_ref);
977 ++count;
978 }
979 gc_mark_stack_->Reset();
980 } else if (mark_stack_mode == kMarkStackModeShared) {
981 // Process the shared GC mark stack with a lock.
982 {
983 MutexLock mu(self, mark_stack_lock_);
984 CHECK(revoked_mark_stacks_.empty());
985 }
986 while (true) {
987 std::vector<mirror::Object*> refs;
988 {
989 // Copy refs with lock. Note the number of refs should be small.
990 MutexLock mu(self, mark_stack_lock_);
991 if (gc_mark_stack_->IsEmpty()) {
992 break;
993 }
994 for (StackReference<mirror::Object>* p = gc_mark_stack_->Begin();
995 p != gc_mark_stack_->End(); ++p) {
996 refs.push_back(p->AsMirrorPtr());
997 }
998 gc_mark_stack_->Reset();
999 }
1000 for (mirror::Object* ref : refs) {
1001 ProcessMarkStackRef(ref);
1002 ++count;
1003 }
1004 }
1005 } else {
1006 CHECK_EQ(static_cast<uint32_t>(mark_stack_mode),
1007 static_cast<uint32_t>(kMarkStackModeGcExclusive));
1008 {
1009 MutexLock mu(self, mark_stack_lock_);
1010 CHECK(revoked_mark_stacks_.empty());
1011 }
1012 // Process the GC mark stack in the exclusive mode. No need to take the lock.
1013 while (!gc_mark_stack_->IsEmpty()) {
1014 mirror::Object* to_ref = gc_mark_stack_->PopBack();
1015 ProcessMarkStackRef(to_ref);
1016 ++count;
1017 }
1018 gc_mark_stack_->Reset();
1019 }
1020
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001021 // Return true if the stack was empty.
1022 return count == 0;
1023}
1024
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001025size_t ConcurrentCopying::ProcessThreadLocalMarkStacks(bool disable_weak_ref_access) {
1026 // Run a checkpoint to collect all thread local mark stacks and iterate over them all.
1027 RevokeThreadLocalMarkStacks(disable_weak_ref_access);
1028 size_t count = 0;
1029 std::vector<accounting::AtomicStack<mirror::Object>*> mark_stacks;
1030 {
1031 MutexLock mu(Thread::Current(), mark_stack_lock_);
1032 // Make a copy of the mark stack vector.
1033 mark_stacks = revoked_mark_stacks_;
1034 revoked_mark_stacks_.clear();
1035 }
1036 for (accounting::AtomicStack<mirror::Object>* mark_stack : mark_stacks) {
1037 for (StackReference<mirror::Object>* p = mark_stack->Begin(); p != mark_stack->End(); ++p) {
1038 mirror::Object* to_ref = p->AsMirrorPtr();
1039 ProcessMarkStackRef(to_ref);
1040 ++count;
1041 }
1042 {
1043 MutexLock mu(Thread::Current(), mark_stack_lock_);
1044 if (pooled_mark_stacks_.size() >= kMarkStackPoolSize) {
1045 // The pool has enough. Delete it.
1046 delete mark_stack;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001047 } else {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001048 // Otherwise, put it into the pool for later reuse.
1049 mark_stack->Reset();
1050 pooled_mark_stacks_.push_back(mark_stack);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001051 }
1052 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001053 }
1054 return count;
1055}
1056
1057void ConcurrentCopying::ProcessMarkStackRef(mirror::Object* to_ref) {
1058 DCHECK(!region_space_->IsInFromSpace(to_ref));
1059 if (kUseBakerReadBarrier) {
1060 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr())
1061 << " " << to_ref << " " << to_ref->GetReadBarrierPointer()
1062 << " is_marked=" << IsMarked(to_ref);
1063 }
1064 // Scan ref fields.
1065 Scan(to_ref);
1066 // Mark the gray ref as white or black.
1067 if (kUseBakerReadBarrier) {
1068 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr())
1069 << " " << to_ref << " " << to_ref->GetReadBarrierPointer()
1070 << " is_marked=" << IsMarked(to_ref);
1071 }
1072 if (to_ref->GetClass<kVerifyNone, kWithoutReadBarrier>()->IsTypeOfReferenceClass() &&
1073 to_ref->AsReference()->GetReferent<kWithoutReadBarrier>() != nullptr &&
1074 !IsInToSpace(to_ref->AsReference()->GetReferent<kWithoutReadBarrier>())) {
1075 // Leave References gray so that GetReferent() will trigger RB.
1076 CHECK(to_ref->AsReference()->IsEnqueued()) << "Left unenqueued ref gray " << to_ref;
1077 } else {
1078#ifdef USE_BAKER_OR_BROOKS_READ_BARRIER
1079 if (kUseBakerReadBarrier) {
1080 if (region_space_->IsInToSpace(to_ref)) {
1081 // If to-space, change from gray to white.
1082 bool success = to_ref->AtomicSetReadBarrierPointer(ReadBarrier::GrayPtr(),
1083 ReadBarrier::WhitePtr());
1084 CHECK(success) << "Must succeed as we won the race.";
1085 CHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::WhitePtr());
1086 } else {
1087 // If non-moving space/unevac from space, change from gray
1088 // to black. We can't change gray to white because it's not
1089 // safe to use CAS if two threads change values in opposite
1090 // directions (A->B and B->A). So, we change it to black to
1091 // indicate non-moving objects that have been marked
1092 // through. Note we'd need to change from black to white
1093 // later (concurrently).
1094 bool success = to_ref->AtomicSetReadBarrierPointer(ReadBarrier::GrayPtr(),
1095 ReadBarrier::BlackPtr());
1096 CHECK(success) << "Must succeed as we won the race.";
1097 CHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::BlackPtr());
1098 }
1099 }
1100#else
1101 DCHECK(!kUseBakerReadBarrier);
1102#endif
1103 }
1104 if (ReadBarrier::kEnableToSpaceInvariantChecks || kIsDebugBuild) {
1105 ConcurrentCopyingAssertToSpaceInvariantObjectVisitor visitor(this);
1106 visitor(to_ref);
1107 }
1108}
1109
1110void ConcurrentCopying::SwitchToSharedMarkStackMode() {
1111 Thread* self = Thread::Current();
1112 CHECK(thread_running_gc_ != nullptr);
1113 CHECK_EQ(self, thread_running_gc_);
1114 CHECK(self->GetThreadLocalMarkStack() == nullptr);
1115 MarkStackMode before_mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1116 CHECK_EQ(static_cast<uint32_t>(before_mark_stack_mode),
1117 static_cast<uint32_t>(kMarkStackModeThreadLocal));
1118 mark_stack_mode_.StoreRelaxed(kMarkStackModeShared);
1119 CHECK(weak_ref_access_enabled_.LoadRelaxed());
1120 weak_ref_access_enabled_.StoreRelaxed(false);
1121 QuasiAtomic::ThreadFenceForConstructor();
1122 // Process the thread local mark stacks one last time after switching to the shared mark stack
1123 // mode and disable weak ref accesses.
1124 ProcessThreadLocalMarkStacks(true);
1125 if (kVerboseMode) {
1126 LOG(INFO) << "Switched to shared mark stack mode and disabled weak ref access";
1127 }
1128}
1129
1130void ConcurrentCopying::SwitchToGcExclusiveMarkStackMode() {
1131 Thread* self = Thread::Current();
1132 CHECK(thread_running_gc_ != nullptr);
1133 CHECK_EQ(self, thread_running_gc_);
1134 CHECK(self->GetThreadLocalMarkStack() == nullptr);
1135 MarkStackMode before_mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1136 CHECK_EQ(static_cast<uint32_t>(before_mark_stack_mode),
1137 static_cast<uint32_t>(kMarkStackModeShared));
1138 mark_stack_mode_.StoreRelaxed(kMarkStackModeGcExclusive);
1139 QuasiAtomic::ThreadFenceForConstructor();
1140 if (kVerboseMode) {
1141 LOG(INFO) << "Switched to GC exclusive mark stack mode";
1142 }
1143}
1144
1145void ConcurrentCopying::CheckEmptyMarkStack() {
1146 Thread* self = Thread::Current();
1147 CHECK(thread_running_gc_ != nullptr);
1148 CHECK_EQ(self, thread_running_gc_);
1149 CHECK(self->GetThreadLocalMarkStack() == nullptr);
1150 MarkStackMode mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1151 if (mark_stack_mode == kMarkStackModeThreadLocal) {
1152 // Thread-local mark stack mode.
1153 RevokeThreadLocalMarkStacks(false);
1154 MutexLock mu(Thread::Current(), mark_stack_lock_);
1155 if (!revoked_mark_stacks_.empty()) {
1156 for (accounting::AtomicStack<mirror::Object>* mark_stack : revoked_mark_stacks_) {
1157 while (!mark_stack->IsEmpty()) {
1158 mirror::Object* obj = mark_stack->PopBack();
1159 if (kUseBakerReadBarrier) {
1160 mirror::Object* rb_ptr = obj->GetReadBarrierPointer();
1161 LOG(INFO) << "On mark queue : " << obj << " " << PrettyTypeOf(obj) << " rb_ptr=" << rb_ptr
1162 << " is_marked=" << IsMarked(obj);
1163 } else {
1164 LOG(INFO) << "On mark queue : " << obj << " " << PrettyTypeOf(obj)
1165 << " is_marked=" << IsMarked(obj);
1166 }
1167 }
1168 }
1169 LOG(FATAL) << "mark stack is not empty";
1170 }
1171 } else {
1172 // Shared, GC-exclusive, or off.
1173 MutexLock mu(Thread::Current(), mark_stack_lock_);
1174 CHECK(gc_mark_stack_->IsEmpty());
1175 CHECK(revoked_mark_stacks_.empty());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001176 }
1177}
1178
1179void ConcurrentCopying::SweepSystemWeaks(Thread* self) {
1180 TimingLogger::ScopedTiming split("SweepSystemWeaks", GetTimings());
1181 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier97509952015-07-13 14:35:43 -07001182 Runtime::Current()->SweepSystemWeaks(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001183}
1184
1185void ConcurrentCopying::Sweep(bool swap_bitmaps) {
1186 {
1187 TimingLogger::ScopedTiming t("MarkStackAsLive", GetTimings());
1188 accounting::ObjectStack* live_stack = heap_->GetLiveStack();
1189 if (kEnableFromSpaceAccountingCheck) {
1190 CHECK_GE(live_stack_freeze_size_, live_stack->Size());
1191 }
1192 heap_->MarkAllocStackAsLive(live_stack);
1193 live_stack->Reset();
1194 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001195 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001196 TimingLogger::ScopedTiming split("Sweep", GetTimings());
1197 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
1198 if (space->IsContinuousMemMapAllocSpace()) {
1199 space::ContinuousMemMapAllocSpace* alloc_space = space->AsContinuousMemMapAllocSpace();
1200 if (space == region_space_ || immune_region_.ContainsSpace(space)) {
1201 continue;
1202 }
1203 TimingLogger::ScopedTiming split2(
1204 alloc_space->IsZygoteSpace() ? "SweepZygoteSpace" : "SweepAllocSpace", GetTimings());
1205 RecordFree(alloc_space->Sweep(swap_bitmaps));
1206 }
1207 }
1208 SweepLargeObjects(swap_bitmaps);
1209}
1210
1211void ConcurrentCopying::SweepLargeObjects(bool swap_bitmaps) {
1212 TimingLogger::ScopedTiming split("SweepLargeObjects", GetTimings());
1213 RecordFreeLOS(heap_->GetLargeObjectsSpace()->Sweep(swap_bitmaps));
1214}
1215
1216class ConcurrentCopyingClearBlackPtrsVisitor {
1217 public:
1218 explicit ConcurrentCopyingClearBlackPtrsVisitor(ConcurrentCopying* cc)
1219 : collector_(cc) {}
Andreas Gampe65b798e2015-04-06 09:35:22 -07001220#ifndef USE_BAKER_OR_BROOKS_READ_BARRIER
1221 NO_RETURN
1222#endif
Mathieu Chartier90443472015-07-16 20:32:27 -07001223 void operator()(mirror::Object* obj) const SHARED_REQUIRES(Locks::mutator_lock_)
1224 SHARED_REQUIRES(Locks::heap_bitmap_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001225 DCHECK(obj != nullptr);
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08001226 DCHECK(collector_->heap_->GetMarkBitmap()->Test(obj)) << obj;
1227 DCHECK_EQ(obj->GetReadBarrierPointer(), ReadBarrier::BlackPtr()) << obj;
Hiroshi Yamauchi60f63f52015-04-23 16:12:40 -07001228 obj->AtomicSetReadBarrierPointer(ReadBarrier::BlackPtr(), ReadBarrier::WhitePtr());
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08001229 DCHECK_EQ(obj->GetReadBarrierPointer(), ReadBarrier::WhitePtr()) << obj;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001230 }
1231
1232 private:
1233 ConcurrentCopying* const collector_;
1234};
1235
1236// Clear the black ptrs in non-moving objects back to white.
1237void ConcurrentCopying::ClearBlackPtrs() {
1238 CHECK(kUseBakerReadBarrier);
1239 TimingLogger::ScopedTiming split("ClearBlackPtrs", GetTimings());
1240 ConcurrentCopyingClearBlackPtrsVisitor visitor(this);
1241 for (auto& space : heap_->GetContinuousSpaces()) {
1242 if (space == region_space_) {
1243 continue;
1244 }
1245 accounting::ContinuousSpaceBitmap* mark_bitmap = space->GetMarkBitmap();
1246 if (kVerboseMode) {
1247 LOG(INFO) << "ClearBlackPtrs: " << *space << " bitmap: " << *mark_bitmap;
1248 }
1249 mark_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()),
1250 reinterpret_cast<uintptr_t>(space->Limit()),
1251 visitor);
1252 }
1253 space::LargeObjectSpace* large_object_space = heap_->GetLargeObjectsSpace();
1254 large_object_space->GetMarkBitmap()->VisitMarkedRange(
1255 reinterpret_cast<uintptr_t>(large_object_space->Begin()),
1256 reinterpret_cast<uintptr_t>(large_object_space->End()),
1257 visitor);
1258 // Objects on the allocation stack?
1259 if (ReadBarrier::kEnableReadBarrierInvariantChecks || kIsDebugBuild) {
1260 size_t count = GetAllocationStack()->Size();
Mathieu Chartiercb535da2015-01-23 13:50:03 -08001261 auto* it = GetAllocationStack()->Begin();
1262 auto* end = GetAllocationStack()->End();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001263 for (size_t i = 0; i < count; ++i, ++it) {
Mathieu Chartiercb535da2015-01-23 13:50:03 -08001264 CHECK_LT(it, end);
1265 mirror::Object* obj = it->AsMirrorPtr();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001266 if (obj != nullptr) {
1267 // Must have been cleared above.
Mathieu Chartiercb535da2015-01-23 13:50:03 -08001268 CHECK_EQ(obj->GetReadBarrierPointer(), ReadBarrier::WhitePtr()) << obj;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001269 }
1270 }
1271 }
1272}
1273
1274void ConcurrentCopying::ReclaimPhase() {
1275 TimingLogger::ScopedTiming split("ReclaimPhase", GetTimings());
1276 if (kVerboseMode) {
1277 LOG(INFO) << "GC ReclaimPhase";
1278 }
1279 Thread* self = Thread::Current();
1280
1281 {
1282 // Double-check that the mark stack is empty.
1283 // Note: need to set this after VerifyNoFromSpaceRef().
1284 is_asserting_to_space_invariant_ = false;
1285 QuasiAtomic::ThreadFenceForConstructor();
1286 if (kVerboseMode) {
1287 LOG(INFO) << "Issue an empty check point. ";
1288 }
1289 IssueEmptyCheckpoint();
1290 // Disable the check.
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001291 is_mark_stack_push_disallowed_.StoreSequentiallyConsistent(0);
1292 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001293 }
1294
1295 {
1296 // Record freed objects.
1297 TimingLogger::ScopedTiming split2("RecordFree", GetTimings());
1298 // Don't include thread-locals that are in the to-space.
1299 uint64_t from_bytes = region_space_->GetBytesAllocatedInFromSpace();
1300 uint64_t from_objects = region_space_->GetObjectsAllocatedInFromSpace();
1301 uint64_t unevac_from_bytes = region_space_->GetBytesAllocatedInUnevacFromSpace();
1302 uint64_t unevac_from_objects = region_space_->GetObjectsAllocatedInUnevacFromSpace();
1303 uint64_t to_bytes = bytes_moved_.LoadSequentiallyConsistent();
1304 uint64_t to_objects = objects_moved_.LoadSequentiallyConsistent();
1305 if (kEnableFromSpaceAccountingCheck) {
1306 CHECK_EQ(from_space_num_objects_at_first_pause_, from_objects + unevac_from_objects);
1307 CHECK_EQ(from_space_num_bytes_at_first_pause_, from_bytes + unevac_from_bytes);
1308 }
1309 CHECK_LE(to_objects, from_objects);
1310 CHECK_LE(to_bytes, from_bytes);
1311 int64_t freed_bytes = from_bytes - to_bytes;
1312 int64_t freed_objects = from_objects - to_objects;
1313 if (kVerboseMode) {
1314 LOG(INFO) << "RecordFree:"
1315 << " from_bytes=" << from_bytes << " from_objects=" << from_objects
1316 << " unevac_from_bytes=" << unevac_from_bytes << " unevac_from_objects=" << unevac_from_objects
1317 << " to_bytes=" << to_bytes << " to_objects=" << to_objects
1318 << " freed_bytes=" << freed_bytes << " freed_objects=" << freed_objects
1319 << " from_space size=" << region_space_->FromSpaceSize()
1320 << " unevac_from_space size=" << region_space_->UnevacFromSpaceSize()
1321 << " to_space size=" << region_space_->ToSpaceSize();
1322 LOG(INFO) << "(before) num_bytes_allocated=" << heap_->num_bytes_allocated_.LoadSequentiallyConsistent();
1323 }
1324 RecordFree(ObjectBytePair(freed_objects, freed_bytes));
1325 if (kVerboseMode) {
1326 LOG(INFO) << "(after) num_bytes_allocated=" << heap_->num_bytes_allocated_.LoadSequentiallyConsistent();
1327 }
1328 }
1329
1330 {
1331 TimingLogger::ScopedTiming split3("ComputeUnevacFromSpaceLiveRatio", GetTimings());
1332 ComputeUnevacFromSpaceLiveRatio();
1333 }
1334
1335 {
1336 TimingLogger::ScopedTiming split4("ClearFromSpace", GetTimings());
1337 region_space_->ClearFromSpace();
1338 }
1339
1340 {
1341 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1342 if (kUseBakerReadBarrier) {
1343 ClearBlackPtrs();
1344 }
1345 Sweep(false);
1346 SwapBitmaps();
1347 heap_->UnBindBitmaps();
1348
1349 // Remove bitmaps for the immune spaces.
1350 while (!cc_bitmaps_.empty()) {
1351 accounting::ContinuousSpaceBitmap* cc_bitmap = cc_bitmaps_.back();
1352 cc_heap_bitmap_->RemoveContinuousSpaceBitmap(cc_bitmap);
1353 delete cc_bitmap;
1354 cc_bitmaps_.pop_back();
1355 }
1356 region_space_bitmap_ = nullptr;
1357 }
1358
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001359 CheckEmptyMarkStack();
1360
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001361 if (kVerboseMode) {
1362 LOG(INFO) << "GC end of ReclaimPhase";
1363 }
1364}
1365
1366class ConcurrentCopyingComputeUnevacFromSpaceLiveRatioVisitor {
1367 public:
1368 explicit ConcurrentCopyingComputeUnevacFromSpaceLiveRatioVisitor(ConcurrentCopying* cc)
1369 : collector_(cc) {}
Mathieu Chartier90443472015-07-16 20:32:27 -07001370 void operator()(mirror::Object* ref) const SHARED_REQUIRES(Locks::mutator_lock_)
1371 SHARED_REQUIRES(Locks::heap_bitmap_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001372 DCHECK(ref != nullptr);
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08001373 DCHECK(collector_->region_space_bitmap_->Test(ref)) << ref;
1374 DCHECK(collector_->region_space_->IsInUnevacFromSpace(ref)) << ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001375 if (kUseBakerReadBarrier) {
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08001376 DCHECK_EQ(ref->GetReadBarrierPointer(), ReadBarrier::BlackPtr()) << ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001377 // Clear the black ptr.
Hiroshi Yamauchi60f63f52015-04-23 16:12:40 -07001378 ref->AtomicSetReadBarrierPointer(ReadBarrier::BlackPtr(), ReadBarrier::WhitePtr());
1379 DCHECK_EQ(ref->GetReadBarrierPointer(), ReadBarrier::WhitePtr()) << ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001380 }
1381 size_t obj_size = ref->SizeOf();
1382 size_t alloc_size = RoundUp(obj_size, space::RegionSpace::kAlignment);
1383 collector_->region_space_->AddLiveBytes(ref, alloc_size);
1384 }
1385
1386 private:
Mathieu Chartier97509952015-07-13 14:35:43 -07001387 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001388};
1389
1390// Compute how much live objects are left in regions.
1391void ConcurrentCopying::ComputeUnevacFromSpaceLiveRatio() {
1392 region_space_->AssertAllRegionLiveBytesZeroOrCleared();
1393 ConcurrentCopyingComputeUnevacFromSpaceLiveRatioVisitor visitor(this);
1394 region_space_bitmap_->VisitMarkedRange(reinterpret_cast<uintptr_t>(region_space_->Begin()),
1395 reinterpret_cast<uintptr_t>(region_space_->Limit()),
1396 visitor);
1397}
1398
1399// Assert the to-space invariant.
1400void ConcurrentCopying::AssertToSpaceInvariant(mirror::Object* obj, MemberOffset offset,
1401 mirror::Object* ref) {
1402 CHECK(heap_->collector_type_ == kCollectorTypeCC) << static_cast<size_t>(heap_->collector_type_);
1403 if (is_asserting_to_space_invariant_) {
1404 if (region_space_->IsInToSpace(ref)) {
1405 // OK.
1406 return;
1407 } else if (region_space_->IsInUnevacFromSpace(ref)) {
1408 CHECK(region_space_bitmap_->Test(ref)) << ref;
1409 } else if (region_space_->IsInFromSpace(ref)) {
1410 // Not OK. Do extra logging.
1411 if (obj != nullptr) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001412 LogFromSpaceRefHolder(obj, offset);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001413 }
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001414 ref->GetLockWord(false).Dump(LOG(INTERNAL_FATAL));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001415 CHECK(false) << "Found from-space ref " << ref << " " << PrettyTypeOf(ref);
1416 } else {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001417 AssertToSpaceInvariantInNonMovingSpace(obj, ref);
1418 }
1419 }
1420}
1421
1422class RootPrinter {
1423 public:
1424 RootPrinter() { }
1425
1426 template <class MirrorType>
1427 ALWAYS_INLINE void VisitRootIfNonNull(mirror::CompressedReference<MirrorType>* root)
Mathieu Chartier90443472015-07-16 20:32:27 -07001428 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001429 if (!root->IsNull()) {
1430 VisitRoot(root);
1431 }
1432 }
1433
1434 template <class MirrorType>
1435 void VisitRoot(mirror::Object** root)
Mathieu Chartier90443472015-07-16 20:32:27 -07001436 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001437 LOG(INTERNAL_FATAL) << "root=" << root << " ref=" << *root;
1438 }
1439
1440 template <class MirrorType>
1441 void VisitRoot(mirror::CompressedReference<MirrorType>* root)
Mathieu Chartier90443472015-07-16 20:32:27 -07001442 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001443 LOG(INTERNAL_FATAL) << "root=" << root << " ref=" << root->AsMirrorPtr();
1444 }
1445};
1446
1447void ConcurrentCopying::AssertToSpaceInvariant(GcRootSource* gc_root_source,
1448 mirror::Object* ref) {
1449 CHECK(heap_->collector_type_ == kCollectorTypeCC) << static_cast<size_t>(heap_->collector_type_);
1450 if (is_asserting_to_space_invariant_) {
1451 if (region_space_->IsInToSpace(ref)) {
1452 // OK.
1453 return;
1454 } else if (region_space_->IsInUnevacFromSpace(ref)) {
1455 CHECK(region_space_bitmap_->Test(ref)) << ref;
1456 } else if (region_space_->IsInFromSpace(ref)) {
1457 // Not OK. Do extra logging.
1458 if (gc_root_source == nullptr) {
1459 // No info.
1460 } else if (gc_root_source->HasArtField()) {
1461 ArtField* field = gc_root_source->GetArtField();
1462 LOG(INTERNAL_FATAL) << "gc root in field " << field << " " << PrettyField(field);
1463 RootPrinter root_printer;
1464 field->VisitRoots(root_printer);
1465 } else if (gc_root_source->HasArtMethod()) {
1466 ArtMethod* method = gc_root_source->GetArtMethod();
1467 LOG(INTERNAL_FATAL) << "gc root in method " << method << " " << PrettyMethod(method);
1468 RootPrinter root_printer;
1469 method->VisitRoots(root_printer);
1470 }
1471 ref->GetLockWord(false).Dump(LOG(INTERNAL_FATAL));
1472 region_space_->DumpNonFreeRegions(LOG(INTERNAL_FATAL));
1473 PrintFileToLog("/proc/self/maps", LogSeverity::INTERNAL_FATAL);
1474 MemMap::DumpMaps(LOG(INTERNAL_FATAL), true);
1475 CHECK(false) << "Found from-space ref " << ref << " " << PrettyTypeOf(ref);
1476 } else {
1477 AssertToSpaceInvariantInNonMovingSpace(nullptr, ref);
1478 }
1479 }
1480}
1481
1482void ConcurrentCopying::LogFromSpaceRefHolder(mirror::Object* obj, MemberOffset offset) {
1483 if (kUseBakerReadBarrier) {
1484 LOG(INFO) << "holder=" << obj << " " << PrettyTypeOf(obj)
1485 << " holder rb_ptr=" << obj->GetReadBarrierPointer();
1486 } else {
1487 LOG(INFO) << "holder=" << obj << " " << PrettyTypeOf(obj);
1488 }
1489 if (region_space_->IsInFromSpace(obj)) {
1490 LOG(INFO) << "holder is in the from-space.";
1491 } else if (region_space_->IsInToSpace(obj)) {
1492 LOG(INFO) << "holder is in the to-space.";
1493 } else if (region_space_->IsInUnevacFromSpace(obj)) {
1494 LOG(INFO) << "holder is in the unevac from-space.";
1495 if (region_space_bitmap_->Test(obj)) {
1496 LOG(INFO) << "holder is marked in the region space bitmap.";
1497 } else {
1498 LOG(INFO) << "holder is not marked in the region space bitmap.";
1499 }
1500 } else {
1501 // In a non-moving space.
1502 if (immune_region_.ContainsObject(obj)) {
1503 LOG(INFO) << "holder is in the image or the zygote space.";
1504 accounting::ContinuousSpaceBitmap* cc_bitmap =
1505 cc_heap_bitmap_->GetContinuousSpaceBitmap(obj);
1506 CHECK(cc_bitmap != nullptr)
1507 << "An immune space object must have a bitmap.";
1508 if (cc_bitmap->Test(obj)) {
1509 LOG(INFO) << "holder is marked in the bit map.";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001510 } else {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001511 LOG(INFO) << "holder is NOT marked in the bit map.";
1512 }
1513 } else {
1514 LOG(INFO) << "holder is in a non-moving (or main) space.";
1515 accounting::ContinuousSpaceBitmap* mark_bitmap =
1516 heap_mark_bitmap_->GetContinuousSpaceBitmap(obj);
1517 accounting::LargeObjectBitmap* los_bitmap =
1518 heap_mark_bitmap_->GetLargeObjectBitmap(obj);
1519 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
1520 bool is_los = mark_bitmap == nullptr;
1521 if (!is_los && mark_bitmap->Test(obj)) {
1522 LOG(INFO) << "holder is marked in the mark bit map.";
1523 } else if (is_los && los_bitmap->Test(obj)) {
1524 LOG(INFO) << "holder is marked in the los bit map.";
1525 } else {
1526 // If ref is on the allocation stack, then it is considered
1527 // mark/alive (but not necessarily on the live stack.)
1528 if (IsOnAllocStack(obj)) {
1529 LOG(INFO) << "holder is on the alloc stack.";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001530 } else {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001531 LOG(INFO) << "holder is not marked or on the alloc stack.";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001532 }
1533 }
1534 }
1535 }
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001536 LOG(INFO) << "offset=" << offset.SizeValue();
1537}
1538
1539void ConcurrentCopying::AssertToSpaceInvariantInNonMovingSpace(mirror::Object* obj,
1540 mirror::Object* ref) {
1541 // In a non-moving spaces. Check that the ref is marked.
1542 if (immune_region_.ContainsObject(ref)) {
1543 accounting::ContinuousSpaceBitmap* cc_bitmap =
1544 cc_heap_bitmap_->GetContinuousSpaceBitmap(ref);
1545 CHECK(cc_bitmap != nullptr)
1546 << "An immune space ref must have a bitmap. " << ref;
1547 if (kUseBakerReadBarrier) {
1548 CHECK(cc_bitmap->Test(ref))
1549 << "Unmarked immune space ref. obj=" << obj << " rb_ptr="
1550 << obj->GetReadBarrierPointer() << " ref=" << ref;
1551 } else {
1552 CHECK(cc_bitmap->Test(ref))
1553 << "Unmarked immune space ref. obj=" << obj << " ref=" << ref;
1554 }
1555 } else {
1556 accounting::ContinuousSpaceBitmap* mark_bitmap =
1557 heap_mark_bitmap_->GetContinuousSpaceBitmap(ref);
1558 accounting::LargeObjectBitmap* los_bitmap =
1559 heap_mark_bitmap_->GetLargeObjectBitmap(ref);
1560 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
1561 bool is_los = mark_bitmap == nullptr;
1562 if ((!is_los && mark_bitmap->Test(ref)) ||
1563 (is_los && los_bitmap->Test(ref))) {
1564 // OK.
1565 } else {
1566 // If ref is on the allocation stack, then it may not be
1567 // marked live, but considered marked/alive (but not
1568 // necessarily on the live stack).
1569 CHECK(IsOnAllocStack(ref)) << "Unmarked ref that's not on the allocation stack. "
1570 << "obj=" << obj << " ref=" << ref;
1571 }
1572 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001573}
1574
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001575// Used to scan ref fields of an object.
1576class ConcurrentCopyingRefFieldsVisitor {
1577 public:
1578 explicit ConcurrentCopyingRefFieldsVisitor(ConcurrentCopying* collector)
1579 : collector_(collector) {}
1580
1581 void operator()(mirror::Object* obj, MemberOffset offset, bool /* is_static */)
Mathieu Chartier90443472015-07-16 20:32:27 -07001582 const ALWAYS_INLINE SHARED_REQUIRES(Locks::mutator_lock_)
1583 SHARED_REQUIRES(Locks::heap_bitmap_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001584 collector_->Process(obj, offset);
1585 }
1586
1587 void operator()(mirror::Class* klass, mirror::Reference* ref) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001588 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001589 CHECK(klass->IsTypeOfReferenceClass());
1590 collector_->DelayReferenceReferent(klass, ref);
1591 }
1592
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001593 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
1594 SHARED_REQUIRES(Locks::mutator_lock_) {
1595 if (!root->IsNull()) {
1596 VisitRoot(root);
1597 }
1598 }
1599
1600 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
1601 SHARED_REQUIRES(Locks::mutator_lock_) {
1602 collector_->MarkRoot(root);
1603 }
1604
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001605 private:
1606 ConcurrentCopying* const collector_;
1607};
1608
1609// Scan ref fields of an object.
1610void ConcurrentCopying::Scan(mirror::Object* to_ref) {
1611 DCHECK(!region_space_->IsInFromSpace(to_ref));
1612 ConcurrentCopyingRefFieldsVisitor visitor(this);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07001613 to_ref->VisitReferences(visitor, visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001614}
1615
1616// Process a field.
1617inline void ConcurrentCopying::Process(mirror::Object* obj, MemberOffset offset) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001618 mirror::Object* ref = obj->GetFieldObject<
1619 mirror::Object, kVerifyNone, kWithoutReadBarrier, false>(offset);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001620 if (ref == nullptr || region_space_->IsInToSpace(ref)) {
1621 return;
1622 }
1623 mirror::Object* to_ref = Mark(ref);
1624 if (to_ref == ref) {
1625 return;
1626 }
1627 // This may fail if the mutator writes to the field at the same time. But it's ok.
1628 mirror::Object* expected_ref = ref;
1629 mirror::Object* new_ref = to_ref;
1630 do {
1631 if (expected_ref !=
1632 obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier, false>(offset)) {
1633 // It was updated by the mutator.
1634 break;
1635 }
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001636 } while (!obj->CasFieldWeakSequentiallyConsistentObjectWithoutWriteBarrier<
1637 false, false, kVerifyNone>(offset, expected_ref, new_ref));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001638}
1639
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001640// Process some roots.
1641void ConcurrentCopying::VisitRoots(
1642 mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED) {
1643 for (size_t i = 0; i < count; ++i) {
1644 mirror::Object** root = roots[i];
1645 mirror::Object* ref = *root;
1646 if (ref == nullptr || region_space_->IsInToSpace(ref)) {
Mathieu Chartier4809d0a2015-04-07 10:39:04 -07001647 continue;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001648 }
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001649 mirror::Object* to_ref = Mark(ref);
1650 if (to_ref == ref) {
Mathieu Chartier4809d0a2015-04-07 10:39:04 -07001651 continue;
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001652 }
1653 Atomic<mirror::Object*>* addr = reinterpret_cast<Atomic<mirror::Object*>*>(root);
1654 mirror::Object* expected_ref = ref;
1655 mirror::Object* new_ref = to_ref;
1656 do {
1657 if (expected_ref != addr->LoadRelaxed()) {
1658 // It was updated by the mutator.
1659 break;
1660 }
1661 } while (!addr->CompareExchangeWeakSequentiallyConsistent(expected_ref, new_ref));
1662 }
1663}
1664
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001665void ConcurrentCopying::MarkRoot(mirror::CompressedReference<mirror::Object>* root) {
1666 DCHECK(!root->IsNull());
1667 mirror::Object* const ref = root->AsMirrorPtr();
1668 if (region_space_->IsInToSpace(ref)) {
1669 return;
1670 }
1671 mirror::Object* to_ref = Mark(ref);
1672 if (to_ref != ref) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001673 auto* addr = reinterpret_cast<Atomic<mirror::CompressedReference<mirror::Object>>*>(root);
1674 auto expected_ref = mirror::CompressedReference<mirror::Object>::FromMirrorPtr(ref);
1675 auto new_ref = mirror::CompressedReference<mirror::Object>::FromMirrorPtr(to_ref);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001676 // If the cas fails, then it was updated by the mutator.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001677 do {
1678 if (ref != addr->LoadRelaxed().AsMirrorPtr()) {
1679 // It was updated by the mutator.
1680 break;
1681 }
1682 } while (!addr->CompareExchangeWeakSequentiallyConsistent(expected_ref, new_ref));
1683 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001684}
1685
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001686void ConcurrentCopying::VisitRoots(
1687 mirror::CompressedReference<mirror::Object>** roots, size_t count,
1688 const RootInfo& info ATTRIBUTE_UNUSED) {
1689 for (size_t i = 0; i < count; ++i) {
1690 mirror::CompressedReference<mirror::Object>* const root = roots[i];
1691 if (!root->IsNull()) {
1692 MarkRoot(root);
1693 }
1694 }
1695}
1696
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001697// Fill the given memory block with a dummy object. Used to fill in a
1698// copy of objects that was lost in race.
1699void ConcurrentCopying::FillWithDummyObject(mirror::Object* dummy_obj, size_t byte_size) {
Roland Levillain14d90572015-07-16 10:52:26 +01001700 CHECK_ALIGNED(byte_size, kObjectAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001701 memset(dummy_obj, 0, byte_size);
1702 mirror::Class* int_array_class = mirror::IntArray::GetArrayClass();
1703 CHECK(int_array_class != nullptr);
1704 AssertToSpaceInvariant(nullptr, MemberOffset(0), int_array_class);
1705 size_t component_size = int_array_class->GetComponentSize();
1706 CHECK_EQ(component_size, sizeof(int32_t));
1707 size_t data_offset = mirror::Array::DataOffset(component_size).SizeValue();
1708 if (data_offset > byte_size) {
1709 // An int array is too big. Use java.lang.Object.
1710 mirror::Class* java_lang_Object = WellKnownClasses::ToClass(WellKnownClasses::java_lang_Object);
1711 AssertToSpaceInvariant(nullptr, MemberOffset(0), java_lang_Object);
1712 CHECK_EQ(byte_size, java_lang_Object->GetObjectSize());
1713 dummy_obj->SetClass(java_lang_Object);
1714 CHECK_EQ(byte_size, dummy_obj->SizeOf());
1715 } else {
1716 // Use an int array.
1717 dummy_obj->SetClass(int_array_class);
1718 CHECK(dummy_obj->IsArrayInstance());
1719 int32_t length = (byte_size - data_offset) / component_size;
1720 dummy_obj->AsArray()->SetLength(length);
1721 CHECK_EQ(dummy_obj->AsArray()->GetLength(), length)
1722 << "byte_size=" << byte_size << " length=" << length
1723 << " component_size=" << component_size << " data_offset=" << data_offset;
1724 CHECK_EQ(byte_size, dummy_obj->SizeOf())
1725 << "byte_size=" << byte_size << " length=" << length
1726 << " component_size=" << component_size << " data_offset=" << data_offset;
1727 }
1728}
1729
1730// Reuse the memory blocks that were copy of objects that were lost in race.
1731mirror::Object* ConcurrentCopying::AllocateInSkippedBlock(size_t alloc_size) {
1732 // Try to reuse the blocks that were unused due to CAS failures.
Roland Levillain14d90572015-07-16 10:52:26 +01001733 CHECK_ALIGNED(alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001734 Thread* self = Thread::Current();
1735 size_t min_object_size = RoundUp(sizeof(mirror::Object), space::RegionSpace::kAlignment);
1736 MutexLock mu(self, skipped_blocks_lock_);
1737 auto it = skipped_blocks_map_.lower_bound(alloc_size);
1738 if (it == skipped_blocks_map_.end()) {
1739 // Not found.
1740 return nullptr;
1741 }
1742 {
1743 size_t byte_size = it->first;
1744 CHECK_GE(byte_size, alloc_size);
1745 if (byte_size > alloc_size && byte_size - alloc_size < min_object_size) {
1746 // If remainder would be too small for a dummy object, retry with a larger request size.
1747 it = skipped_blocks_map_.lower_bound(alloc_size + min_object_size);
1748 if (it == skipped_blocks_map_.end()) {
1749 // Not found.
1750 return nullptr;
1751 }
Roland Levillain14d90572015-07-16 10:52:26 +01001752 CHECK_ALIGNED(it->first - alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001753 CHECK_GE(it->first - alloc_size, min_object_size)
1754 << "byte_size=" << byte_size << " it->first=" << it->first << " alloc_size=" << alloc_size;
1755 }
1756 }
1757 // Found a block.
1758 CHECK(it != skipped_blocks_map_.end());
1759 size_t byte_size = it->first;
1760 uint8_t* addr = it->second;
1761 CHECK_GE(byte_size, alloc_size);
1762 CHECK(region_space_->IsInToSpace(reinterpret_cast<mirror::Object*>(addr)));
Roland Levillain14d90572015-07-16 10:52:26 +01001763 CHECK_ALIGNED(byte_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001764 if (kVerboseMode) {
1765 LOG(INFO) << "Reusing skipped bytes : " << reinterpret_cast<void*>(addr) << ", " << byte_size;
1766 }
1767 skipped_blocks_map_.erase(it);
1768 memset(addr, 0, byte_size);
1769 if (byte_size > alloc_size) {
1770 // Return the remainder to the map.
Roland Levillain14d90572015-07-16 10:52:26 +01001771 CHECK_ALIGNED(byte_size - alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001772 CHECK_GE(byte_size - alloc_size, min_object_size);
1773 FillWithDummyObject(reinterpret_cast<mirror::Object*>(addr + alloc_size),
1774 byte_size - alloc_size);
1775 CHECK(region_space_->IsInToSpace(reinterpret_cast<mirror::Object*>(addr + alloc_size)));
1776 skipped_blocks_map_.insert(std::make_pair(byte_size - alloc_size, addr + alloc_size));
1777 }
1778 return reinterpret_cast<mirror::Object*>(addr);
1779}
1780
1781mirror::Object* ConcurrentCopying::Copy(mirror::Object* from_ref) {
1782 DCHECK(region_space_->IsInFromSpace(from_ref));
1783 // No read barrier to avoid nested RB that might violate the to-space
1784 // invariant. Note that from_ref is a from space ref so the SizeOf()
1785 // call will access the from-space meta objects, but it's ok and necessary.
1786 size_t obj_size = from_ref->SizeOf<kDefaultVerifyFlags, kWithoutReadBarrier>();
1787 size_t region_space_alloc_size = RoundUp(obj_size, space::RegionSpace::kAlignment);
1788 size_t region_space_bytes_allocated = 0U;
1789 size_t non_moving_space_bytes_allocated = 0U;
1790 size_t bytes_allocated = 0U;
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001791 size_t dummy;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001792 mirror::Object* to_ref = region_space_->AllocNonvirtual<true>(
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001793 region_space_alloc_size, &region_space_bytes_allocated, nullptr, &dummy);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001794 bytes_allocated = region_space_bytes_allocated;
1795 if (to_ref != nullptr) {
1796 DCHECK_EQ(region_space_alloc_size, region_space_bytes_allocated);
1797 }
1798 bool fall_back_to_non_moving = false;
1799 if (UNLIKELY(to_ref == nullptr)) {
1800 // Failed to allocate in the region space. Try the skipped blocks.
1801 to_ref = AllocateInSkippedBlock(region_space_alloc_size);
1802 if (to_ref != nullptr) {
1803 // Succeeded to allocate in a skipped block.
1804 if (heap_->use_tlab_) {
1805 // This is necessary for the tlab case as it's not accounted in the space.
1806 region_space_->RecordAlloc(to_ref);
1807 }
1808 bytes_allocated = region_space_alloc_size;
1809 } else {
1810 // Fall back to the non-moving space.
1811 fall_back_to_non_moving = true;
1812 if (kVerboseMode) {
1813 LOG(INFO) << "Out of memory in the to-space. Fall back to non-moving. skipped_bytes="
1814 << to_space_bytes_skipped_.LoadSequentiallyConsistent()
1815 << " skipped_objects=" << to_space_objects_skipped_.LoadSequentiallyConsistent();
1816 }
1817 fall_back_to_non_moving = true;
1818 to_ref = heap_->non_moving_space_->Alloc(Thread::Current(), obj_size,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001819 &non_moving_space_bytes_allocated, nullptr, &dummy);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001820 CHECK(to_ref != nullptr) << "Fall-back non-moving space allocation failed";
1821 bytes_allocated = non_moving_space_bytes_allocated;
1822 // Mark it in the mark bitmap.
1823 accounting::ContinuousSpaceBitmap* mark_bitmap =
1824 heap_mark_bitmap_->GetContinuousSpaceBitmap(to_ref);
1825 CHECK(mark_bitmap != nullptr);
1826 CHECK(!mark_bitmap->AtomicTestAndSet(to_ref));
1827 }
1828 }
1829 DCHECK(to_ref != nullptr);
1830
1831 // Attempt to install the forward pointer. This is in a loop as the
1832 // lock word atomic write can fail.
1833 while (true) {
1834 // Copy the object. TODO: copy only the lockword in the second iteration and on?
1835 memcpy(to_ref, from_ref, obj_size);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001836
1837 LockWord old_lock_word = to_ref->GetLockWord(false);
1838
1839 if (old_lock_word.GetState() == LockWord::kForwardingAddress) {
1840 // Lost the race. Another thread (either GC or mutator) stored
1841 // the forwarding pointer first. Make the lost copy (to_ref)
1842 // look like a valid but dead (dummy) object and keep it for
1843 // future reuse.
1844 FillWithDummyObject(to_ref, bytes_allocated);
1845 if (!fall_back_to_non_moving) {
1846 DCHECK(region_space_->IsInToSpace(to_ref));
1847 if (bytes_allocated > space::RegionSpace::kRegionSize) {
1848 // Free the large alloc.
1849 region_space_->FreeLarge(to_ref, bytes_allocated);
1850 } else {
1851 // Record the lost copy for later reuse.
1852 heap_->num_bytes_allocated_.FetchAndAddSequentiallyConsistent(bytes_allocated);
1853 to_space_bytes_skipped_.FetchAndAddSequentiallyConsistent(bytes_allocated);
1854 to_space_objects_skipped_.FetchAndAddSequentiallyConsistent(1);
1855 MutexLock mu(Thread::Current(), skipped_blocks_lock_);
1856 skipped_blocks_map_.insert(std::make_pair(bytes_allocated,
1857 reinterpret_cast<uint8_t*>(to_ref)));
1858 }
1859 } else {
1860 DCHECK(heap_->non_moving_space_->HasAddress(to_ref));
1861 DCHECK_EQ(bytes_allocated, non_moving_space_bytes_allocated);
1862 // Free the non-moving-space chunk.
1863 accounting::ContinuousSpaceBitmap* mark_bitmap =
1864 heap_mark_bitmap_->GetContinuousSpaceBitmap(to_ref);
1865 CHECK(mark_bitmap != nullptr);
1866 CHECK(mark_bitmap->Clear(to_ref));
1867 heap_->non_moving_space_->Free(Thread::Current(), to_ref);
1868 }
1869
1870 // Get the winner's forward ptr.
1871 mirror::Object* lost_fwd_ptr = to_ref;
1872 to_ref = reinterpret_cast<mirror::Object*>(old_lock_word.ForwardingAddress());
1873 CHECK(to_ref != nullptr);
1874 CHECK_NE(to_ref, lost_fwd_ptr);
1875 CHECK(region_space_->IsInToSpace(to_ref) || heap_->non_moving_space_->HasAddress(to_ref));
1876 CHECK_NE(to_ref->GetLockWord(false).GetState(), LockWord::kForwardingAddress);
1877 return to_ref;
1878 }
1879
Hiroshi Yamauchi60f63f52015-04-23 16:12:40 -07001880 // Set the gray ptr.
1881 if (kUseBakerReadBarrier) {
1882 to_ref->SetReadBarrierPointer(ReadBarrier::GrayPtr());
1883 }
1884
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001885 LockWord new_lock_word = LockWord::FromForwardingAddress(reinterpret_cast<size_t>(to_ref));
1886
1887 // Try to atomically write the fwd ptr.
1888 bool success = from_ref->CasLockWordWeakSequentiallyConsistent(old_lock_word, new_lock_word);
1889 if (LIKELY(success)) {
1890 // The CAS succeeded.
1891 objects_moved_.FetchAndAddSequentiallyConsistent(1);
1892 bytes_moved_.FetchAndAddSequentiallyConsistent(region_space_alloc_size);
1893 if (LIKELY(!fall_back_to_non_moving)) {
1894 DCHECK(region_space_->IsInToSpace(to_ref));
1895 } else {
1896 DCHECK(heap_->non_moving_space_->HasAddress(to_ref));
1897 DCHECK_EQ(bytes_allocated, non_moving_space_bytes_allocated);
1898 }
1899 if (kUseBakerReadBarrier) {
1900 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr());
1901 }
1902 DCHECK(GetFwdPtr(from_ref) == to_ref);
1903 CHECK_NE(to_ref->GetLockWord(false).GetState(), LockWord::kForwardingAddress);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001904 PushOntoMarkStack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001905 return to_ref;
1906 } else {
1907 // The CAS failed. It may have lost the race or may have failed
1908 // due to monitor/hashcode ops. Either way, retry.
1909 }
1910 }
1911}
1912
1913mirror::Object* ConcurrentCopying::IsMarked(mirror::Object* from_ref) {
1914 DCHECK(from_ref != nullptr);
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08001915 space::RegionSpace::RegionType rtype = region_space_->GetRegionType(from_ref);
1916 if (rtype == space::RegionSpace::RegionType::kRegionTypeToSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001917 // It's already marked.
1918 return from_ref;
1919 }
1920 mirror::Object* to_ref;
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08001921 if (rtype == space::RegionSpace::RegionType::kRegionTypeFromSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001922 to_ref = GetFwdPtr(from_ref);
1923 DCHECK(to_ref == nullptr || region_space_->IsInToSpace(to_ref) ||
1924 heap_->non_moving_space_->HasAddress(to_ref))
1925 << "from_ref=" << from_ref << " to_ref=" << to_ref;
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08001926 } else if (rtype == space::RegionSpace::RegionType::kRegionTypeUnevacFromSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001927 if (region_space_bitmap_->Test(from_ref)) {
1928 to_ref = from_ref;
1929 } else {
1930 to_ref = nullptr;
1931 }
1932 } else {
1933 // from_ref is in a non-moving space.
1934 if (immune_region_.ContainsObject(from_ref)) {
1935 accounting::ContinuousSpaceBitmap* cc_bitmap =
1936 cc_heap_bitmap_->GetContinuousSpaceBitmap(from_ref);
1937 DCHECK(cc_bitmap != nullptr)
1938 << "An immune space object must have a bitmap";
1939 if (kIsDebugBuild) {
1940 DCHECK(heap_mark_bitmap_->GetContinuousSpaceBitmap(from_ref)->Test(from_ref))
1941 << "Immune space object must be already marked";
1942 }
1943 if (cc_bitmap->Test(from_ref)) {
1944 // Already marked.
1945 to_ref = from_ref;
1946 } else {
1947 // Newly marked.
1948 to_ref = nullptr;
1949 }
1950 } else {
1951 // Non-immune non-moving space. Use the mark bitmap.
1952 accounting::ContinuousSpaceBitmap* mark_bitmap =
1953 heap_mark_bitmap_->GetContinuousSpaceBitmap(from_ref);
1954 accounting::LargeObjectBitmap* los_bitmap =
1955 heap_mark_bitmap_->GetLargeObjectBitmap(from_ref);
1956 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
1957 bool is_los = mark_bitmap == nullptr;
1958 if (!is_los && mark_bitmap->Test(from_ref)) {
1959 // Already marked.
1960 to_ref = from_ref;
1961 } else if (is_los && los_bitmap->Test(from_ref)) {
1962 // Already marked in LOS.
1963 to_ref = from_ref;
1964 } else {
1965 // Not marked.
1966 if (IsOnAllocStack(from_ref)) {
1967 // If on the allocation stack, it's considered marked.
1968 to_ref = from_ref;
1969 } else {
1970 // Not marked.
1971 to_ref = nullptr;
1972 }
1973 }
1974 }
1975 }
1976 return to_ref;
1977}
1978
1979bool ConcurrentCopying::IsOnAllocStack(mirror::Object* ref) {
1980 QuasiAtomic::ThreadFenceAcquire();
1981 accounting::ObjectStack* alloc_stack = GetAllocationStack();
Mathieu Chartiercb535da2015-01-23 13:50:03 -08001982 return alloc_stack->Contains(ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001983}
1984
1985mirror::Object* ConcurrentCopying::Mark(mirror::Object* from_ref) {
1986 if (from_ref == nullptr) {
1987 return nullptr;
1988 }
1989 DCHECK(from_ref != nullptr);
1990 DCHECK(heap_->collector_type_ == kCollectorTypeCC);
Hiroshi Yamauchi60f63f52015-04-23 16:12:40 -07001991 if (kUseBakerReadBarrier && !is_active_) {
1992 // In the lock word forward address state, the read barrier bits
1993 // in the lock word are part of the stored forwarding address and
1994 // invalid. This is usually OK as the from-space copy of objects
1995 // aren't accessed by mutators due to the to-space
1996 // invariant. However, during the dex2oat image writing relocation
1997 // and the zygote compaction, objects can be in the forward
1998 // address state (to store the forward/relocation addresses) and
1999 // they can still be accessed and the invalid read barrier bits
2000 // are consulted. If they look like gray but aren't really, the
2001 // read barriers slow path can trigger when it shouldn't. To guard
2002 // against this, return here if the CC collector isn't running.
2003 return from_ref;
2004 }
2005 DCHECK(region_space_ != nullptr) << "Read barrier slow path taken when CC isn't running?";
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08002006 space::RegionSpace::RegionType rtype = region_space_->GetRegionType(from_ref);
2007 if (rtype == space::RegionSpace::RegionType::kRegionTypeToSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002008 // It's already marked.
2009 return from_ref;
2010 }
2011 mirror::Object* to_ref;
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08002012 if (rtype == space::RegionSpace::RegionType::kRegionTypeFromSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002013 to_ref = GetFwdPtr(from_ref);
2014 if (kUseBakerReadBarrier) {
2015 DCHECK(to_ref != ReadBarrier::GrayPtr()) << "from_ref=" << from_ref << " to_ref=" << to_ref;
2016 }
2017 if (to_ref == nullptr) {
2018 // It isn't marked yet. Mark it by copying it to the to-space.
2019 to_ref = Copy(from_ref);
2020 }
2021 DCHECK(region_space_->IsInToSpace(to_ref) || heap_->non_moving_space_->HasAddress(to_ref))
2022 << "from_ref=" << from_ref << " to_ref=" << to_ref;
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08002023 } else if (rtype == space::RegionSpace::RegionType::kRegionTypeUnevacFromSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002024 // This may or may not succeed, which is ok.
2025 if (kUseBakerReadBarrier) {
2026 from_ref->AtomicSetReadBarrierPointer(ReadBarrier::WhitePtr(), ReadBarrier::GrayPtr());
2027 }
2028 if (region_space_bitmap_->AtomicTestAndSet(from_ref)) {
2029 // Already marked.
2030 to_ref = from_ref;
2031 } else {
2032 // Newly marked.
2033 to_ref = from_ref;
2034 if (kUseBakerReadBarrier) {
2035 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr());
2036 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002037 PushOntoMarkStack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002038 }
2039 } else {
2040 // from_ref is in a non-moving space.
2041 DCHECK(!region_space_->HasAddress(from_ref)) << from_ref;
2042 if (immune_region_.ContainsObject(from_ref)) {
2043 accounting::ContinuousSpaceBitmap* cc_bitmap =
2044 cc_heap_bitmap_->GetContinuousSpaceBitmap(from_ref);
2045 DCHECK(cc_bitmap != nullptr)
2046 << "An immune space object must have a bitmap";
2047 if (kIsDebugBuild) {
2048 DCHECK(heap_mark_bitmap_->GetContinuousSpaceBitmap(from_ref)->Test(from_ref))
2049 << "Immune space object must be already marked";
2050 }
2051 // This may or may not succeed, which is ok.
2052 if (kUseBakerReadBarrier) {
2053 from_ref->AtomicSetReadBarrierPointer(ReadBarrier::WhitePtr(), ReadBarrier::GrayPtr());
2054 }
2055 if (cc_bitmap->AtomicTestAndSet(from_ref)) {
2056 // Already marked.
2057 to_ref = from_ref;
2058 } else {
2059 // Newly marked.
2060 to_ref = from_ref;
2061 if (kUseBakerReadBarrier) {
2062 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr());
2063 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002064 PushOntoMarkStack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002065 }
2066 } else {
2067 // Use the mark bitmap.
2068 accounting::ContinuousSpaceBitmap* mark_bitmap =
2069 heap_mark_bitmap_->GetContinuousSpaceBitmap(from_ref);
2070 accounting::LargeObjectBitmap* los_bitmap =
2071 heap_mark_bitmap_->GetLargeObjectBitmap(from_ref);
2072 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
2073 bool is_los = mark_bitmap == nullptr;
2074 if (!is_los && mark_bitmap->Test(from_ref)) {
2075 // Already marked.
2076 to_ref = from_ref;
2077 if (kUseBakerReadBarrier) {
2078 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr() ||
2079 to_ref->GetReadBarrierPointer() == ReadBarrier::BlackPtr());
2080 }
2081 } else if (is_los && los_bitmap->Test(from_ref)) {
2082 // Already marked in LOS.
2083 to_ref = from_ref;
2084 if (kUseBakerReadBarrier) {
2085 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr() ||
2086 to_ref->GetReadBarrierPointer() == ReadBarrier::BlackPtr());
2087 }
2088 } else {
2089 // Not marked.
2090 if (IsOnAllocStack(from_ref)) {
2091 // If it's on the allocation stack, it's considered marked. Keep it white.
2092 to_ref = from_ref;
2093 // Objects on the allocation stack need not be marked.
2094 if (!is_los) {
2095 DCHECK(!mark_bitmap->Test(to_ref));
2096 } else {
2097 DCHECK(!los_bitmap->Test(to_ref));
2098 }
2099 if (kUseBakerReadBarrier) {
2100 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::WhitePtr());
2101 }
2102 } else {
2103 // Not marked or on the allocation stack. Try to mark it.
2104 // This may or may not succeed, which is ok.
2105 if (kUseBakerReadBarrier) {
2106 from_ref->AtomicSetReadBarrierPointer(ReadBarrier::WhitePtr(), ReadBarrier::GrayPtr());
2107 }
2108 if (!is_los && mark_bitmap->AtomicTestAndSet(from_ref)) {
2109 // Already marked.
2110 to_ref = from_ref;
2111 } else if (is_los && los_bitmap->AtomicTestAndSet(from_ref)) {
2112 // Already marked in LOS.
2113 to_ref = from_ref;
2114 } else {
2115 // Newly marked.
2116 to_ref = from_ref;
2117 if (kUseBakerReadBarrier) {
2118 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr());
2119 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002120 PushOntoMarkStack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002121 }
2122 }
2123 }
2124 }
2125 }
2126 return to_ref;
2127}
2128
2129void ConcurrentCopying::FinishPhase() {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002130 {
2131 MutexLock mu(Thread::Current(), mark_stack_lock_);
2132 CHECK_EQ(pooled_mark_stacks_.size(), kMarkStackPoolSize);
2133 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002134 region_space_ = nullptr;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002135 {
2136 MutexLock mu(Thread::Current(), skipped_blocks_lock_);
2137 skipped_blocks_map_.clear();
2138 }
2139 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
2140 heap_->ClearMarkedObjects();
2141}
2142
Mathieu Chartier97509952015-07-13 14:35:43 -07002143bool ConcurrentCopying::IsMarkedHeapReference(mirror::HeapReference<mirror::Object>* field) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002144 mirror::Object* from_ref = field->AsMirrorPtr();
Mathieu Chartier97509952015-07-13 14:35:43 -07002145 mirror::Object* to_ref = IsMarked(from_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002146 if (to_ref == nullptr) {
2147 return false;
2148 }
2149 if (from_ref != to_ref) {
2150 QuasiAtomic::ThreadFenceRelease();
2151 field->Assign(to_ref);
2152 QuasiAtomic::ThreadFenceSequentiallyConsistent();
2153 }
2154 return true;
2155}
2156
Mathieu Chartier97509952015-07-13 14:35:43 -07002157mirror::Object* ConcurrentCopying::MarkObject(mirror::Object* from_ref) {
2158 return Mark(from_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002159}
2160
2161void ConcurrentCopying::DelayReferenceReferent(mirror::Class* klass, mirror::Reference* reference) {
Mathieu Chartier97509952015-07-13 14:35:43 -07002162 heap_->GetReferenceProcessor()->DelayReferenceReferent(klass, reference, this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002163}
2164
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002165void ConcurrentCopying::ProcessReferences(Thread* self) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002166 TimingLogger::ScopedTiming split("ProcessReferences", GetTimings());
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002167 // 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 -08002168 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
2169 GetHeap()->GetReferenceProcessor()->ProcessReferences(
Mathieu Chartier97509952015-07-13 14:35:43 -07002170 true /*concurrent*/, GetTimings(), GetCurrentIteration()->GetClearSoftReferences(), this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002171}
2172
2173void ConcurrentCopying::RevokeAllThreadLocalBuffers() {
2174 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
2175 region_space_->RevokeAllThreadLocalBuffers();
2176}
2177
Hiroshi Yamauchid5307ec2014-03-27 21:07:51 -07002178} // namespace collector
2179} // namespace gc
2180} // namespace art