blob: 65e946fd790dd3977173512456a113b99e6351aa [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);
264 size_t barrier_count = Runtime::Current()->FlipThreadRoots(
265 &thread_flip_visitor, &flip_callback, this);
266 {
267 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
268 gc_barrier_->Increment(self, barrier_count);
269 }
270 is_asserting_to_space_invariant_ = true;
271 QuasiAtomic::ThreadFenceForConstructor();
272 if (kVerboseMode) {
273 LOG(INFO) << "time=" << region_space_->Time();
274 region_space_->DumpNonFreeRegions(LOG(INFO));
275 LOG(INFO) << "GC end of FlipThreadRoots";
276 }
277}
278
Mathieu Chartiera4f6af92015-08-11 17:35:25 -0700279void ConcurrentCopying::SwapStacks() {
280 heap_->SwapStacks();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800281}
282
283void ConcurrentCopying::RecordLiveStackFreezeSize(Thread* self) {
284 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
285 live_stack_freeze_size_ = heap_->GetLiveStack()->Size();
286}
287
288// Used to visit objects in the immune spaces.
289class ConcurrentCopyingImmuneSpaceObjVisitor {
290 public:
291 explicit ConcurrentCopyingImmuneSpaceObjVisitor(ConcurrentCopying* cc)
292 : collector_(cc) {}
293
Mathieu Chartier90443472015-07-16 20:32:27 -0700294 void operator()(mirror::Object* obj) const SHARED_REQUIRES(Locks::mutator_lock_)
295 SHARED_REQUIRES(Locks::heap_bitmap_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800296 DCHECK(obj != nullptr);
297 DCHECK(collector_->immune_region_.ContainsObject(obj));
298 accounting::ContinuousSpaceBitmap* cc_bitmap =
299 collector_->cc_heap_bitmap_->GetContinuousSpaceBitmap(obj);
300 DCHECK(cc_bitmap != nullptr)
301 << "An immune space object must have a bitmap";
302 if (kIsDebugBuild) {
303 DCHECK(collector_->heap_->GetMarkBitmap()->Test(obj))
304 << "Immune space object must be already marked";
305 }
306 // This may or may not succeed, which is ok.
307 if (kUseBakerReadBarrier) {
308 obj->AtomicSetReadBarrierPointer(ReadBarrier::WhitePtr(), ReadBarrier::GrayPtr());
309 }
310 if (cc_bitmap->AtomicTestAndSet(obj)) {
311 // Already marked. Do nothing.
312 } else {
313 // Newly marked. Set the gray bit and push it onto the mark stack.
314 CHECK(!kUseBakerReadBarrier || obj->GetReadBarrierPointer() == ReadBarrier::GrayPtr());
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700315 collector_->PushOntoMarkStack(obj);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800316 }
317 }
318
319 private:
Mathieu Chartier97509952015-07-13 14:35:43 -0700320 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800321};
322
323class EmptyCheckpoint : public Closure {
324 public:
325 explicit EmptyCheckpoint(ConcurrentCopying* concurrent_copying)
326 : concurrent_copying_(concurrent_copying) {
327 }
328
329 virtual void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
330 // Note: self is not necessarily equal to thread since thread may be suspended.
331 Thread* self = Thread::Current();
332 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
333 << thread->GetState() << " thread " << thread << " self " << self;
Lei Lidd9943d2015-02-02 14:24:44 +0800334 // If thread is a running mutator, then act on behalf of the garbage collector.
335 // See the code in ThreadList::RunCheckpoint.
336 if (thread->GetState() == kRunnable) {
337 concurrent_copying_->GetBarrier().Pass(self);
338 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800339 }
340
341 private:
342 ConcurrentCopying* const concurrent_copying_;
343};
344
345// Concurrently mark roots that are guarded by read barriers and process the mark stack.
346void ConcurrentCopying::MarkingPhase() {
347 TimingLogger::ScopedTiming split("MarkingPhase", GetTimings());
348 if (kVerboseMode) {
349 LOG(INFO) << "GC MarkingPhase";
350 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700351 CHECK(weak_ref_access_enabled_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800352 {
353 // Mark the image root. The WB-based collectors do not need to
354 // scan the image objects from roots by relying on the card table,
355 // but it's necessary for the RB to-space invariant to hold.
356 TimingLogger::ScopedTiming split1("VisitImageRoots", GetTimings());
357 gc::space::ImageSpace* image = heap_->GetImageSpace();
358 if (image != nullptr) {
359 mirror::ObjectArray<mirror::Object>* image_root = image->GetImageHeader().GetImageRoots();
360 mirror::Object* marked_image_root = Mark(image_root);
361 CHECK_EQ(image_root, marked_image_root) << "An image object does not move";
362 if (ReadBarrier::kEnableToSpaceInvariantChecks) {
363 AssertToSpaceInvariant(nullptr, MemberOffset(0), marked_image_root);
364 }
365 }
366 }
Man Cao41656de2015-07-06 18:53:15 -0700367 // TODO: Other garbage collectors uses Runtime::VisitConcurrentRoots(), refactor this part
368 // to also use the same function.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800369 {
370 TimingLogger::ScopedTiming split2("VisitConstantRoots", GetTimings());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700371 Runtime::Current()->VisitConstantRoots(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800372 }
373 {
374 TimingLogger::ScopedTiming split3("VisitInternTableRoots", GetTimings());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700375 Runtime::Current()->GetInternTable()->VisitRoots(this, kVisitRootFlagAllRoots);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800376 }
377 {
378 TimingLogger::ScopedTiming split4("VisitClassLinkerRoots", GetTimings());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700379 Runtime::Current()->GetClassLinker()->VisitRoots(this, kVisitRootFlagAllRoots);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800380 }
381 {
382 // TODO: don't visit the transaction roots if it's not active.
383 TimingLogger::ScopedTiming split5("VisitNonThreadRoots", GetTimings());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700384 Runtime::Current()->VisitNonThreadRoots(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800385 }
Man Cao41656de2015-07-06 18:53:15 -0700386 Runtime::Current()->GetHeap()->VisitAllocationRecords(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800387
388 // Immune spaces.
389 for (auto& space : heap_->GetContinuousSpaces()) {
390 if (immune_region_.ContainsSpace(space)) {
391 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
392 accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
393 ConcurrentCopyingImmuneSpaceObjVisitor visitor(this);
394 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()),
395 reinterpret_cast<uintptr_t>(space->Limit()),
396 visitor);
397 }
398 }
399
400 Thread* self = Thread::Current();
401 {
402 TimingLogger::ScopedTiming split6("ProcessMarkStack", GetTimings());
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700403 // We transition through three mark stack modes (thread-local, shared, GC-exclusive). The
404 // primary reasons are the fact that we need to use a checkpoint to process thread-local mark
405 // stacks, but after we disable weak refs accesses, we can't use a checkpoint due to a deadlock
406 // issue because running threads potentially blocking at WaitHoldingLocks, and that once we
407 // reach the point where we process weak references, we can avoid using a lock when accessing
408 // the GC mark stack, which makes mark stack processing more efficient.
409
410 // Process the mark stack once in the thread local stack mode. This marks most of the live
411 // objects, aside from weak ref accesses with read barriers (Reference::GetReferent() and system
412 // weaks) that may happen concurrently while we processing the mark stack and newly mark/gray
413 // objects and push refs on the mark stack.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800414 ProcessMarkStack();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700415 // Switch to the shared mark stack mode. That is, revoke and process thread-local mark stacks
416 // for the last time before transitioning to the shared mark stack mode, which would process new
417 // refs that may have been concurrently pushed onto the mark stack during the ProcessMarkStack()
418 // call above. At the same time, disable weak ref accesses using a per-thread flag. It's
419 // important to do these together in a single checkpoint so that we can ensure that mutators
420 // won't newly gray objects and push new refs onto the mark stack due to weak ref accesses and
421 // mutators safely transition to the shared mark stack mode (without leaving unprocessed refs on
422 // the thread-local mark stacks), without a race. This is why we use a thread-local weak ref
423 // access flag Thread::tls32_.weak_ref_access_enabled_ instead of the global ones.
424 SwitchToSharedMarkStackMode();
425 CHECK(!self->GetWeakRefAccessEnabled());
426 // Now that weak refs accesses are disabled, once we exhaust the shared mark stack again here
427 // (which may be non-empty if there were refs found on thread-local mark stacks during the above
428 // SwitchToSharedMarkStackMode() call), we won't have new refs to process, that is, mutators
429 // (via read barriers) have no way to produce any more refs to process. Marking converges once
430 // before we process weak refs below.
431 ProcessMarkStack();
432 CheckEmptyMarkStack();
433 // Switch to the GC exclusive mark stack mode so that we can process the mark stack without a
434 // lock from this point on.
435 SwitchToGcExclusiveMarkStackMode();
436 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800437 if (kVerboseMode) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800438 LOG(INFO) << "ProcessReferences";
439 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700440 // Process weak references. This may produce new refs to process and have them processed via
Mathieu Chartier97509952015-07-13 14:35:43 -0700441 // ProcessMarkStack (in the GC exclusive mark stack mode).
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700442 ProcessReferences(self);
443 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800444 if (kVerboseMode) {
445 LOG(INFO) << "SweepSystemWeaks";
446 }
447 SweepSystemWeaks(self);
448 if (kVerboseMode) {
449 LOG(INFO) << "SweepSystemWeaks done";
450 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700451 // Process the mark stack here one last time because the above SweepSystemWeaks() call may have
452 // marked some objects (strings alive) as hash_set::Erase() can call the hash function for
453 // arbitrary elements in the weak intern table in InternTable::Table::SweepWeaks().
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800454 ProcessMarkStack();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700455 CheckEmptyMarkStack();
456 // Re-enable weak ref accesses.
457 ReenableWeakRefAccess(self);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700458 // Marking is done. Disable marking.
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700459 DisableMarking();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700460 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800461 }
462
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700463 CHECK(weak_ref_access_enabled_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800464 if (kVerboseMode) {
465 LOG(INFO) << "GC end of MarkingPhase";
466 }
467}
468
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700469void ConcurrentCopying::ReenableWeakRefAccess(Thread* self) {
470 if (kVerboseMode) {
471 LOG(INFO) << "ReenableWeakRefAccess";
472 }
473 weak_ref_access_enabled_.StoreRelaxed(true); // This is for new threads.
474 QuasiAtomic::ThreadFenceForConstructor();
475 // Iterate all threads (don't need to or can't use a checkpoint) and re-enable weak ref access.
476 {
477 MutexLock mu(self, *Locks::thread_list_lock_);
478 std::list<Thread*> thread_list = Runtime::Current()->GetThreadList()->GetList();
479 for (Thread* thread : thread_list) {
480 thread->SetWeakRefAccessEnabled(true);
481 }
482 }
483 // Unblock blocking threads.
484 GetHeap()->GetReferenceProcessor()->BroadcastForSlowPath(self);
485 Runtime::Current()->BroadcastForNewSystemWeaks();
486}
487
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700488class DisableMarkingCheckpoint : public Closure {
489 public:
490 explicit DisableMarkingCheckpoint(ConcurrentCopying* concurrent_copying)
491 : concurrent_copying_(concurrent_copying) {
492 }
493
494 void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
495 // Note: self is not necessarily equal to thread since thread may be suspended.
496 Thread* self = Thread::Current();
497 DCHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
498 << thread->GetState() << " thread " << thread << " self " << self;
499 // Disable the thread-local is_gc_marking flag.
500 DCHECK(thread->GetIsGcMarking());
501 thread->SetIsGcMarking(false);
502 // If thread is a running mutator, then act on behalf of the garbage collector.
503 // See the code in ThreadList::RunCheckpoint.
504 if (thread->GetState() == kRunnable) {
505 concurrent_copying_->GetBarrier().Pass(self);
506 }
507 }
508
509 private:
510 ConcurrentCopying* const concurrent_copying_;
511};
512
513void ConcurrentCopying::IssueDisableMarkingCheckpoint() {
514 Thread* self = Thread::Current();
515 DisableMarkingCheckpoint check_point(this);
516 ThreadList* thread_list = Runtime::Current()->GetThreadList();
517 gc_barrier_->Init(self, 0);
518 size_t barrier_count = thread_list->RunCheckpoint(&check_point);
519 // If there are no threads to wait which implies that all the checkpoint functions are finished,
520 // then no need to release the mutator lock.
521 if (barrier_count == 0) {
522 return;
523 }
524 // Release locks then wait for all mutator threads to pass the barrier.
525 Locks::mutator_lock_->SharedUnlock(self);
526 {
527 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
528 gc_barrier_->Increment(self, barrier_count);
529 }
530 Locks::mutator_lock_->SharedLock(self);
531}
532
533void ConcurrentCopying::DisableMarking() {
534 // Change the global is_marking flag to false. Do a fence before doing a checkpoint to update the
535 // thread-local flags so that a new thread starting up will get the correct is_marking flag.
536 is_marking_ = false;
537 QuasiAtomic::ThreadFenceForConstructor();
538 // Use a checkpoint to turn off the thread-local is_gc_marking flags and to ensure no threads are
539 // still in the middle of a read barrier which may have a from-space ref cached in a local
540 // variable.
541 IssueDisableMarkingCheckpoint();
542 if (kUseTableLookupReadBarrier) {
543 heap_->rb_table_->ClearAll();
544 DCHECK(heap_->rb_table_->IsAllCleared());
545 }
546 is_mark_stack_push_disallowed_.StoreSequentiallyConsistent(1);
547 mark_stack_mode_.StoreSequentiallyConsistent(kMarkStackModeOff);
548}
549
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800550void ConcurrentCopying::IssueEmptyCheckpoint() {
551 Thread* self = Thread::Current();
552 EmptyCheckpoint check_point(this);
553 ThreadList* thread_list = Runtime::Current()->GetThreadList();
554 gc_barrier_->Init(self, 0);
555 size_t barrier_count = thread_list->RunCheckpoint(&check_point);
Lei Lidd9943d2015-02-02 14:24:44 +0800556 // If there are no threads to wait which implys that all the checkpoint functions are finished,
557 // then no need to release the mutator lock.
558 if (barrier_count == 0) {
559 return;
560 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800561 // Release locks then wait for all mutator threads to pass the barrier.
562 Locks::mutator_lock_->SharedUnlock(self);
563 {
564 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
565 gc_barrier_->Increment(self, barrier_count);
566 }
567 Locks::mutator_lock_->SharedLock(self);
568}
569
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800570void ConcurrentCopying::PushOntoMarkStack(mirror::Object* to_ref) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700571 CHECK_EQ(is_mark_stack_push_disallowed_.LoadRelaxed(), 0)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800572 << " " << to_ref << " " << PrettyTypeOf(to_ref);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700573 Thread* self = Thread::Current(); // TODO: pass self as an argument from call sites?
574 CHECK(thread_running_gc_ != nullptr);
575 MarkStackMode mark_stack_mode = mark_stack_mode_.LoadRelaxed();
576 if (mark_stack_mode == kMarkStackModeThreadLocal) {
577 if (self == thread_running_gc_) {
578 // If GC-running thread, use the GC mark stack instead of a thread-local mark stack.
579 CHECK(self->GetThreadLocalMarkStack() == nullptr);
580 CHECK(!gc_mark_stack_->IsFull());
581 gc_mark_stack_->PushBack(to_ref);
582 } else {
583 // Otherwise, use a thread-local mark stack.
584 accounting::AtomicStack<mirror::Object>* tl_mark_stack = self->GetThreadLocalMarkStack();
585 if (UNLIKELY(tl_mark_stack == nullptr || tl_mark_stack->IsFull())) {
586 MutexLock mu(self, mark_stack_lock_);
587 // Get a new thread local mark stack.
588 accounting::AtomicStack<mirror::Object>* new_tl_mark_stack;
589 if (!pooled_mark_stacks_.empty()) {
590 // Use a pooled mark stack.
591 new_tl_mark_stack = pooled_mark_stacks_.back();
592 pooled_mark_stacks_.pop_back();
593 } else {
594 // None pooled. Create a new one.
595 new_tl_mark_stack =
596 accounting::AtomicStack<mirror::Object>::Create(
597 "thread local mark stack", 4 * KB, 4 * KB);
598 }
599 DCHECK(new_tl_mark_stack != nullptr);
600 DCHECK(new_tl_mark_stack->IsEmpty());
601 new_tl_mark_stack->PushBack(to_ref);
602 self->SetThreadLocalMarkStack(new_tl_mark_stack);
603 if (tl_mark_stack != nullptr) {
604 // Store the old full stack into a vector.
605 revoked_mark_stacks_.push_back(tl_mark_stack);
606 }
607 } else {
608 tl_mark_stack->PushBack(to_ref);
609 }
610 }
611 } else if (mark_stack_mode == kMarkStackModeShared) {
612 // Access the shared GC mark stack with a lock.
613 MutexLock mu(self, mark_stack_lock_);
614 CHECK(!gc_mark_stack_->IsFull());
615 gc_mark_stack_->PushBack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800616 } else {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700617 CHECK_EQ(static_cast<uint32_t>(mark_stack_mode),
618 static_cast<uint32_t>(kMarkStackModeGcExclusive));
619 CHECK(self == thread_running_gc_)
620 << "Only GC-running thread should access the mark stack "
621 << "in the GC exclusive mark stack mode";
622 // Access the GC mark stack without a lock.
623 CHECK(!gc_mark_stack_->IsFull());
624 gc_mark_stack_->PushBack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800625 }
626}
627
628accounting::ObjectStack* ConcurrentCopying::GetAllocationStack() {
629 return heap_->allocation_stack_.get();
630}
631
632accounting::ObjectStack* ConcurrentCopying::GetLiveStack() {
633 return heap_->live_stack_.get();
634}
635
636inline mirror::Object* ConcurrentCopying::GetFwdPtr(mirror::Object* from_ref) {
637 DCHECK(region_space_->IsInFromSpace(from_ref));
638 LockWord lw = from_ref->GetLockWord(false);
639 if (lw.GetState() == LockWord::kForwardingAddress) {
640 mirror::Object* fwd_ptr = reinterpret_cast<mirror::Object*>(lw.ForwardingAddress());
641 CHECK(fwd_ptr != nullptr);
642 return fwd_ptr;
643 } else {
644 return nullptr;
645 }
646}
647
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800648// The following visitors are that used to verify that there's no
649// references to the from-space left after marking.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700650class ConcurrentCopyingVerifyNoFromSpaceRefsVisitor : public SingleRootVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800651 public:
652 explicit ConcurrentCopyingVerifyNoFromSpaceRefsVisitor(ConcurrentCopying* collector)
653 : collector_(collector) {}
654
655 void operator()(mirror::Object* ref) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700656 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800657 if (ref == nullptr) {
658 // OK.
659 return;
660 }
661 collector_->AssertToSpaceInvariant(nullptr, MemberOffset(0), ref);
662 if (kUseBakerReadBarrier) {
663 if (collector_->RegionSpace()->IsInToSpace(ref)) {
664 CHECK(ref->GetReadBarrierPointer() == nullptr)
665 << "To-space ref " << ref << " " << PrettyTypeOf(ref)
666 << " has non-white rb_ptr " << ref->GetReadBarrierPointer();
667 } else {
668 CHECK(ref->GetReadBarrierPointer() == ReadBarrier::BlackPtr() ||
669 (ref->GetReadBarrierPointer() == ReadBarrier::WhitePtr() &&
670 collector_->IsOnAllocStack(ref)))
671 << "Non-moving/unevac from space ref " << ref << " " << PrettyTypeOf(ref)
672 << " has non-black rb_ptr " << ref->GetReadBarrierPointer()
673 << " but isn't on the alloc stack (and has white rb_ptr)."
674 << " Is it in the non-moving space="
675 << (collector_->GetHeap()->GetNonMovingSpace()->HasAddress(ref));
676 }
677 }
678 }
679
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700680 void VisitRoot(mirror::Object* root, const RootInfo& info ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -0700681 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800682 DCHECK(root != nullptr);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700683 operator()(root);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800684 }
685
686 private:
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700687 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800688};
689
690class ConcurrentCopyingVerifyNoFromSpaceRefsFieldVisitor {
691 public:
692 explicit ConcurrentCopyingVerifyNoFromSpaceRefsFieldVisitor(ConcurrentCopying* collector)
693 : collector_(collector) {}
694
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700695 void operator()(mirror::Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700696 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800697 mirror::Object* ref =
698 obj->GetFieldObject<mirror::Object, kDefaultVerifyFlags, kWithoutReadBarrier>(offset);
699 ConcurrentCopyingVerifyNoFromSpaceRefsVisitor visitor(collector_);
700 visitor(ref);
701 }
702 void operator()(mirror::Class* klass, mirror::Reference* ref) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700703 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800704 CHECK(klass->IsTypeOfReferenceClass());
705 this->operator()(ref, mirror::Reference::ReferentOffset(), false);
706 }
707
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700708 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
709 SHARED_REQUIRES(Locks::mutator_lock_) {
710 if (!root->IsNull()) {
711 VisitRoot(root);
712 }
713 }
714
715 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
716 SHARED_REQUIRES(Locks::mutator_lock_) {
717 ConcurrentCopyingVerifyNoFromSpaceRefsVisitor visitor(collector_);
718 visitor(root->AsMirrorPtr());
719 }
720
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800721 private:
Mathieu Chartier97509952015-07-13 14:35:43 -0700722 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800723};
724
725class ConcurrentCopyingVerifyNoFromSpaceRefsObjectVisitor {
726 public:
727 explicit ConcurrentCopyingVerifyNoFromSpaceRefsObjectVisitor(ConcurrentCopying* collector)
728 : collector_(collector) {}
729 void operator()(mirror::Object* obj) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700730 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800731 ObjectCallback(obj, collector_);
732 }
733 static void ObjectCallback(mirror::Object* obj, void *arg)
Mathieu Chartier90443472015-07-16 20:32:27 -0700734 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800735 CHECK(obj != nullptr);
736 ConcurrentCopying* collector = reinterpret_cast<ConcurrentCopying*>(arg);
737 space::RegionSpace* region_space = collector->RegionSpace();
738 CHECK(!region_space->IsInFromSpace(obj)) << "Scanning object " << obj << " in from space";
739 ConcurrentCopyingVerifyNoFromSpaceRefsFieldVisitor visitor(collector);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -0700740 obj->VisitReferences(visitor, visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800741 if (kUseBakerReadBarrier) {
742 if (collector->RegionSpace()->IsInToSpace(obj)) {
743 CHECK(obj->GetReadBarrierPointer() == nullptr)
744 << "obj=" << obj << " non-white rb_ptr " << obj->GetReadBarrierPointer();
745 } else {
746 CHECK(obj->GetReadBarrierPointer() == ReadBarrier::BlackPtr() ||
747 (obj->GetReadBarrierPointer() == ReadBarrier::WhitePtr() &&
748 collector->IsOnAllocStack(obj)))
749 << "Non-moving space/unevac from space ref " << obj << " " << PrettyTypeOf(obj)
750 << " has non-black rb_ptr " << obj->GetReadBarrierPointer()
751 << " but isn't on the alloc stack (and has white rb_ptr). Is it in the non-moving space="
752 << (collector->GetHeap()->GetNonMovingSpace()->HasAddress(obj));
753 }
754 }
755 }
756
757 private:
758 ConcurrentCopying* const collector_;
759};
760
761// Verify there's no from-space references left after the marking phase.
762void ConcurrentCopying::VerifyNoFromSpaceReferences() {
763 Thread* self = Thread::Current();
764 DCHECK(Locks::mutator_lock_->IsExclusiveHeld(self));
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700765 // Verify all threads have is_gc_marking to be false
766 {
767 MutexLock mu(self, *Locks::thread_list_lock_);
768 std::list<Thread*> thread_list = Runtime::Current()->GetThreadList()->GetList();
769 for (Thread* thread : thread_list) {
770 CHECK(!thread->GetIsGcMarking());
771 }
772 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800773 ConcurrentCopyingVerifyNoFromSpaceRefsObjectVisitor visitor(this);
774 // Roots.
775 {
776 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700777 ConcurrentCopyingVerifyNoFromSpaceRefsVisitor ref_visitor(this);
778 Runtime::Current()->VisitRoots(&ref_visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800779 }
780 // The to-space.
781 region_space_->WalkToSpace(ConcurrentCopyingVerifyNoFromSpaceRefsObjectVisitor::ObjectCallback,
782 this);
783 // Non-moving spaces.
784 {
785 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
786 heap_->GetMarkBitmap()->Visit(visitor);
787 }
788 // The alloc stack.
789 {
790 ConcurrentCopyingVerifyNoFromSpaceRefsVisitor ref_visitor(this);
Mathieu Chartiercb535da2015-01-23 13:50:03 -0800791 for (auto* it = heap_->allocation_stack_->Begin(), *end = heap_->allocation_stack_->End();
792 it < end; ++it) {
793 mirror::Object* const obj = it->AsMirrorPtr();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800794 if (obj != nullptr && obj->GetClass() != nullptr) {
795 // TODO: need to call this only if obj is alive?
796 ref_visitor(obj);
797 visitor(obj);
798 }
799 }
800 }
801 // TODO: LOS. But only refs in LOS are classes.
802}
803
804// The following visitors are used to assert the to-space invariant.
805class ConcurrentCopyingAssertToSpaceInvariantRefsVisitor {
806 public:
807 explicit ConcurrentCopyingAssertToSpaceInvariantRefsVisitor(ConcurrentCopying* collector)
808 : collector_(collector) {}
809
810 void operator()(mirror::Object* ref) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700811 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800812 if (ref == nullptr) {
813 // OK.
814 return;
815 }
816 collector_->AssertToSpaceInvariant(nullptr, MemberOffset(0), ref);
817 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800818
819 private:
Mathieu Chartier97509952015-07-13 14:35:43 -0700820 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800821};
822
823class ConcurrentCopyingAssertToSpaceInvariantFieldVisitor {
824 public:
825 explicit ConcurrentCopyingAssertToSpaceInvariantFieldVisitor(ConcurrentCopying* collector)
826 : collector_(collector) {}
827
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700828 void operator()(mirror::Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700829 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800830 mirror::Object* ref =
831 obj->GetFieldObject<mirror::Object, kDefaultVerifyFlags, kWithoutReadBarrier>(offset);
832 ConcurrentCopyingAssertToSpaceInvariantRefsVisitor visitor(collector_);
833 visitor(ref);
834 }
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700835 void operator()(mirror::Class* klass, mirror::Reference* ref ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700836 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800837 CHECK(klass->IsTypeOfReferenceClass());
838 }
839
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700840 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
841 SHARED_REQUIRES(Locks::mutator_lock_) {
842 if (!root->IsNull()) {
843 VisitRoot(root);
844 }
845 }
846
847 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
848 SHARED_REQUIRES(Locks::mutator_lock_) {
849 ConcurrentCopyingAssertToSpaceInvariantRefsVisitor visitor(collector_);
850 visitor(root->AsMirrorPtr());
851 }
852
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800853 private:
Mathieu Chartier97509952015-07-13 14:35:43 -0700854 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800855};
856
857class ConcurrentCopyingAssertToSpaceInvariantObjectVisitor {
858 public:
859 explicit ConcurrentCopyingAssertToSpaceInvariantObjectVisitor(ConcurrentCopying* collector)
860 : collector_(collector) {}
861 void operator()(mirror::Object* obj) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700862 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800863 ObjectCallback(obj, collector_);
864 }
865 static void ObjectCallback(mirror::Object* obj, void *arg)
Mathieu Chartier90443472015-07-16 20:32:27 -0700866 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800867 CHECK(obj != nullptr);
868 ConcurrentCopying* collector = reinterpret_cast<ConcurrentCopying*>(arg);
869 space::RegionSpace* region_space = collector->RegionSpace();
870 CHECK(!region_space->IsInFromSpace(obj)) << "Scanning object " << obj << " in from space";
871 collector->AssertToSpaceInvariant(nullptr, MemberOffset(0), obj);
872 ConcurrentCopyingAssertToSpaceInvariantFieldVisitor visitor(collector);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -0700873 obj->VisitReferences(visitor, visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800874 }
875
876 private:
Mathieu Chartier97509952015-07-13 14:35:43 -0700877 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800878};
879
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700880class RevokeThreadLocalMarkStackCheckpoint : public Closure {
881 public:
Roland Levillain3887c462015-08-12 18:15:42 +0100882 RevokeThreadLocalMarkStackCheckpoint(ConcurrentCopying* concurrent_copying,
883 bool disable_weak_ref_access)
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700884 : concurrent_copying_(concurrent_copying),
885 disable_weak_ref_access_(disable_weak_ref_access) {
886 }
887
888 virtual void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
889 // Note: self is not necessarily equal to thread since thread may be suspended.
890 Thread* self = Thread::Current();
891 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
892 << thread->GetState() << " thread " << thread << " self " << self;
893 // Revoke thread local mark stacks.
894 accounting::AtomicStack<mirror::Object>* tl_mark_stack = thread->GetThreadLocalMarkStack();
895 if (tl_mark_stack != nullptr) {
896 MutexLock mu(self, concurrent_copying_->mark_stack_lock_);
897 concurrent_copying_->revoked_mark_stacks_.push_back(tl_mark_stack);
898 thread->SetThreadLocalMarkStack(nullptr);
899 }
900 // Disable weak ref access.
901 if (disable_weak_ref_access_) {
902 thread->SetWeakRefAccessEnabled(false);
903 }
904 // If thread is a running mutator, then act on behalf of the garbage collector.
905 // See the code in ThreadList::RunCheckpoint.
906 if (thread->GetState() == kRunnable) {
907 concurrent_copying_->GetBarrier().Pass(self);
908 }
909 }
910
911 private:
912 ConcurrentCopying* const concurrent_copying_;
913 const bool disable_weak_ref_access_;
914};
915
916void ConcurrentCopying::RevokeThreadLocalMarkStacks(bool disable_weak_ref_access) {
917 Thread* self = Thread::Current();
918 RevokeThreadLocalMarkStackCheckpoint check_point(this, disable_weak_ref_access);
919 ThreadList* thread_list = Runtime::Current()->GetThreadList();
920 gc_barrier_->Init(self, 0);
921 size_t barrier_count = thread_list->RunCheckpoint(&check_point);
922 // If there are no threads to wait which implys that all the checkpoint functions are finished,
923 // then no need to release the mutator lock.
924 if (barrier_count == 0) {
925 return;
926 }
927 Locks::mutator_lock_->SharedUnlock(self);
928 {
929 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
930 gc_barrier_->Increment(self, barrier_count);
931 }
932 Locks::mutator_lock_->SharedLock(self);
933}
934
935void ConcurrentCopying::RevokeThreadLocalMarkStack(Thread* thread) {
936 Thread* self = Thread::Current();
937 CHECK_EQ(self, thread);
938 accounting::AtomicStack<mirror::Object>* tl_mark_stack = thread->GetThreadLocalMarkStack();
939 if (tl_mark_stack != nullptr) {
940 CHECK(is_marking_);
941 MutexLock mu(self, mark_stack_lock_);
942 revoked_mark_stacks_.push_back(tl_mark_stack);
943 thread->SetThreadLocalMarkStack(nullptr);
944 }
945}
946
947void ConcurrentCopying::ProcessMarkStack() {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800948 if (kVerboseMode) {
949 LOG(INFO) << "ProcessMarkStack. ";
950 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700951 bool empty_prev = false;
952 while (true) {
953 bool empty = ProcessMarkStackOnce();
954 if (empty_prev && empty) {
955 // Saw empty mark stack for a second time, done.
956 break;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800957 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700958 empty_prev = empty;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800959 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700960}
961
962bool ConcurrentCopying::ProcessMarkStackOnce() {
963 Thread* self = Thread::Current();
964 CHECK(thread_running_gc_ != nullptr);
965 CHECK(self == thread_running_gc_);
966 CHECK(self->GetThreadLocalMarkStack() == nullptr);
967 size_t count = 0;
968 MarkStackMode mark_stack_mode = mark_stack_mode_.LoadRelaxed();
969 if (mark_stack_mode == kMarkStackModeThreadLocal) {
970 // Process the thread-local mark stacks and the GC mark stack.
971 count += ProcessThreadLocalMarkStacks(false);
972 while (!gc_mark_stack_->IsEmpty()) {
973 mirror::Object* to_ref = gc_mark_stack_->PopBack();
974 ProcessMarkStackRef(to_ref);
975 ++count;
976 }
977 gc_mark_stack_->Reset();
978 } else if (mark_stack_mode == kMarkStackModeShared) {
979 // Process the shared GC mark stack with a lock.
980 {
981 MutexLock mu(self, mark_stack_lock_);
982 CHECK(revoked_mark_stacks_.empty());
983 }
984 while (true) {
985 std::vector<mirror::Object*> refs;
986 {
987 // Copy refs with lock. Note the number of refs should be small.
988 MutexLock mu(self, mark_stack_lock_);
989 if (gc_mark_stack_->IsEmpty()) {
990 break;
991 }
992 for (StackReference<mirror::Object>* p = gc_mark_stack_->Begin();
993 p != gc_mark_stack_->End(); ++p) {
994 refs.push_back(p->AsMirrorPtr());
995 }
996 gc_mark_stack_->Reset();
997 }
998 for (mirror::Object* ref : refs) {
999 ProcessMarkStackRef(ref);
1000 ++count;
1001 }
1002 }
1003 } else {
1004 CHECK_EQ(static_cast<uint32_t>(mark_stack_mode),
1005 static_cast<uint32_t>(kMarkStackModeGcExclusive));
1006 {
1007 MutexLock mu(self, mark_stack_lock_);
1008 CHECK(revoked_mark_stacks_.empty());
1009 }
1010 // Process the GC mark stack in the exclusive mode. No need to take the lock.
1011 while (!gc_mark_stack_->IsEmpty()) {
1012 mirror::Object* to_ref = gc_mark_stack_->PopBack();
1013 ProcessMarkStackRef(to_ref);
1014 ++count;
1015 }
1016 gc_mark_stack_->Reset();
1017 }
1018
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001019 // Return true if the stack was empty.
1020 return count == 0;
1021}
1022
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001023size_t ConcurrentCopying::ProcessThreadLocalMarkStacks(bool disable_weak_ref_access) {
1024 // Run a checkpoint to collect all thread local mark stacks and iterate over them all.
1025 RevokeThreadLocalMarkStacks(disable_weak_ref_access);
1026 size_t count = 0;
1027 std::vector<accounting::AtomicStack<mirror::Object>*> mark_stacks;
1028 {
1029 MutexLock mu(Thread::Current(), mark_stack_lock_);
1030 // Make a copy of the mark stack vector.
1031 mark_stacks = revoked_mark_stacks_;
1032 revoked_mark_stacks_.clear();
1033 }
1034 for (accounting::AtomicStack<mirror::Object>* mark_stack : mark_stacks) {
1035 for (StackReference<mirror::Object>* p = mark_stack->Begin(); p != mark_stack->End(); ++p) {
1036 mirror::Object* to_ref = p->AsMirrorPtr();
1037 ProcessMarkStackRef(to_ref);
1038 ++count;
1039 }
1040 {
1041 MutexLock mu(Thread::Current(), mark_stack_lock_);
1042 if (pooled_mark_stacks_.size() >= kMarkStackPoolSize) {
1043 // The pool has enough. Delete it.
1044 delete mark_stack;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001045 } else {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001046 // Otherwise, put it into the pool for later reuse.
1047 mark_stack->Reset();
1048 pooled_mark_stacks_.push_back(mark_stack);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001049 }
1050 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001051 }
1052 return count;
1053}
1054
1055void ConcurrentCopying::ProcessMarkStackRef(mirror::Object* to_ref) {
1056 DCHECK(!region_space_->IsInFromSpace(to_ref));
1057 if (kUseBakerReadBarrier) {
1058 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr())
1059 << " " << to_ref << " " << to_ref->GetReadBarrierPointer()
1060 << " is_marked=" << IsMarked(to_ref);
1061 }
1062 // Scan ref fields.
1063 Scan(to_ref);
1064 // Mark the gray ref as white or black.
1065 if (kUseBakerReadBarrier) {
1066 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr())
1067 << " " << to_ref << " " << to_ref->GetReadBarrierPointer()
1068 << " is_marked=" << IsMarked(to_ref);
1069 }
1070 if (to_ref->GetClass<kVerifyNone, kWithoutReadBarrier>()->IsTypeOfReferenceClass() &&
1071 to_ref->AsReference()->GetReferent<kWithoutReadBarrier>() != nullptr &&
1072 !IsInToSpace(to_ref->AsReference()->GetReferent<kWithoutReadBarrier>())) {
1073 // Leave References gray so that GetReferent() will trigger RB.
1074 CHECK(to_ref->AsReference()->IsEnqueued()) << "Left unenqueued ref gray " << to_ref;
1075 } else {
1076#ifdef USE_BAKER_OR_BROOKS_READ_BARRIER
1077 if (kUseBakerReadBarrier) {
1078 if (region_space_->IsInToSpace(to_ref)) {
1079 // If to-space, change from gray to white.
1080 bool success = to_ref->AtomicSetReadBarrierPointer(ReadBarrier::GrayPtr(),
1081 ReadBarrier::WhitePtr());
1082 CHECK(success) << "Must succeed as we won the race.";
1083 CHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::WhitePtr());
1084 } else {
1085 // If non-moving space/unevac from space, change from gray
1086 // to black. We can't change gray to white because it's not
1087 // safe to use CAS if two threads change values in opposite
1088 // directions (A->B and B->A). So, we change it to black to
1089 // indicate non-moving objects that have been marked
1090 // through. Note we'd need to change from black to white
1091 // later (concurrently).
1092 bool success = to_ref->AtomicSetReadBarrierPointer(ReadBarrier::GrayPtr(),
1093 ReadBarrier::BlackPtr());
1094 CHECK(success) << "Must succeed as we won the race.";
1095 CHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::BlackPtr());
1096 }
1097 }
1098#else
1099 DCHECK(!kUseBakerReadBarrier);
1100#endif
1101 }
1102 if (ReadBarrier::kEnableToSpaceInvariantChecks || kIsDebugBuild) {
1103 ConcurrentCopyingAssertToSpaceInvariantObjectVisitor visitor(this);
1104 visitor(to_ref);
1105 }
1106}
1107
1108void ConcurrentCopying::SwitchToSharedMarkStackMode() {
1109 Thread* self = Thread::Current();
1110 CHECK(thread_running_gc_ != nullptr);
1111 CHECK_EQ(self, thread_running_gc_);
1112 CHECK(self->GetThreadLocalMarkStack() == nullptr);
1113 MarkStackMode before_mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1114 CHECK_EQ(static_cast<uint32_t>(before_mark_stack_mode),
1115 static_cast<uint32_t>(kMarkStackModeThreadLocal));
1116 mark_stack_mode_.StoreRelaxed(kMarkStackModeShared);
1117 CHECK(weak_ref_access_enabled_.LoadRelaxed());
1118 weak_ref_access_enabled_.StoreRelaxed(false);
1119 QuasiAtomic::ThreadFenceForConstructor();
1120 // Process the thread local mark stacks one last time after switching to the shared mark stack
1121 // mode and disable weak ref accesses.
1122 ProcessThreadLocalMarkStacks(true);
1123 if (kVerboseMode) {
1124 LOG(INFO) << "Switched to shared mark stack mode and disabled weak ref access";
1125 }
1126}
1127
1128void ConcurrentCopying::SwitchToGcExclusiveMarkStackMode() {
1129 Thread* self = Thread::Current();
1130 CHECK(thread_running_gc_ != nullptr);
1131 CHECK_EQ(self, thread_running_gc_);
1132 CHECK(self->GetThreadLocalMarkStack() == nullptr);
1133 MarkStackMode before_mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1134 CHECK_EQ(static_cast<uint32_t>(before_mark_stack_mode),
1135 static_cast<uint32_t>(kMarkStackModeShared));
1136 mark_stack_mode_.StoreRelaxed(kMarkStackModeGcExclusive);
1137 QuasiAtomic::ThreadFenceForConstructor();
1138 if (kVerboseMode) {
1139 LOG(INFO) << "Switched to GC exclusive mark stack mode";
1140 }
1141}
1142
1143void ConcurrentCopying::CheckEmptyMarkStack() {
1144 Thread* self = Thread::Current();
1145 CHECK(thread_running_gc_ != nullptr);
1146 CHECK_EQ(self, thread_running_gc_);
1147 CHECK(self->GetThreadLocalMarkStack() == nullptr);
1148 MarkStackMode mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1149 if (mark_stack_mode == kMarkStackModeThreadLocal) {
1150 // Thread-local mark stack mode.
1151 RevokeThreadLocalMarkStacks(false);
1152 MutexLock mu(Thread::Current(), mark_stack_lock_);
1153 if (!revoked_mark_stacks_.empty()) {
1154 for (accounting::AtomicStack<mirror::Object>* mark_stack : revoked_mark_stacks_) {
1155 while (!mark_stack->IsEmpty()) {
1156 mirror::Object* obj = mark_stack->PopBack();
1157 if (kUseBakerReadBarrier) {
1158 mirror::Object* rb_ptr = obj->GetReadBarrierPointer();
1159 LOG(INFO) << "On mark queue : " << obj << " " << PrettyTypeOf(obj) << " rb_ptr=" << rb_ptr
1160 << " is_marked=" << IsMarked(obj);
1161 } else {
1162 LOG(INFO) << "On mark queue : " << obj << " " << PrettyTypeOf(obj)
1163 << " is_marked=" << IsMarked(obj);
1164 }
1165 }
1166 }
1167 LOG(FATAL) << "mark stack is not empty";
1168 }
1169 } else {
1170 // Shared, GC-exclusive, or off.
1171 MutexLock mu(Thread::Current(), mark_stack_lock_);
1172 CHECK(gc_mark_stack_->IsEmpty());
1173 CHECK(revoked_mark_stacks_.empty());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001174 }
1175}
1176
1177void ConcurrentCopying::SweepSystemWeaks(Thread* self) {
1178 TimingLogger::ScopedTiming split("SweepSystemWeaks", GetTimings());
1179 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier97509952015-07-13 14:35:43 -07001180 Runtime::Current()->SweepSystemWeaks(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001181}
1182
1183void ConcurrentCopying::Sweep(bool swap_bitmaps) {
1184 {
1185 TimingLogger::ScopedTiming t("MarkStackAsLive", GetTimings());
1186 accounting::ObjectStack* live_stack = heap_->GetLiveStack();
1187 if (kEnableFromSpaceAccountingCheck) {
1188 CHECK_GE(live_stack_freeze_size_, live_stack->Size());
1189 }
1190 heap_->MarkAllocStackAsLive(live_stack);
1191 live_stack->Reset();
1192 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001193 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001194 TimingLogger::ScopedTiming split("Sweep", GetTimings());
1195 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
1196 if (space->IsContinuousMemMapAllocSpace()) {
1197 space::ContinuousMemMapAllocSpace* alloc_space = space->AsContinuousMemMapAllocSpace();
1198 if (space == region_space_ || immune_region_.ContainsSpace(space)) {
1199 continue;
1200 }
1201 TimingLogger::ScopedTiming split2(
1202 alloc_space->IsZygoteSpace() ? "SweepZygoteSpace" : "SweepAllocSpace", GetTimings());
1203 RecordFree(alloc_space->Sweep(swap_bitmaps));
1204 }
1205 }
1206 SweepLargeObjects(swap_bitmaps);
1207}
1208
1209void ConcurrentCopying::SweepLargeObjects(bool swap_bitmaps) {
1210 TimingLogger::ScopedTiming split("SweepLargeObjects", GetTimings());
1211 RecordFreeLOS(heap_->GetLargeObjectsSpace()->Sweep(swap_bitmaps));
1212}
1213
1214class ConcurrentCopyingClearBlackPtrsVisitor {
1215 public:
1216 explicit ConcurrentCopyingClearBlackPtrsVisitor(ConcurrentCopying* cc)
1217 : collector_(cc) {}
Andreas Gampe65b798e2015-04-06 09:35:22 -07001218#ifndef USE_BAKER_OR_BROOKS_READ_BARRIER
1219 NO_RETURN
1220#endif
Mathieu Chartier90443472015-07-16 20:32:27 -07001221 void operator()(mirror::Object* obj) const SHARED_REQUIRES(Locks::mutator_lock_)
1222 SHARED_REQUIRES(Locks::heap_bitmap_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001223 DCHECK(obj != nullptr);
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08001224 DCHECK(collector_->heap_->GetMarkBitmap()->Test(obj)) << obj;
1225 DCHECK_EQ(obj->GetReadBarrierPointer(), ReadBarrier::BlackPtr()) << obj;
Hiroshi Yamauchi60f63f52015-04-23 16:12:40 -07001226 obj->AtomicSetReadBarrierPointer(ReadBarrier::BlackPtr(), ReadBarrier::WhitePtr());
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08001227 DCHECK_EQ(obj->GetReadBarrierPointer(), ReadBarrier::WhitePtr()) << obj;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001228 }
1229
1230 private:
1231 ConcurrentCopying* const collector_;
1232};
1233
1234// Clear the black ptrs in non-moving objects back to white.
1235void ConcurrentCopying::ClearBlackPtrs() {
1236 CHECK(kUseBakerReadBarrier);
1237 TimingLogger::ScopedTiming split("ClearBlackPtrs", GetTimings());
1238 ConcurrentCopyingClearBlackPtrsVisitor visitor(this);
1239 for (auto& space : heap_->GetContinuousSpaces()) {
1240 if (space == region_space_) {
1241 continue;
1242 }
1243 accounting::ContinuousSpaceBitmap* mark_bitmap = space->GetMarkBitmap();
1244 if (kVerboseMode) {
1245 LOG(INFO) << "ClearBlackPtrs: " << *space << " bitmap: " << *mark_bitmap;
1246 }
1247 mark_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()),
1248 reinterpret_cast<uintptr_t>(space->Limit()),
1249 visitor);
1250 }
1251 space::LargeObjectSpace* large_object_space = heap_->GetLargeObjectsSpace();
1252 large_object_space->GetMarkBitmap()->VisitMarkedRange(
1253 reinterpret_cast<uintptr_t>(large_object_space->Begin()),
1254 reinterpret_cast<uintptr_t>(large_object_space->End()),
1255 visitor);
1256 // Objects on the allocation stack?
1257 if (ReadBarrier::kEnableReadBarrierInvariantChecks || kIsDebugBuild) {
1258 size_t count = GetAllocationStack()->Size();
Mathieu Chartiercb535da2015-01-23 13:50:03 -08001259 auto* it = GetAllocationStack()->Begin();
1260 auto* end = GetAllocationStack()->End();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001261 for (size_t i = 0; i < count; ++i, ++it) {
Mathieu Chartiercb535da2015-01-23 13:50:03 -08001262 CHECK_LT(it, end);
1263 mirror::Object* obj = it->AsMirrorPtr();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001264 if (obj != nullptr) {
1265 // Must have been cleared above.
Mathieu Chartiercb535da2015-01-23 13:50:03 -08001266 CHECK_EQ(obj->GetReadBarrierPointer(), ReadBarrier::WhitePtr()) << obj;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001267 }
1268 }
1269 }
1270}
1271
1272void ConcurrentCopying::ReclaimPhase() {
1273 TimingLogger::ScopedTiming split("ReclaimPhase", GetTimings());
1274 if (kVerboseMode) {
1275 LOG(INFO) << "GC ReclaimPhase";
1276 }
1277 Thread* self = Thread::Current();
1278
1279 {
1280 // Double-check that the mark stack is empty.
1281 // Note: need to set this after VerifyNoFromSpaceRef().
1282 is_asserting_to_space_invariant_ = false;
1283 QuasiAtomic::ThreadFenceForConstructor();
1284 if (kVerboseMode) {
1285 LOG(INFO) << "Issue an empty check point. ";
1286 }
1287 IssueEmptyCheckpoint();
1288 // Disable the check.
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001289 is_mark_stack_push_disallowed_.StoreSequentiallyConsistent(0);
1290 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001291 }
1292
1293 {
1294 // Record freed objects.
1295 TimingLogger::ScopedTiming split2("RecordFree", GetTimings());
1296 // Don't include thread-locals that are in the to-space.
1297 uint64_t from_bytes = region_space_->GetBytesAllocatedInFromSpace();
1298 uint64_t from_objects = region_space_->GetObjectsAllocatedInFromSpace();
1299 uint64_t unevac_from_bytes = region_space_->GetBytesAllocatedInUnevacFromSpace();
1300 uint64_t unevac_from_objects = region_space_->GetObjectsAllocatedInUnevacFromSpace();
1301 uint64_t to_bytes = bytes_moved_.LoadSequentiallyConsistent();
1302 uint64_t to_objects = objects_moved_.LoadSequentiallyConsistent();
1303 if (kEnableFromSpaceAccountingCheck) {
1304 CHECK_EQ(from_space_num_objects_at_first_pause_, from_objects + unevac_from_objects);
1305 CHECK_EQ(from_space_num_bytes_at_first_pause_, from_bytes + unevac_from_bytes);
1306 }
1307 CHECK_LE(to_objects, from_objects);
1308 CHECK_LE(to_bytes, from_bytes);
1309 int64_t freed_bytes = from_bytes - to_bytes;
1310 int64_t freed_objects = from_objects - to_objects;
1311 if (kVerboseMode) {
1312 LOG(INFO) << "RecordFree:"
1313 << " from_bytes=" << from_bytes << " from_objects=" << from_objects
1314 << " unevac_from_bytes=" << unevac_from_bytes << " unevac_from_objects=" << unevac_from_objects
1315 << " to_bytes=" << to_bytes << " to_objects=" << to_objects
1316 << " freed_bytes=" << freed_bytes << " freed_objects=" << freed_objects
1317 << " from_space size=" << region_space_->FromSpaceSize()
1318 << " unevac_from_space size=" << region_space_->UnevacFromSpaceSize()
1319 << " to_space size=" << region_space_->ToSpaceSize();
1320 LOG(INFO) << "(before) num_bytes_allocated=" << heap_->num_bytes_allocated_.LoadSequentiallyConsistent();
1321 }
1322 RecordFree(ObjectBytePair(freed_objects, freed_bytes));
1323 if (kVerboseMode) {
1324 LOG(INFO) << "(after) num_bytes_allocated=" << heap_->num_bytes_allocated_.LoadSequentiallyConsistent();
1325 }
1326 }
1327
1328 {
1329 TimingLogger::ScopedTiming split3("ComputeUnevacFromSpaceLiveRatio", GetTimings());
1330 ComputeUnevacFromSpaceLiveRatio();
1331 }
1332
1333 {
1334 TimingLogger::ScopedTiming split4("ClearFromSpace", GetTimings());
1335 region_space_->ClearFromSpace();
1336 }
1337
1338 {
1339 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1340 if (kUseBakerReadBarrier) {
1341 ClearBlackPtrs();
1342 }
1343 Sweep(false);
1344 SwapBitmaps();
1345 heap_->UnBindBitmaps();
1346
1347 // Remove bitmaps for the immune spaces.
1348 while (!cc_bitmaps_.empty()) {
1349 accounting::ContinuousSpaceBitmap* cc_bitmap = cc_bitmaps_.back();
1350 cc_heap_bitmap_->RemoveContinuousSpaceBitmap(cc_bitmap);
1351 delete cc_bitmap;
1352 cc_bitmaps_.pop_back();
1353 }
1354 region_space_bitmap_ = nullptr;
1355 }
1356
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001357 CheckEmptyMarkStack();
1358
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001359 if (kVerboseMode) {
1360 LOG(INFO) << "GC end of ReclaimPhase";
1361 }
1362}
1363
1364class ConcurrentCopyingComputeUnevacFromSpaceLiveRatioVisitor {
1365 public:
1366 explicit ConcurrentCopyingComputeUnevacFromSpaceLiveRatioVisitor(ConcurrentCopying* cc)
1367 : collector_(cc) {}
Mathieu Chartier90443472015-07-16 20:32:27 -07001368 void operator()(mirror::Object* ref) const SHARED_REQUIRES(Locks::mutator_lock_)
1369 SHARED_REQUIRES(Locks::heap_bitmap_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001370 DCHECK(ref != nullptr);
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08001371 DCHECK(collector_->region_space_bitmap_->Test(ref)) << ref;
1372 DCHECK(collector_->region_space_->IsInUnevacFromSpace(ref)) << ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001373 if (kUseBakerReadBarrier) {
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08001374 DCHECK_EQ(ref->GetReadBarrierPointer(), ReadBarrier::BlackPtr()) << ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001375 // Clear the black ptr.
Hiroshi Yamauchi60f63f52015-04-23 16:12:40 -07001376 ref->AtomicSetReadBarrierPointer(ReadBarrier::BlackPtr(), ReadBarrier::WhitePtr());
1377 DCHECK_EQ(ref->GetReadBarrierPointer(), ReadBarrier::WhitePtr()) << ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001378 }
1379 size_t obj_size = ref->SizeOf();
1380 size_t alloc_size = RoundUp(obj_size, space::RegionSpace::kAlignment);
1381 collector_->region_space_->AddLiveBytes(ref, alloc_size);
1382 }
1383
1384 private:
Mathieu Chartier97509952015-07-13 14:35:43 -07001385 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001386};
1387
1388// Compute how much live objects are left in regions.
1389void ConcurrentCopying::ComputeUnevacFromSpaceLiveRatio() {
1390 region_space_->AssertAllRegionLiveBytesZeroOrCleared();
1391 ConcurrentCopyingComputeUnevacFromSpaceLiveRatioVisitor visitor(this);
1392 region_space_bitmap_->VisitMarkedRange(reinterpret_cast<uintptr_t>(region_space_->Begin()),
1393 reinterpret_cast<uintptr_t>(region_space_->Limit()),
1394 visitor);
1395}
1396
1397// Assert the to-space invariant.
1398void ConcurrentCopying::AssertToSpaceInvariant(mirror::Object* obj, MemberOffset offset,
1399 mirror::Object* ref) {
1400 CHECK(heap_->collector_type_ == kCollectorTypeCC) << static_cast<size_t>(heap_->collector_type_);
1401 if (is_asserting_to_space_invariant_) {
1402 if (region_space_->IsInToSpace(ref)) {
1403 // OK.
1404 return;
1405 } else if (region_space_->IsInUnevacFromSpace(ref)) {
1406 CHECK(region_space_bitmap_->Test(ref)) << ref;
1407 } else if (region_space_->IsInFromSpace(ref)) {
1408 // Not OK. Do extra logging.
1409 if (obj != nullptr) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001410 LogFromSpaceRefHolder(obj, offset);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001411 }
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001412 ref->GetLockWord(false).Dump(LOG(INTERNAL_FATAL));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001413 CHECK(false) << "Found from-space ref " << ref << " " << PrettyTypeOf(ref);
1414 } else {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001415 AssertToSpaceInvariantInNonMovingSpace(obj, ref);
1416 }
1417 }
1418}
1419
1420class RootPrinter {
1421 public:
1422 RootPrinter() { }
1423
1424 template <class MirrorType>
1425 ALWAYS_INLINE void VisitRootIfNonNull(mirror::CompressedReference<MirrorType>* root)
Mathieu Chartier90443472015-07-16 20:32:27 -07001426 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001427 if (!root->IsNull()) {
1428 VisitRoot(root);
1429 }
1430 }
1431
1432 template <class MirrorType>
1433 void VisitRoot(mirror::Object** root)
Mathieu Chartier90443472015-07-16 20:32:27 -07001434 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001435 LOG(INTERNAL_FATAL) << "root=" << root << " ref=" << *root;
1436 }
1437
1438 template <class MirrorType>
1439 void VisitRoot(mirror::CompressedReference<MirrorType>* root)
Mathieu Chartier90443472015-07-16 20:32:27 -07001440 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001441 LOG(INTERNAL_FATAL) << "root=" << root << " ref=" << root->AsMirrorPtr();
1442 }
1443};
1444
1445void ConcurrentCopying::AssertToSpaceInvariant(GcRootSource* gc_root_source,
1446 mirror::Object* ref) {
1447 CHECK(heap_->collector_type_ == kCollectorTypeCC) << static_cast<size_t>(heap_->collector_type_);
1448 if (is_asserting_to_space_invariant_) {
1449 if (region_space_->IsInToSpace(ref)) {
1450 // OK.
1451 return;
1452 } else if (region_space_->IsInUnevacFromSpace(ref)) {
1453 CHECK(region_space_bitmap_->Test(ref)) << ref;
1454 } else if (region_space_->IsInFromSpace(ref)) {
1455 // Not OK. Do extra logging.
1456 if (gc_root_source == nullptr) {
1457 // No info.
1458 } else if (gc_root_source->HasArtField()) {
1459 ArtField* field = gc_root_source->GetArtField();
1460 LOG(INTERNAL_FATAL) << "gc root in field " << field << " " << PrettyField(field);
1461 RootPrinter root_printer;
1462 field->VisitRoots(root_printer);
1463 } else if (gc_root_source->HasArtMethod()) {
1464 ArtMethod* method = gc_root_source->GetArtMethod();
1465 LOG(INTERNAL_FATAL) << "gc root in method " << method << " " << PrettyMethod(method);
1466 RootPrinter root_printer;
1467 method->VisitRoots(root_printer);
1468 }
1469 ref->GetLockWord(false).Dump(LOG(INTERNAL_FATAL));
1470 region_space_->DumpNonFreeRegions(LOG(INTERNAL_FATAL));
1471 PrintFileToLog("/proc/self/maps", LogSeverity::INTERNAL_FATAL);
1472 MemMap::DumpMaps(LOG(INTERNAL_FATAL), true);
1473 CHECK(false) << "Found from-space ref " << ref << " " << PrettyTypeOf(ref);
1474 } else {
1475 AssertToSpaceInvariantInNonMovingSpace(nullptr, ref);
1476 }
1477 }
1478}
1479
1480void ConcurrentCopying::LogFromSpaceRefHolder(mirror::Object* obj, MemberOffset offset) {
1481 if (kUseBakerReadBarrier) {
1482 LOG(INFO) << "holder=" << obj << " " << PrettyTypeOf(obj)
1483 << " holder rb_ptr=" << obj->GetReadBarrierPointer();
1484 } else {
1485 LOG(INFO) << "holder=" << obj << " " << PrettyTypeOf(obj);
1486 }
1487 if (region_space_->IsInFromSpace(obj)) {
1488 LOG(INFO) << "holder is in the from-space.";
1489 } else if (region_space_->IsInToSpace(obj)) {
1490 LOG(INFO) << "holder is in the to-space.";
1491 } else if (region_space_->IsInUnevacFromSpace(obj)) {
1492 LOG(INFO) << "holder is in the unevac from-space.";
1493 if (region_space_bitmap_->Test(obj)) {
1494 LOG(INFO) << "holder is marked in the region space bitmap.";
1495 } else {
1496 LOG(INFO) << "holder is not marked in the region space bitmap.";
1497 }
1498 } else {
1499 // In a non-moving space.
1500 if (immune_region_.ContainsObject(obj)) {
1501 LOG(INFO) << "holder is in the image or the zygote space.";
1502 accounting::ContinuousSpaceBitmap* cc_bitmap =
1503 cc_heap_bitmap_->GetContinuousSpaceBitmap(obj);
1504 CHECK(cc_bitmap != nullptr)
1505 << "An immune space object must have a bitmap.";
1506 if (cc_bitmap->Test(obj)) {
1507 LOG(INFO) << "holder is marked in the bit map.";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001508 } else {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001509 LOG(INFO) << "holder is NOT marked in the bit map.";
1510 }
1511 } else {
1512 LOG(INFO) << "holder is in a non-moving (or main) space.";
1513 accounting::ContinuousSpaceBitmap* mark_bitmap =
1514 heap_mark_bitmap_->GetContinuousSpaceBitmap(obj);
1515 accounting::LargeObjectBitmap* los_bitmap =
1516 heap_mark_bitmap_->GetLargeObjectBitmap(obj);
1517 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
1518 bool is_los = mark_bitmap == nullptr;
1519 if (!is_los && mark_bitmap->Test(obj)) {
1520 LOG(INFO) << "holder is marked in the mark bit map.";
1521 } else if (is_los && los_bitmap->Test(obj)) {
1522 LOG(INFO) << "holder is marked in the los bit map.";
1523 } else {
1524 // If ref is on the allocation stack, then it is considered
1525 // mark/alive (but not necessarily on the live stack.)
1526 if (IsOnAllocStack(obj)) {
1527 LOG(INFO) << "holder is on the alloc stack.";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001528 } else {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001529 LOG(INFO) << "holder is not marked or on the alloc stack.";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001530 }
1531 }
1532 }
1533 }
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001534 LOG(INFO) << "offset=" << offset.SizeValue();
1535}
1536
1537void ConcurrentCopying::AssertToSpaceInvariantInNonMovingSpace(mirror::Object* obj,
1538 mirror::Object* ref) {
1539 // In a non-moving spaces. Check that the ref is marked.
1540 if (immune_region_.ContainsObject(ref)) {
1541 accounting::ContinuousSpaceBitmap* cc_bitmap =
1542 cc_heap_bitmap_->GetContinuousSpaceBitmap(ref);
1543 CHECK(cc_bitmap != nullptr)
1544 << "An immune space ref must have a bitmap. " << ref;
1545 if (kUseBakerReadBarrier) {
1546 CHECK(cc_bitmap->Test(ref))
1547 << "Unmarked immune space ref. obj=" << obj << " rb_ptr="
1548 << obj->GetReadBarrierPointer() << " ref=" << ref;
1549 } else {
1550 CHECK(cc_bitmap->Test(ref))
1551 << "Unmarked immune space ref. obj=" << obj << " ref=" << ref;
1552 }
1553 } else {
1554 accounting::ContinuousSpaceBitmap* mark_bitmap =
1555 heap_mark_bitmap_->GetContinuousSpaceBitmap(ref);
1556 accounting::LargeObjectBitmap* los_bitmap =
1557 heap_mark_bitmap_->GetLargeObjectBitmap(ref);
1558 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
1559 bool is_los = mark_bitmap == nullptr;
1560 if ((!is_los && mark_bitmap->Test(ref)) ||
1561 (is_los && los_bitmap->Test(ref))) {
1562 // OK.
1563 } else {
1564 // If ref is on the allocation stack, then it may not be
1565 // marked live, but considered marked/alive (but not
1566 // necessarily on the live stack).
1567 CHECK(IsOnAllocStack(ref)) << "Unmarked ref that's not on the allocation stack. "
1568 << "obj=" << obj << " ref=" << ref;
1569 }
1570 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001571}
1572
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001573// Used to scan ref fields of an object.
1574class ConcurrentCopyingRefFieldsVisitor {
1575 public:
1576 explicit ConcurrentCopyingRefFieldsVisitor(ConcurrentCopying* collector)
1577 : collector_(collector) {}
1578
1579 void operator()(mirror::Object* obj, MemberOffset offset, bool /* is_static */)
Mathieu Chartier90443472015-07-16 20:32:27 -07001580 const ALWAYS_INLINE SHARED_REQUIRES(Locks::mutator_lock_)
1581 SHARED_REQUIRES(Locks::heap_bitmap_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001582 collector_->Process(obj, offset);
1583 }
1584
1585 void operator()(mirror::Class* klass, mirror::Reference* ref) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001586 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001587 CHECK(klass->IsTypeOfReferenceClass());
1588 collector_->DelayReferenceReferent(klass, ref);
1589 }
1590
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001591 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
1592 SHARED_REQUIRES(Locks::mutator_lock_) {
1593 if (!root->IsNull()) {
1594 VisitRoot(root);
1595 }
1596 }
1597
1598 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
1599 SHARED_REQUIRES(Locks::mutator_lock_) {
1600 collector_->MarkRoot(root);
1601 }
1602
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001603 private:
1604 ConcurrentCopying* const collector_;
1605};
1606
1607// Scan ref fields of an object.
1608void ConcurrentCopying::Scan(mirror::Object* to_ref) {
1609 DCHECK(!region_space_->IsInFromSpace(to_ref));
1610 ConcurrentCopyingRefFieldsVisitor visitor(this);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07001611 to_ref->VisitReferences(visitor, visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001612}
1613
1614// Process a field.
1615inline void ConcurrentCopying::Process(mirror::Object* obj, MemberOffset offset) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001616 mirror::Object* ref = obj->GetFieldObject<
1617 mirror::Object, kVerifyNone, kWithoutReadBarrier, false>(offset);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001618 if (ref == nullptr || region_space_->IsInToSpace(ref)) {
1619 return;
1620 }
1621 mirror::Object* to_ref = Mark(ref);
1622 if (to_ref == ref) {
1623 return;
1624 }
1625 // This may fail if the mutator writes to the field at the same time. But it's ok.
1626 mirror::Object* expected_ref = ref;
1627 mirror::Object* new_ref = to_ref;
1628 do {
1629 if (expected_ref !=
1630 obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier, false>(offset)) {
1631 // It was updated by the mutator.
1632 break;
1633 }
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001634 } while (!obj->CasFieldWeakSequentiallyConsistentObjectWithoutWriteBarrier<
1635 false, false, kVerifyNone>(offset, expected_ref, new_ref));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001636}
1637
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001638// Process some roots.
1639void ConcurrentCopying::VisitRoots(
1640 mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED) {
1641 for (size_t i = 0; i < count; ++i) {
1642 mirror::Object** root = roots[i];
1643 mirror::Object* ref = *root;
1644 if (ref == nullptr || region_space_->IsInToSpace(ref)) {
Mathieu Chartier4809d0a2015-04-07 10:39:04 -07001645 continue;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001646 }
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001647 mirror::Object* to_ref = Mark(ref);
1648 if (to_ref == ref) {
Mathieu Chartier4809d0a2015-04-07 10:39:04 -07001649 continue;
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001650 }
1651 Atomic<mirror::Object*>* addr = reinterpret_cast<Atomic<mirror::Object*>*>(root);
1652 mirror::Object* expected_ref = ref;
1653 mirror::Object* new_ref = to_ref;
1654 do {
1655 if (expected_ref != addr->LoadRelaxed()) {
1656 // It was updated by the mutator.
1657 break;
1658 }
1659 } while (!addr->CompareExchangeWeakSequentiallyConsistent(expected_ref, new_ref));
1660 }
1661}
1662
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001663void ConcurrentCopying::MarkRoot(mirror::CompressedReference<mirror::Object>* root) {
1664 DCHECK(!root->IsNull());
1665 mirror::Object* const ref = root->AsMirrorPtr();
1666 if (region_space_->IsInToSpace(ref)) {
1667 return;
1668 }
1669 mirror::Object* to_ref = Mark(ref);
1670 if (to_ref != ref) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001671 auto* addr = reinterpret_cast<Atomic<mirror::CompressedReference<mirror::Object>>*>(root);
1672 auto expected_ref = mirror::CompressedReference<mirror::Object>::FromMirrorPtr(ref);
1673 auto new_ref = mirror::CompressedReference<mirror::Object>::FromMirrorPtr(to_ref);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001674 // If the cas fails, then it was updated by the mutator.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001675 do {
1676 if (ref != addr->LoadRelaxed().AsMirrorPtr()) {
1677 // It was updated by the mutator.
1678 break;
1679 }
1680 } while (!addr->CompareExchangeWeakSequentiallyConsistent(expected_ref, new_ref));
1681 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001682}
1683
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001684void ConcurrentCopying::VisitRoots(
1685 mirror::CompressedReference<mirror::Object>** roots, size_t count,
1686 const RootInfo& info ATTRIBUTE_UNUSED) {
1687 for (size_t i = 0; i < count; ++i) {
1688 mirror::CompressedReference<mirror::Object>* const root = roots[i];
1689 if (!root->IsNull()) {
1690 MarkRoot(root);
1691 }
1692 }
1693}
1694
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001695// Fill the given memory block with a dummy object. Used to fill in a
1696// copy of objects that was lost in race.
1697void ConcurrentCopying::FillWithDummyObject(mirror::Object* dummy_obj, size_t byte_size) {
Roland Levillain14d90572015-07-16 10:52:26 +01001698 CHECK_ALIGNED(byte_size, kObjectAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001699 memset(dummy_obj, 0, byte_size);
1700 mirror::Class* int_array_class = mirror::IntArray::GetArrayClass();
1701 CHECK(int_array_class != nullptr);
1702 AssertToSpaceInvariant(nullptr, MemberOffset(0), int_array_class);
1703 size_t component_size = int_array_class->GetComponentSize();
1704 CHECK_EQ(component_size, sizeof(int32_t));
1705 size_t data_offset = mirror::Array::DataOffset(component_size).SizeValue();
1706 if (data_offset > byte_size) {
1707 // An int array is too big. Use java.lang.Object.
1708 mirror::Class* java_lang_Object = WellKnownClasses::ToClass(WellKnownClasses::java_lang_Object);
1709 AssertToSpaceInvariant(nullptr, MemberOffset(0), java_lang_Object);
1710 CHECK_EQ(byte_size, java_lang_Object->GetObjectSize());
1711 dummy_obj->SetClass(java_lang_Object);
1712 CHECK_EQ(byte_size, dummy_obj->SizeOf());
1713 } else {
1714 // Use an int array.
1715 dummy_obj->SetClass(int_array_class);
1716 CHECK(dummy_obj->IsArrayInstance());
1717 int32_t length = (byte_size - data_offset) / component_size;
1718 dummy_obj->AsArray()->SetLength(length);
1719 CHECK_EQ(dummy_obj->AsArray()->GetLength(), length)
1720 << "byte_size=" << byte_size << " length=" << length
1721 << " component_size=" << component_size << " data_offset=" << data_offset;
1722 CHECK_EQ(byte_size, dummy_obj->SizeOf())
1723 << "byte_size=" << byte_size << " length=" << length
1724 << " component_size=" << component_size << " data_offset=" << data_offset;
1725 }
1726}
1727
1728// Reuse the memory blocks that were copy of objects that were lost in race.
1729mirror::Object* ConcurrentCopying::AllocateInSkippedBlock(size_t alloc_size) {
1730 // Try to reuse the blocks that were unused due to CAS failures.
Roland Levillain14d90572015-07-16 10:52:26 +01001731 CHECK_ALIGNED(alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001732 Thread* self = Thread::Current();
1733 size_t min_object_size = RoundUp(sizeof(mirror::Object), space::RegionSpace::kAlignment);
1734 MutexLock mu(self, skipped_blocks_lock_);
1735 auto it = skipped_blocks_map_.lower_bound(alloc_size);
1736 if (it == skipped_blocks_map_.end()) {
1737 // Not found.
1738 return nullptr;
1739 }
1740 {
1741 size_t byte_size = it->first;
1742 CHECK_GE(byte_size, alloc_size);
1743 if (byte_size > alloc_size && byte_size - alloc_size < min_object_size) {
1744 // If remainder would be too small for a dummy object, retry with a larger request size.
1745 it = skipped_blocks_map_.lower_bound(alloc_size + min_object_size);
1746 if (it == skipped_blocks_map_.end()) {
1747 // Not found.
1748 return nullptr;
1749 }
Roland Levillain14d90572015-07-16 10:52:26 +01001750 CHECK_ALIGNED(it->first - alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001751 CHECK_GE(it->first - alloc_size, min_object_size)
1752 << "byte_size=" << byte_size << " it->first=" << it->first << " alloc_size=" << alloc_size;
1753 }
1754 }
1755 // Found a block.
1756 CHECK(it != skipped_blocks_map_.end());
1757 size_t byte_size = it->first;
1758 uint8_t* addr = it->second;
1759 CHECK_GE(byte_size, alloc_size);
1760 CHECK(region_space_->IsInToSpace(reinterpret_cast<mirror::Object*>(addr)));
Roland Levillain14d90572015-07-16 10:52:26 +01001761 CHECK_ALIGNED(byte_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001762 if (kVerboseMode) {
1763 LOG(INFO) << "Reusing skipped bytes : " << reinterpret_cast<void*>(addr) << ", " << byte_size;
1764 }
1765 skipped_blocks_map_.erase(it);
1766 memset(addr, 0, byte_size);
1767 if (byte_size > alloc_size) {
1768 // Return the remainder to the map.
Roland Levillain14d90572015-07-16 10:52:26 +01001769 CHECK_ALIGNED(byte_size - alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001770 CHECK_GE(byte_size - alloc_size, min_object_size);
1771 FillWithDummyObject(reinterpret_cast<mirror::Object*>(addr + alloc_size),
1772 byte_size - alloc_size);
1773 CHECK(region_space_->IsInToSpace(reinterpret_cast<mirror::Object*>(addr + alloc_size)));
1774 skipped_blocks_map_.insert(std::make_pair(byte_size - alloc_size, addr + alloc_size));
1775 }
1776 return reinterpret_cast<mirror::Object*>(addr);
1777}
1778
1779mirror::Object* ConcurrentCopying::Copy(mirror::Object* from_ref) {
1780 DCHECK(region_space_->IsInFromSpace(from_ref));
1781 // No read barrier to avoid nested RB that might violate the to-space
1782 // invariant. Note that from_ref is a from space ref so the SizeOf()
1783 // call will access the from-space meta objects, but it's ok and necessary.
1784 size_t obj_size = from_ref->SizeOf<kDefaultVerifyFlags, kWithoutReadBarrier>();
1785 size_t region_space_alloc_size = RoundUp(obj_size, space::RegionSpace::kAlignment);
1786 size_t region_space_bytes_allocated = 0U;
1787 size_t non_moving_space_bytes_allocated = 0U;
1788 size_t bytes_allocated = 0U;
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001789 size_t dummy;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001790 mirror::Object* to_ref = region_space_->AllocNonvirtual<true>(
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001791 region_space_alloc_size, &region_space_bytes_allocated, nullptr, &dummy);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001792 bytes_allocated = region_space_bytes_allocated;
1793 if (to_ref != nullptr) {
1794 DCHECK_EQ(region_space_alloc_size, region_space_bytes_allocated);
1795 }
1796 bool fall_back_to_non_moving = false;
1797 if (UNLIKELY(to_ref == nullptr)) {
1798 // Failed to allocate in the region space. Try the skipped blocks.
1799 to_ref = AllocateInSkippedBlock(region_space_alloc_size);
1800 if (to_ref != nullptr) {
1801 // Succeeded to allocate in a skipped block.
1802 if (heap_->use_tlab_) {
1803 // This is necessary for the tlab case as it's not accounted in the space.
1804 region_space_->RecordAlloc(to_ref);
1805 }
1806 bytes_allocated = region_space_alloc_size;
1807 } else {
1808 // Fall back to the non-moving space.
1809 fall_back_to_non_moving = true;
1810 if (kVerboseMode) {
1811 LOG(INFO) << "Out of memory in the to-space. Fall back to non-moving. skipped_bytes="
1812 << to_space_bytes_skipped_.LoadSequentiallyConsistent()
1813 << " skipped_objects=" << to_space_objects_skipped_.LoadSequentiallyConsistent();
1814 }
1815 fall_back_to_non_moving = true;
1816 to_ref = heap_->non_moving_space_->Alloc(Thread::Current(), obj_size,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001817 &non_moving_space_bytes_allocated, nullptr, &dummy);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001818 CHECK(to_ref != nullptr) << "Fall-back non-moving space allocation failed";
1819 bytes_allocated = non_moving_space_bytes_allocated;
1820 // Mark it in the mark bitmap.
1821 accounting::ContinuousSpaceBitmap* mark_bitmap =
1822 heap_mark_bitmap_->GetContinuousSpaceBitmap(to_ref);
1823 CHECK(mark_bitmap != nullptr);
1824 CHECK(!mark_bitmap->AtomicTestAndSet(to_ref));
1825 }
1826 }
1827 DCHECK(to_ref != nullptr);
1828
1829 // Attempt to install the forward pointer. This is in a loop as the
1830 // lock word atomic write can fail.
1831 while (true) {
1832 // Copy the object. TODO: copy only the lockword in the second iteration and on?
1833 memcpy(to_ref, from_ref, obj_size);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001834
1835 LockWord old_lock_word = to_ref->GetLockWord(false);
1836
1837 if (old_lock_word.GetState() == LockWord::kForwardingAddress) {
1838 // Lost the race. Another thread (either GC or mutator) stored
1839 // the forwarding pointer first. Make the lost copy (to_ref)
1840 // look like a valid but dead (dummy) object and keep it for
1841 // future reuse.
1842 FillWithDummyObject(to_ref, bytes_allocated);
1843 if (!fall_back_to_non_moving) {
1844 DCHECK(region_space_->IsInToSpace(to_ref));
1845 if (bytes_allocated > space::RegionSpace::kRegionSize) {
1846 // Free the large alloc.
1847 region_space_->FreeLarge(to_ref, bytes_allocated);
1848 } else {
1849 // Record the lost copy for later reuse.
1850 heap_->num_bytes_allocated_.FetchAndAddSequentiallyConsistent(bytes_allocated);
1851 to_space_bytes_skipped_.FetchAndAddSequentiallyConsistent(bytes_allocated);
1852 to_space_objects_skipped_.FetchAndAddSequentiallyConsistent(1);
1853 MutexLock mu(Thread::Current(), skipped_blocks_lock_);
1854 skipped_blocks_map_.insert(std::make_pair(bytes_allocated,
1855 reinterpret_cast<uint8_t*>(to_ref)));
1856 }
1857 } else {
1858 DCHECK(heap_->non_moving_space_->HasAddress(to_ref));
1859 DCHECK_EQ(bytes_allocated, non_moving_space_bytes_allocated);
1860 // Free the non-moving-space chunk.
1861 accounting::ContinuousSpaceBitmap* mark_bitmap =
1862 heap_mark_bitmap_->GetContinuousSpaceBitmap(to_ref);
1863 CHECK(mark_bitmap != nullptr);
1864 CHECK(mark_bitmap->Clear(to_ref));
1865 heap_->non_moving_space_->Free(Thread::Current(), to_ref);
1866 }
1867
1868 // Get the winner's forward ptr.
1869 mirror::Object* lost_fwd_ptr = to_ref;
1870 to_ref = reinterpret_cast<mirror::Object*>(old_lock_word.ForwardingAddress());
1871 CHECK(to_ref != nullptr);
1872 CHECK_NE(to_ref, lost_fwd_ptr);
1873 CHECK(region_space_->IsInToSpace(to_ref) || heap_->non_moving_space_->HasAddress(to_ref));
1874 CHECK_NE(to_ref->GetLockWord(false).GetState(), LockWord::kForwardingAddress);
1875 return to_ref;
1876 }
1877
Hiroshi Yamauchi60f63f52015-04-23 16:12:40 -07001878 // Set the gray ptr.
1879 if (kUseBakerReadBarrier) {
1880 to_ref->SetReadBarrierPointer(ReadBarrier::GrayPtr());
1881 }
1882
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001883 LockWord new_lock_word = LockWord::FromForwardingAddress(reinterpret_cast<size_t>(to_ref));
1884
1885 // Try to atomically write the fwd ptr.
1886 bool success = from_ref->CasLockWordWeakSequentiallyConsistent(old_lock_word, new_lock_word);
1887 if (LIKELY(success)) {
1888 // The CAS succeeded.
1889 objects_moved_.FetchAndAddSequentiallyConsistent(1);
1890 bytes_moved_.FetchAndAddSequentiallyConsistent(region_space_alloc_size);
1891 if (LIKELY(!fall_back_to_non_moving)) {
1892 DCHECK(region_space_->IsInToSpace(to_ref));
1893 } else {
1894 DCHECK(heap_->non_moving_space_->HasAddress(to_ref));
1895 DCHECK_EQ(bytes_allocated, non_moving_space_bytes_allocated);
1896 }
1897 if (kUseBakerReadBarrier) {
1898 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr());
1899 }
1900 DCHECK(GetFwdPtr(from_ref) == to_ref);
1901 CHECK_NE(to_ref->GetLockWord(false).GetState(), LockWord::kForwardingAddress);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001902 PushOntoMarkStack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001903 return to_ref;
1904 } else {
1905 // The CAS failed. It may have lost the race or may have failed
1906 // due to monitor/hashcode ops. Either way, retry.
1907 }
1908 }
1909}
1910
1911mirror::Object* ConcurrentCopying::IsMarked(mirror::Object* from_ref) {
1912 DCHECK(from_ref != nullptr);
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08001913 space::RegionSpace::RegionType rtype = region_space_->GetRegionType(from_ref);
1914 if (rtype == space::RegionSpace::RegionType::kRegionTypeToSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001915 // It's already marked.
1916 return from_ref;
1917 }
1918 mirror::Object* to_ref;
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08001919 if (rtype == space::RegionSpace::RegionType::kRegionTypeFromSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001920 to_ref = GetFwdPtr(from_ref);
1921 DCHECK(to_ref == nullptr || region_space_->IsInToSpace(to_ref) ||
1922 heap_->non_moving_space_->HasAddress(to_ref))
1923 << "from_ref=" << from_ref << " to_ref=" << to_ref;
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08001924 } else if (rtype == space::RegionSpace::RegionType::kRegionTypeUnevacFromSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001925 if (region_space_bitmap_->Test(from_ref)) {
1926 to_ref = from_ref;
1927 } else {
1928 to_ref = nullptr;
1929 }
1930 } else {
1931 // from_ref is in a non-moving space.
1932 if (immune_region_.ContainsObject(from_ref)) {
1933 accounting::ContinuousSpaceBitmap* cc_bitmap =
1934 cc_heap_bitmap_->GetContinuousSpaceBitmap(from_ref);
1935 DCHECK(cc_bitmap != nullptr)
1936 << "An immune space object must have a bitmap";
1937 if (kIsDebugBuild) {
1938 DCHECK(heap_mark_bitmap_->GetContinuousSpaceBitmap(from_ref)->Test(from_ref))
1939 << "Immune space object must be already marked";
1940 }
1941 if (cc_bitmap->Test(from_ref)) {
1942 // Already marked.
1943 to_ref = from_ref;
1944 } else {
1945 // Newly marked.
1946 to_ref = nullptr;
1947 }
1948 } else {
1949 // Non-immune non-moving space. Use the mark bitmap.
1950 accounting::ContinuousSpaceBitmap* mark_bitmap =
1951 heap_mark_bitmap_->GetContinuousSpaceBitmap(from_ref);
1952 accounting::LargeObjectBitmap* los_bitmap =
1953 heap_mark_bitmap_->GetLargeObjectBitmap(from_ref);
1954 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
1955 bool is_los = mark_bitmap == nullptr;
1956 if (!is_los && mark_bitmap->Test(from_ref)) {
1957 // Already marked.
1958 to_ref = from_ref;
1959 } else if (is_los && los_bitmap->Test(from_ref)) {
1960 // Already marked in LOS.
1961 to_ref = from_ref;
1962 } else {
1963 // Not marked.
1964 if (IsOnAllocStack(from_ref)) {
1965 // If on the allocation stack, it's considered marked.
1966 to_ref = from_ref;
1967 } else {
1968 // Not marked.
1969 to_ref = nullptr;
1970 }
1971 }
1972 }
1973 }
1974 return to_ref;
1975}
1976
1977bool ConcurrentCopying::IsOnAllocStack(mirror::Object* ref) {
1978 QuasiAtomic::ThreadFenceAcquire();
1979 accounting::ObjectStack* alloc_stack = GetAllocationStack();
Mathieu Chartiercb535da2015-01-23 13:50:03 -08001980 return alloc_stack->Contains(ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001981}
1982
1983mirror::Object* ConcurrentCopying::Mark(mirror::Object* from_ref) {
1984 if (from_ref == nullptr) {
1985 return nullptr;
1986 }
1987 DCHECK(from_ref != nullptr);
1988 DCHECK(heap_->collector_type_ == kCollectorTypeCC);
Hiroshi Yamauchi60f63f52015-04-23 16:12:40 -07001989 if (kUseBakerReadBarrier && !is_active_) {
1990 // In the lock word forward address state, the read barrier bits
1991 // in the lock word are part of the stored forwarding address and
1992 // invalid. This is usually OK as the from-space copy of objects
1993 // aren't accessed by mutators due to the to-space
1994 // invariant. However, during the dex2oat image writing relocation
1995 // and the zygote compaction, objects can be in the forward
1996 // address state (to store the forward/relocation addresses) and
1997 // they can still be accessed and the invalid read barrier bits
1998 // are consulted. If they look like gray but aren't really, the
1999 // read barriers slow path can trigger when it shouldn't. To guard
2000 // against this, return here if the CC collector isn't running.
2001 return from_ref;
2002 }
2003 DCHECK(region_space_ != nullptr) << "Read barrier slow path taken when CC isn't running?";
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08002004 space::RegionSpace::RegionType rtype = region_space_->GetRegionType(from_ref);
2005 if (rtype == space::RegionSpace::RegionType::kRegionTypeToSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002006 // It's already marked.
2007 return from_ref;
2008 }
2009 mirror::Object* to_ref;
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08002010 if (rtype == space::RegionSpace::RegionType::kRegionTypeFromSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002011 to_ref = GetFwdPtr(from_ref);
2012 if (kUseBakerReadBarrier) {
2013 DCHECK(to_ref != ReadBarrier::GrayPtr()) << "from_ref=" << from_ref << " to_ref=" << to_ref;
2014 }
2015 if (to_ref == nullptr) {
2016 // It isn't marked yet. Mark it by copying it to the to-space.
2017 to_ref = Copy(from_ref);
2018 }
2019 DCHECK(region_space_->IsInToSpace(to_ref) || heap_->non_moving_space_->HasAddress(to_ref))
2020 << "from_ref=" << from_ref << " to_ref=" << to_ref;
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08002021 } else if (rtype == space::RegionSpace::RegionType::kRegionTypeUnevacFromSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002022 // This may or may not succeed, which is ok.
2023 if (kUseBakerReadBarrier) {
2024 from_ref->AtomicSetReadBarrierPointer(ReadBarrier::WhitePtr(), ReadBarrier::GrayPtr());
2025 }
2026 if (region_space_bitmap_->AtomicTestAndSet(from_ref)) {
2027 // Already marked.
2028 to_ref = from_ref;
2029 } else {
2030 // Newly marked.
2031 to_ref = from_ref;
2032 if (kUseBakerReadBarrier) {
2033 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr());
2034 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002035 PushOntoMarkStack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002036 }
2037 } else {
2038 // from_ref is in a non-moving space.
2039 DCHECK(!region_space_->HasAddress(from_ref)) << from_ref;
2040 if (immune_region_.ContainsObject(from_ref)) {
2041 accounting::ContinuousSpaceBitmap* cc_bitmap =
2042 cc_heap_bitmap_->GetContinuousSpaceBitmap(from_ref);
2043 DCHECK(cc_bitmap != nullptr)
2044 << "An immune space object must have a bitmap";
2045 if (kIsDebugBuild) {
2046 DCHECK(heap_mark_bitmap_->GetContinuousSpaceBitmap(from_ref)->Test(from_ref))
2047 << "Immune space object must be already marked";
2048 }
2049 // This may or may not succeed, which is ok.
2050 if (kUseBakerReadBarrier) {
2051 from_ref->AtomicSetReadBarrierPointer(ReadBarrier::WhitePtr(), ReadBarrier::GrayPtr());
2052 }
2053 if (cc_bitmap->AtomicTestAndSet(from_ref)) {
2054 // Already marked.
2055 to_ref = from_ref;
2056 } else {
2057 // Newly marked.
2058 to_ref = from_ref;
2059 if (kUseBakerReadBarrier) {
2060 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr());
2061 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002062 PushOntoMarkStack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002063 }
2064 } else {
2065 // Use the mark bitmap.
2066 accounting::ContinuousSpaceBitmap* mark_bitmap =
2067 heap_mark_bitmap_->GetContinuousSpaceBitmap(from_ref);
2068 accounting::LargeObjectBitmap* los_bitmap =
2069 heap_mark_bitmap_->GetLargeObjectBitmap(from_ref);
2070 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
2071 bool is_los = mark_bitmap == nullptr;
2072 if (!is_los && mark_bitmap->Test(from_ref)) {
2073 // Already marked.
2074 to_ref = from_ref;
2075 if (kUseBakerReadBarrier) {
2076 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr() ||
2077 to_ref->GetReadBarrierPointer() == ReadBarrier::BlackPtr());
2078 }
2079 } else if (is_los && los_bitmap->Test(from_ref)) {
2080 // Already marked in LOS.
2081 to_ref = from_ref;
2082 if (kUseBakerReadBarrier) {
2083 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr() ||
2084 to_ref->GetReadBarrierPointer() == ReadBarrier::BlackPtr());
2085 }
2086 } else {
2087 // Not marked.
2088 if (IsOnAllocStack(from_ref)) {
2089 // If it's on the allocation stack, it's considered marked. Keep it white.
2090 to_ref = from_ref;
2091 // Objects on the allocation stack need not be marked.
2092 if (!is_los) {
2093 DCHECK(!mark_bitmap->Test(to_ref));
2094 } else {
2095 DCHECK(!los_bitmap->Test(to_ref));
2096 }
2097 if (kUseBakerReadBarrier) {
2098 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::WhitePtr());
2099 }
2100 } else {
2101 // Not marked or on the allocation stack. Try to mark it.
2102 // This may or may not succeed, which is ok.
2103 if (kUseBakerReadBarrier) {
2104 from_ref->AtomicSetReadBarrierPointer(ReadBarrier::WhitePtr(), ReadBarrier::GrayPtr());
2105 }
2106 if (!is_los && mark_bitmap->AtomicTestAndSet(from_ref)) {
2107 // Already marked.
2108 to_ref = from_ref;
2109 } else if (is_los && los_bitmap->AtomicTestAndSet(from_ref)) {
2110 // Already marked in LOS.
2111 to_ref = from_ref;
2112 } else {
2113 // Newly marked.
2114 to_ref = from_ref;
2115 if (kUseBakerReadBarrier) {
2116 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr());
2117 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002118 PushOntoMarkStack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002119 }
2120 }
2121 }
2122 }
2123 }
2124 return to_ref;
2125}
2126
2127void ConcurrentCopying::FinishPhase() {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002128 {
2129 MutexLock mu(Thread::Current(), mark_stack_lock_);
2130 CHECK_EQ(pooled_mark_stacks_.size(), kMarkStackPoolSize);
2131 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002132 region_space_ = nullptr;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002133 {
2134 MutexLock mu(Thread::Current(), skipped_blocks_lock_);
2135 skipped_blocks_map_.clear();
2136 }
2137 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
2138 heap_->ClearMarkedObjects();
2139}
2140
Mathieu Chartier97509952015-07-13 14:35:43 -07002141bool ConcurrentCopying::IsMarkedHeapReference(mirror::HeapReference<mirror::Object>* field) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002142 mirror::Object* from_ref = field->AsMirrorPtr();
Mathieu Chartier97509952015-07-13 14:35:43 -07002143 mirror::Object* to_ref = IsMarked(from_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002144 if (to_ref == nullptr) {
2145 return false;
2146 }
2147 if (from_ref != to_ref) {
2148 QuasiAtomic::ThreadFenceRelease();
2149 field->Assign(to_ref);
2150 QuasiAtomic::ThreadFenceSequentiallyConsistent();
2151 }
2152 return true;
2153}
2154
Mathieu Chartier97509952015-07-13 14:35:43 -07002155mirror::Object* ConcurrentCopying::MarkObject(mirror::Object* from_ref) {
2156 return Mark(from_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002157}
2158
2159void ConcurrentCopying::DelayReferenceReferent(mirror::Class* klass, mirror::Reference* reference) {
Mathieu Chartier97509952015-07-13 14:35:43 -07002160 heap_->GetReferenceProcessor()->DelayReferenceReferent(klass, reference, this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002161}
2162
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002163void ConcurrentCopying::ProcessReferences(Thread* self) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002164 TimingLogger::ScopedTiming split("ProcessReferences", GetTimings());
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002165 // 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 -08002166 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
2167 GetHeap()->GetReferenceProcessor()->ProcessReferences(
Mathieu Chartier97509952015-07-13 14:35:43 -07002168 true /*concurrent*/, GetTimings(), GetCurrentIteration()->GetClearSoftReferences(), this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002169}
2170
2171void ConcurrentCopying::RevokeAllThreadLocalBuffers() {
2172 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
2173 region_space_->RevokeAllThreadLocalBuffers();
2174}
2175
Hiroshi Yamauchid5307ec2014-03-27 21:07:51 -07002176} // namespace collector
2177} // namespace gc
2178} // namespace art