blob: f4cf3ae26009cc7054ccf834312e1381d6d3718b [file] [log] [blame]
Hiroshi Yamauchid5307ec2014-03-27 21:07:51 -07001/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "concurrent_copying.h"
18
Mathieu Chartierc7853442015-03-27 14:35:38 -070019#include "art_field-inl.h"
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070020#include "base/stl_util.h"
Mathieu Chartiera6b1ead2015-10-06 10:32:38 -070021#include "debugger.h"
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080022#include "gc/accounting/heap_bitmap-inl.h"
23#include "gc/accounting/space_bitmap-inl.h"
Mathieu Chartier3cf22532015-07-09 15:15:09 -070024#include "gc/reference_processor.h"
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080025#include "gc/space/image_space.h"
Mathieu Chartier073b16c2015-11-10 14:13:23 -080026#include "gc/space/space-inl.h"
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080027#include "intern_table.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070028#include "mirror/class-inl.h"
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080029#include "mirror/object-inl.h"
30#include "scoped_thread_state_change.h"
31#include "thread-inl.h"
32#include "thread_list.h"
33#include "well_known_classes.h"
34
Hiroshi Yamauchid5307ec2014-03-27 21:07:51 -070035namespace art {
36namespace gc {
37namespace collector {
38
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -070039static constexpr size_t kDefaultGcMarkStackSize = 2 * MB;
40
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080041ConcurrentCopying::ConcurrentCopying(Heap* heap, const std::string& name_prefix)
42 : GarbageCollector(heap,
43 name_prefix + (name_prefix.empty() ? "" : " ") +
44 "concurrent copying + mark sweep"),
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070045 region_space_(nullptr), gc_barrier_(new Barrier(0)),
46 gc_mark_stack_(accounting::ObjectStack::Create("concurrent copying gc mark stack",
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -070047 kDefaultGcMarkStackSize,
48 kDefaultGcMarkStackSize)),
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070049 mark_stack_lock_("concurrent copying mark stack lock", kMarkSweepMarkStackLock),
50 thread_running_gc_(nullptr),
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080051 is_marking_(false), is_active_(false), is_asserting_to_space_invariant_(false),
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070052 heap_mark_bitmap_(nullptr), live_stack_freeze_size_(0), mark_stack_mode_(kMarkStackModeOff),
53 weak_ref_access_enabled_(true),
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080054 skipped_blocks_lock_("concurrent copying bytes blocks lock", kMarkSweepMarkStackLock),
55 rb_table_(heap_->GetReadBarrierTable()),
56 force_evacuate_all_(false) {
57 static_assert(space::RegionSpace::kRegionSize == accounting::ReadBarrierTable::kRegionSize,
58 "The region space size and the read barrier table region size must match");
59 cc_heap_bitmap_.reset(new accounting::HeapBitmap(heap));
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070060 Thread* self = Thread::Current();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080061 {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080062 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
63 // Cache this so that we won't have to lock heap_bitmap_lock_ in
64 // Mark() which could cause a nested lock on heap_bitmap_lock_
65 // when GC causes a RB while doing GC or a lock order violation
66 // (class_linker_lock_ and heap_bitmap_lock_).
67 heap_mark_bitmap_ = heap->GetMarkBitmap();
68 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070069 {
70 MutexLock mu(self, mark_stack_lock_);
71 for (size_t i = 0; i < kMarkStackPoolSize; ++i) {
72 accounting::AtomicStack<mirror::Object>* mark_stack =
73 accounting::AtomicStack<mirror::Object>::Create(
74 "thread local mark stack", kMarkStackSize, kMarkStackSize);
75 pooled_mark_stacks_.push_back(mark_stack);
76 }
77 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080078}
79
Mathieu Chartierb19ccb12015-07-15 10:24:16 -070080void ConcurrentCopying::MarkHeapReference(mirror::HeapReference<mirror::Object>* from_ref) {
81 // Used for preserving soft references, should be OK to not have a CAS here since there should be
82 // no other threads which can trigger read barriers on the same referent during reference
83 // processing.
84 from_ref->Assign(Mark(from_ref->AsMirrorPtr()));
Mathieu Chartier81187812015-07-15 14:24:07 -070085 DCHECK(!from_ref->IsNull());
Mathieu Chartier97509952015-07-13 14:35:43 -070086}
87
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080088ConcurrentCopying::~ConcurrentCopying() {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070089 STLDeleteElements(&pooled_mark_stacks_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080090}
91
92void ConcurrentCopying::RunPhases() {
93 CHECK(kUseBakerReadBarrier || kUseTableLookupReadBarrier);
94 CHECK(!is_active_);
95 is_active_ = true;
96 Thread* self = Thread::Current();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070097 thread_running_gc_ = self;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080098 Locks::mutator_lock_->AssertNotHeld(self);
99 {
100 ReaderMutexLock mu(self, *Locks::mutator_lock_);
101 InitializePhase();
102 }
103 FlipThreadRoots();
104 {
105 ReaderMutexLock mu(self, *Locks::mutator_lock_);
106 MarkingPhase();
107 }
108 // Verify no from space refs. This causes a pause.
109 if (kEnableNoFromSpaceRefsVerification || kIsDebugBuild) {
110 TimingLogger::ScopedTiming split("(Paused)VerifyNoFromSpaceReferences", GetTimings());
111 ScopedPause pause(this);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700112 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800113 if (kVerboseMode) {
114 LOG(INFO) << "Verifying no from-space refs";
115 }
116 VerifyNoFromSpaceReferences();
Mathieu Chartier720e71a2015-04-06 17:10:58 -0700117 if (kVerboseMode) {
118 LOG(INFO) << "Done verifying no from-space refs";
119 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700120 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800121 }
122 {
123 ReaderMutexLock mu(self, *Locks::mutator_lock_);
124 ReclaimPhase();
125 }
126 FinishPhase();
127 CHECK(is_active_);
128 is_active_ = false;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700129 thread_running_gc_ = nullptr;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800130}
131
132void ConcurrentCopying::BindBitmaps() {
133 Thread* self = Thread::Current();
134 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
135 // Mark all of the spaces we never collect as immune.
136 for (const auto& space : heap_->GetContinuousSpaces()) {
137 if (space->GetGcRetentionPolicy() == space::kGcRetentionPolicyNeverCollect
138 || space->GetGcRetentionPolicy() == space::kGcRetentionPolicyFullCollect) {
139 CHECK(space->IsZygoteSpace() || space->IsImageSpace());
140 CHECK(immune_region_.AddContinuousSpace(space)) << "Failed to add space " << *space;
141 const char* bitmap_name = space->IsImageSpace() ? "cc image space bitmap" :
142 "cc zygote space bitmap";
143 // TODO: try avoiding using bitmaps for image/zygote to save space.
144 accounting::ContinuousSpaceBitmap* bitmap =
145 accounting::ContinuousSpaceBitmap::Create(bitmap_name, space->Begin(), space->Capacity());
146 cc_heap_bitmap_->AddContinuousSpaceBitmap(bitmap);
147 cc_bitmaps_.push_back(bitmap);
148 } else if (space == region_space_) {
149 accounting::ContinuousSpaceBitmap* bitmap =
150 accounting::ContinuousSpaceBitmap::Create("cc region space bitmap",
151 space->Begin(), space->Capacity());
152 cc_heap_bitmap_->AddContinuousSpaceBitmap(bitmap);
153 cc_bitmaps_.push_back(bitmap);
154 region_space_bitmap_ = bitmap;
155 }
156 }
157}
158
159void ConcurrentCopying::InitializePhase() {
160 TimingLogger::ScopedTiming split("InitializePhase", GetTimings());
161 if (kVerboseMode) {
162 LOG(INFO) << "GC InitializePhase";
163 LOG(INFO) << "Region-space : " << reinterpret_cast<void*>(region_space_->Begin()) << "-"
164 << reinterpret_cast<void*>(region_space_->Limit());
165 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700166 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800167 immune_region_.Reset();
168 bytes_moved_.StoreRelaxed(0);
169 objects_moved_.StoreRelaxed(0);
170 if (GetCurrentIteration()->GetGcCause() == kGcCauseExplicit ||
171 GetCurrentIteration()->GetGcCause() == kGcCauseForNativeAlloc ||
172 GetCurrentIteration()->GetClearSoftReferences()) {
173 force_evacuate_all_ = true;
174 } else {
175 force_evacuate_all_ = false;
176 }
177 BindBitmaps();
178 if (kVerboseMode) {
179 LOG(INFO) << "force_evacuate_all=" << force_evacuate_all_;
180 LOG(INFO) << "Immune region: " << immune_region_.Begin() << "-" << immune_region_.End();
181 LOG(INFO) << "GC end of InitializePhase";
182 }
183}
184
185// Used to switch the thread roots of a thread from from-space refs to to-space refs.
186class ThreadFlipVisitor : public Closure {
187 public:
Roland Levillain3887c462015-08-12 18:15:42 +0100188 ThreadFlipVisitor(ConcurrentCopying* concurrent_copying, bool use_tlab)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800189 : concurrent_copying_(concurrent_copying), use_tlab_(use_tlab) {
190 }
191
Mathieu Chartier90443472015-07-16 20:32:27 -0700192 virtual void Run(Thread* thread) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800193 // Note: self is not necessarily equal to thread since thread may be suspended.
194 Thread* self = Thread::Current();
195 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
196 << thread->GetState() << " thread " << thread << " self " << self;
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700197 thread->SetIsGcMarking(true);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800198 if (use_tlab_ && thread->HasTlab()) {
199 if (ConcurrentCopying::kEnableFromSpaceAccountingCheck) {
200 // This must come before the revoke.
201 size_t thread_local_objects = thread->GetThreadLocalObjectsAllocated();
202 concurrent_copying_->region_space_->RevokeThreadLocalBuffers(thread);
203 reinterpret_cast<Atomic<size_t>*>(&concurrent_copying_->from_space_num_objects_at_first_pause_)->
204 FetchAndAddSequentiallyConsistent(thread_local_objects);
205 } else {
206 concurrent_copying_->region_space_->RevokeThreadLocalBuffers(thread);
207 }
208 }
209 if (kUseThreadLocalAllocationStack) {
210 thread->RevokeThreadLocalAllocationStack();
211 }
212 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700213 thread->VisitRoots(concurrent_copying_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800214 concurrent_copying_->GetBarrier().Pass(self);
215 }
216
217 private:
218 ConcurrentCopying* const concurrent_copying_;
219 const bool use_tlab_;
220};
221
222// Called back from Runtime::FlipThreadRoots() during a pause.
223class FlipCallback : public Closure {
224 public:
225 explicit FlipCallback(ConcurrentCopying* concurrent_copying)
226 : concurrent_copying_(concurrent_copying) {
227 }
228
Mathieu Chartier90443472015-07-16 20:32:27 -0700229 virtual void Run(Thread* thread) OVERRIDE REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800230 ConcurrentCopying* cc = concurrent_copying_;
231 TimingLogger::ScopedTiming split("(Paused)FlipCallback", cc->GetTimings());
232 // Note: self is not necessarily equal to thread since thread may be suspended.
233 Thread* self = Thread::Current();
234 CHECK(thread == self);
235 Locks::mutator_lock_->AssertExclusiveHeld(self);
236 cc->region_space_->SetFromSpace(cc->rb_table_, cc->force_evacuate_all_);
Mathieu Chartiera4f6af92015-08-11 17:35:25 -0700237 cc->SwapStacks();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800238 if (ConcurrentCopying::kEnableFromSpaceAccountingCheck) {
239 cc->RecordLiveStackFreezeSize(self);
240 cc->from_space_num_objects_at_first_pause_ = cc->region_space_->GetObjectsAllocated();
241 cc->from_space_num_bytes_at_first_pause_ = cc->region_space_->GetBytesAllocated();
242 }
243 cc->is_marking_ = true;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700244 cc->mark_stack_mode_.StoreRelaxed(ConcurrentCopying::kMarkStackModeThreadLocal);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800245 if (UNLIKELY(Runtime::Current()->IsActiveTransaction())) {
Mathieu Chartier184c9dc2015-03-05 13:20:54 -0800246 CHECK(Runtime::Current()->IsAotCompiler());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800247 TimingLogger::ScopedTiming split2("(Paused)VisitTransactionRoots", cc->GetTimings());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700248 Runtime::Current()->VisitTransactionRoots(cc);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800249 }
250 }
251
252 private:
253 ConcurrentCopying* const concurrent_copying_;
254};
255
256// Switch threads that from from-space to to-space refs. Forward/mark the thread roots.
257void ConcurrentCopying::FlipThreadRoots() {
258 TimingLogger::ScopedTiming split("FlipThreadRoots", GetTimings());
259 if (kVerboseMode) {
260 LOG(INFO) << "time=" << region_space_->Time();
261 region_space_->DumpNonFreeRegions(LOG(INFO));
262 }
263 Thread* self = Thread::Current();
264 Locks::mutator_lock_->AssertNotHeld(self);
265 gc_barrier_->Init(self, 0);
266 ThreadFlipVisitor thread_flip_visitor(this, heap_->use_tlab_);
267 FlipCallback flip_callback(this);
Hiroshi Yamauchi76f55b02015-08-21 16:10:39 -0700268 heap_->ThreadFlipBegin(self); // Sync with JNI critical calls.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800269 size_t barrier_count = Runtime::Current()->FlipThreadRoots(
270 &thread_flip_visitor, &flip_callback, this);
Hiroshi Yamauchi76f55b02015-08-21 16:10:39 -0700271 heap_->ThreadFlipEnd(self);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800272 {
273 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
274 gc_barrier_->Increment(self, barrier_count);
275 }
276 is_asserting_to_space_invariant_ = true;
277 QuasiAtomic::ThreadFenceForConstructor();
278 if (kVerboseMode) {
279 LOG(INFO) << "time=" << region_space_->Time();
280 region_space_->DumpNonFreeRegions(LOG(INFO));
281 LOG(INFO) << "GC end of FlipThreadRoots";
282 }
283}
284
Mathieu Chartiera4f6af92015-08-11 17:35:25 -0700285void ConcurrentCopying::SwapStacks() {
286 heap_->SwapStacks();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800287}
288
289void ConcurrentCopying::RecordLiveStackFreezeSize(Thread* self) {
290 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
291 live_stack_freeze_size_ = heap_->GetLiveStack()->Size();
292}
293
294// Used to visit objects in the immune spaces.
295class ConcurrentCopyingImmuneSpaceObjVisitor {
296 public:
297 explicit ConcurrentCopyingImmuneSpaceObjVisitor(ConcurrentCopying* cc)
298 : collector_(cc) {}
299
Mathieu Chartier90443472015-07-16 20:32:27 -0700300 void operator()(mirror::Object* obj) const SHARED_REQUIRES(Locks::mutator_lock_)
301 SHARED_REQUIRES(Locks::heap_bitmap_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800302 DCHECK(obj != nullptr);
303 DCHECK(collector_->immune_region_.ContainsObject(obj));
304 accounting::ContinuousSpaceBitmap* cc_bitmap =
305 collector_->cc_heap_bitmap_->GetContinuousSpaceBitmap(obj);
306 DCHECK(cc_bitmap != nullptr)
307 << "An immune space object must have a bitmap";
308 if (kIsDebugBuild) {
309 DCHECK(collector_->heap_->GetMarkBitmap()->Test(obj))
310 << "Immune space object must be already marked";
311 }
312 // This may or may not succeed, which is ok.
313 if (kUseBakerReadBarrier) {
314 obj->AtomicSetReadBarrierPointer(ReadBarrier::WhitePtr(), ReadBarrier::GrayPtr());
315 }
316 if (cc_bitmap->AtomicTestAndSet(obj)) {
317 // Already marked. Do nothing.
318 } else {
319 // Newly marked. Set the gray bit and push it onto the mark stack.
320 CHECK(!kUseBakerReadBarrier || obj->GetReadBarrierPointer() == ReadBarrier::GrayPtr());
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700321 collector_->PushOntoMarkStack(obj);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800322 }
323 }
324
325 private:
Mathieu Chartier97509952015-07-13 14:35:43 -0700326 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800327};
328
329class EmptyCheckpoint : public Closure {
330 public:
331 explicit EmptyCheckpoint(ConcurrentCopying* concurrent_copying)
332 : concurrent_copying_(concurrent_copying) {
333 }
334
335 virtual void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
336 // Note: self is not necessarily equal to thread since thread may be suspended.
337 Thread* self = Thread::Current();
338 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
339 << thread->GetState() << " thread " << thread << " self " << self;
Lei Lidd9943d2015-02-02 14:24:44 +0800340 // If thread is a running mutator, then act on behalf of the garbage collector.
341 // See the code in ThreadList::RunCheckpoint.
Mathieu Chartier10d25082015-10-28 18:36:09 -0700342 concurrent_copying_->GetBarrier().Pass(self);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800343 }
344
345 private:
346 ConcurrentCopying* const concurrent_copying_;
347};
348
349// Concurrently mark roots that are guarded by read barriers and process the mark stack.
350void ConcurrentCopying::MarkingPhase() {
351 TimingLogger::ScopedTiming split("MarkingPhase", GetTimings());
352 if (kVerboseMode) {
353 LOG(INFO) << "GC MarkingPhase";
354 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700355 CHECK(weak_ref_access_enabled_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800356 {
357 // Mark the image root. The WB-based collectors do not need to
358 // scan the image objects from roots by relying on the card table,
359 // but it's necessary for the RB to-space invariant to hold.
360 TimingLogger::ScopedTiming split1("VisitImageRoots", GetTimings());
Mathieu Chartier073b16c2015-11-10 14:13:23 -0800361 for (space::ContinuousSpace* space : heap_->GetContinuousSpaces()) {
362 if (space->IsImageSpace()) {
363 gc::space::ImageSpace* image = space->AsImageSpace();
364 if (image != nullptr) {
365 mirror::ObjectArray<mirror::Object>* image_root = image->GetImageHeader().GetImageRoots();
366 mirror::Object* marked_image_root = Mark(image_root);
367 CHECK_EQ(image_root, marked_image_root) << "An image object does not move";
368 if (ReadBarrier::kEnableToSpaceInvariantChecks) {
369 AssertToSpaceInvariant(nullptr, MemberOffset(0), marked_image_root);
370 }
371 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800372 }
373 }
374 }
375 {
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -0700376 TimingLogger::ScopedTiming split2("VisitConcurrentRoots", GetTimings());
377 Runtime::Current()->VisitConcurrentRoots(this, kVisitRootFlagAllRoots);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800378 }
379 {
380 // TODO: don't visit the transaction roots if it's not active.
381 TimingLogger::ScopedTiming split5("VisitNonThreadRoots", GetTimings());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700382 Runtime::Current()->VisitNonThreadRoots(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800383 }
384
385 // Immune spaces.
386 for (auto& space : heap_->GetContinuousSpaces()) {
387 if (immune_region_.ContainsSpace(space)) {
388 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
389 accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
390 ConcurrentCopyingImmuneSpaceObjVisitor visitor(this);
391 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()),
392 reinterpret_cast<uintptr_t>(space->Limit()),
393 visitor);
394 }
395 }
396
397 Thread* self = Thread::Current();
398 {
Mathieu Chartiera6b1ead2015-10-06 10:32:38 -0700399 TimingLogger::ScopedTiming split7("ProcessMarkStack", GetTimings());
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700400 // We transition through three mark stack modes (thread-local, shared, GC-exclusive). The
401 // primary reasons are the fact that we need to use a checkpoint to process thread-local mark
402 // stacks, but after we disable weak refs accesses, we can't use a checkpoint due to a deadlock
403 // issue because running threads potentially blocking at WaitHoldingLocks, and that once we
404 // reach the point where we process weak references, we can avoid using a lock when accessing
405 // the GC mark stack, which makes mark stack processing more efficient.
406
407 // Process the mark stack once in the thread local stack mode. This marks most of the live
408 // objects, aside from weak ref accesses with read barriers (Reference::GetReferent() and system
409 // weaks) that may happen concurrently while we processing the mark stack and newly mark/gray
410 // objects and push refs on the mark stack.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800411 ProcessMarkStack();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700412 // Switch to the shared mark stack mode. That is, revoke and process thread-local mark stacks
413 // for the last time before transitioning to the shared mark stack mode, which would process new
414 // refs that may have been concurrently pushed onto the mark stack during the ProcessMarkStack()
415 // call above. At the same time, disable weak ref accesses using a per-thread flag. It's
416 // important to do these together in a single checkpoint so that we can ensure that mutators
417 // won't newly gray objects and push new refs onto the mark stack due to weak ref accesses and
418 // mutators safely transition to the shared mark stack mode (without leaving unprocessed refs on
419 // the thread-local mark stacks), without a race. This is why we use a thread-local weak ref
420 // access flag Thread::tls32_.weak_ref_access_enabled_ instead of the global ones.
421 SwitchToSharedMarkStackMode();
422 CHECK(!self->GetWeakRefAccessEnabled());
423 // Now that weak refs accesses are disabled, once we exhaust the shared mark stack again here
424 // (which may be non-empty if there were refs found on thread-local mark stacks during the above
425 // SwitchToSharedMarkStackMode() call), we won't have new refs to process, that is, mutators
426 // (via read barriers) have no way to produce any more refs to process. Marking converges once
427 // before we process weak refs below.
428 ProcessMarkStack();
429 CheckEmptyMarkStack();
430 // Switch to the GC exclusive mark stack mode so that we can process the mark stack without a
431 // lock from this point on.
432 SwitchToGcExclusiveMarkStackMode();
433 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800434 if (kVerboseMode) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800435 LOG(INFO) << "ProcessReferences";
436 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700437 // Process weak references. This may produce new refs to process and have them processed via
Mathieu Chartier97509952015-07-13 14:35:43 -0700438 // ProcessMarkStack (in the GC exclusive mark stack mode).
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700439 ProcessReferences(self);
440 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800441 if (kVerboseMode) {
442 LOG(INFO) << "SweepSystemWeaks";
443 }
444 SweepSystemWeaks(self);
445 if (kVerboseMode) {
446 LOG(INFO) << "SweepSystemWeaks done";
447 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700448 // Process the mark stack here one last time because the above SweepSystemWeaks() call may have
449 // marked some objects (strings alive) as hash_set::Erase() can call the hash function for
450 // arbitrary elements in the weak intern table in InternTable::Table::SweepWeaks().
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800451 ProcessMarkStack();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700452 CheckEmptyMarkStack();
453 // Re-enable weak ref accesses.
454 ReenableWeakRefAccess(self);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -0700455 // Free data for class loaders that we unloaded.
456 Runtime::Current()->GetClassLinker()->CleanupClassLoaders();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700457 // Marking is done. Disable marking.
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700458 DisableMarking();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700459 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800460 }
461
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700462 CHECK(weak_ref_access_enabled_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800463 if (kVerboseMode) {
464 LOG(INFO) << "GC end of MarkingPhase";
465 }
466}
467
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700468void ConcurrentCopying::ReenableWeakRefAccess(Thread* self) {
469 if (kVerboseMode) {
470 LOG(INFO) << "ReenableWeakRefAccess";
471 }
472 weak_ref_access_enabled_.StoreRelaxed(true); // This is for new threads.
473 QuasiAtomic::ThreadFenceForConstructor();
474 // Iterate all threads (don't need to or can't use a checkpoint) and re-enable weak ref access.
475 {
476 MutexLock mu(self, *Locks::thread_list_lock_);
477 std::list<Thread*> thread_list = Runtime::Current()->GetThreadList()->GetList();
478 for (Thread* thread : thread_list) {
479 thread->SetWeakRefAccessEnabled(true);
480 }
481 }
482 // Unblock blocking threads.
483 GetHeap()->GetReferenceProcessor()->BroadcastForSlowPath(self);
484 Runtime::Current()->BroadcastForNewSystemWeaks();
485}
486
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700487class DisableMarkingCheckpoint : public Closure {
488 public:
489 explicit DisableMarkingCheckpoint(ConcurrentCopying* concurrent_copying)
490 : concurrent_copying_(concurrent_copying) {
491 }
492
493 void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
494 // Note: self is not necessarily equal to thread since thread may be suspended.
495 Thread* self = Thread::Current();
496 DCHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
497 << thread->GetState() << " thread " << thread << " self " << self;
498 // Disable the thread-local is_gc_marking flag.
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -0700499 // Note a thread that has just started right before this checkpoint may have already this flag
500 // set to false, which is ok.
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700501 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.
Mathieu Chartier10d25082015-10-28 18:36:09 -0700504 concurrent_copying_->GetBarrier().Pass(self);
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700505 }
506
507 private:
508 ConcurrentCopying* const concurrent_copying_;
509};
510
511void ConcurrentCopying::IssueDisableMarkingCheckpoint() {
512 Thread* self = Thread::Current();
513 DisableMarkingCheckpoint check_point(this);
514 ThreadList* thread_list = Runtime::Current()->GetThreadList();
515 gc_barrier_->Init(self, 0);
516 size_t barrier_count = thread_list->RunCheckpoint(&check_point);
517 // If there are no threads to wait which implies that all the checkpoint functions are finished,
518 // then no need to release the mutator lock.
519 if (barrier_count == 0) {
520 return;
521 }
522 // Release locks then wait for all mutator threads to pass the barrier.
523 Locks::mutator_lock_->SharedUnlock(self);
524 {
525 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
526 gc_barrier_->Increment(self, barrier_count);
527 }
528 Locks::mutator_lock_->SharedLock(self);
529}
530
531void ConcurrentCopying::DisableMarking() {
532 // Change the global is_marking flag to false. Do a fence before doing a checkpoint to update the
533 // thread-local flags so that a new thread starting up will get the correct is_marking flag.
534 is_marking_ = false;
535 QuasiAtomic::ThreadFenceForConstructor();
536 // Use a checkpoint to turn off the thread-local is_gc_marking flags and to ensure no threads are
537 // still in the middle of a read barrier which may have a from-space ref cached in a local
538 // variable.
539 IssueDisableMarkingCheckpoint();
540 if (kUseTableLookupReadBarrier) {
541 heap_->rb_table_->ClearAll();
542 DCHECK(heap_->rb_table_->IsAllCleared());
543 }
544 is_mark_stack_push_disallowed_.StoreSequentiallyConsistent(1);
545 mark_stack_mode_.StoreSequentiallyConsistent(kMarkStackModeOff);
546}
547
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800548void ConcurrentCopying::IssueEmptyCheckpoint() {
549 Thread* self = Thread::Current();
550 EmptyCheckpoint check_point(this);
551 ThreadList* thread_list = Runtime::Current()->GetThreadList();
552 gc_barrier_->Init(self, 0);
553 size_t barrier_count = thread_list->RunCheckpoint(&check_point);
Lei Lidd9943d2015-02-02 14:24:44 +0800554 // If there are no threads to wait which implys that all the checkpoint functions are finished,
555 // then no need to release the mutator lock.
556 if (barrier_count == 0) {
557 return;
558 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800559 // Release locks then wait for all mutator threads to pass the barrier.
560 Locks::mutator_lock_->SharedUnlock(self);
561 {
562 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
563 gc_barrier_->Increment(self, barrier_count);
564 }
565 Locks::mutator_lock_->SharedLock(self);
566}
567
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -0700568void ConcurrentCopying::ExpandGcMarkStack() {
569 DCHECK(gc_mark_stack_->IsFull());
570 const size_t new_size = gc_mark_stack_->Capacity() * 2;
571 std::vector<StackReference<mirror::Object>> temp(gc_mark_stack_->Begin(),
572 gc_mark_stack_->End());
573 gc_mark_stack_->Resize(new_size);
574 for (auto& ref : temp) {
575 gc_mark_stack_->PushBack(ref.AsMirrorPtr());
576 }
577 DCHECK(!gc_mark_stack_->IsFull());
578}
579
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800580void ConcurrentCopying::PushOntoMarkStack(mirror::Object* to_ref) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700581 CHECK_EQ(is_mark_stack_push_disallowed_.LoadRelaxed(), 0)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800582 << " " << to_ref << " " << PrettyTypeOf(to_ref);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700583 Thread* self = Thread::Current(); // TODO: pass self as an argument from call sites?
584 CHECK(thread_running_gc_ != nullptr);
585 MarkStackMode mark_stack_mode = mark_stack_mode_.LoadRelaxed();
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -0700586 if (LIKELY(mark_stack_mode == kMarkStackModeThreadLocal)) {
587 if (LIKELY(self == thread_running_gc_)) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700588 // If GC-running thread, use the GC mark stack instead of a thread-local mark stack.
589 CHECK(self->GetThreadLocalMarkStack() == nullptr);
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -0700590 if (UNLIKELY(gc_mark_stack_->IsFull())) {
591 ExpandGcMarkStack();
592 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700593 gc_mark_stack_->PushBack(to_ref);
594 } else {
595 // Otherwise, use a thread-local mark stack.
596 accounting::AtomicStack<mirror::Object>* tl_mark_stack = self->GetThreadLocalMarkStack();
597 if (UNLIKELY(tl_mark_stack == nullptr || tl_mark_stack->IsFull())) {
598 MutexLock mu(self, mark_stack_lock_);
599 // Get a new thread local mark stack.
600 accounting::AtomicStack<mirror::Object>* new_tl_mark_stack;
601 if (!pooled_mark_stacks_.empty()) {
602 // Use a pooled mark stack.
603 new_tl_mark_stack = pooled_mark_stacks_.back();
604 pooled_mark_stacks_.pop_back();
605 } else {
606 // None pooled. Create a new one.
607 new_tl_mark_stack =
608 accounting::AtomicStack<mirror::Object>::Create(
609 "thread local mark stack", 4 * KB, 4 * KB);
610 }
611 DCHECK(new_tl_mark_stack != nullptr);
612 DCHECK(new_tl_mark_stack->IsEmpty());
613 new_tl_mark_stack->PushBack(to_ref);
614 self->SetThreadLocalMarkStack(new_tl_mark_stack);
615 if (tl_mark_stack != nullptr) {
616 // Store the old full stack into a vector.
617 revoked_mark_stacks_.push_back(tl_mark_stack);
618 }
619 } else {
620 tl_mark_stack->PushBack(to_ref);
621 }
622 }
623 } else if (mark_stack_mode == kMarkStackModeShared) {
624 // Access the shared GC mark stack with a lock.
625 MutexLock mu(self, mark_stack_lock_);
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -0700626 if (UNLIKELY(gc_mark_stack_->IsFull())) {
627 ExpandGcMarkStack();
628 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700629 gc_mark_stack_->PushBack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800630 } else {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700631 CHECK_EQ(static_cast<uint32_t>(mark_stack_mode),
Hiroshi Yamauchifa755182015-09-30 20:12:11 -0700632 static_cast<uint32_t>(kMarkStackModeGcExclusive))
633 << "ref=" << to_ref
634 << " self->gc_marking=" << self->GetIsGcMarking()
635 << " cc->is_marking=" << is_marking_;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700636 CHECK(self == thread_running_gc_)
637 << "Only GC-running thread should access the mark stack "
638 << "in the GC exclusive mark stack mode";
639 // Access the GC mark stack without a lock.
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -0700640 if (UNLIKELY(gc_mark_stack_->IsFull())) {
641 ExpandGcMarkStack();
642 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700643 gc_mark_stack_->PushBack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800644 }
645}
646
647accounting::ObjectStack* ConcurrentCopying::GetAllocationStack() {
648 return heap_->allocation_stack_.get();
649}
650
651accounting::ObjectStack* ConcurrentCopying::GetLiveStack() {
652 return heap_->live_stack_.get();
653}
654
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800655// The following visitors are that used to verify that there's no
656// references to the from-space left after marking.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700657class ConcurrentCopyingVerifyNoFromSpaceRefsVisitor : public SingleRootVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800658 public:
659 explicit ConcurrentCopyingVerifyNoFromSpaceRefsVisitor(ConcurrentCopying* collector)
660 : collector_(collector) {}
661
662 void operator()(mirror::Object* ref) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700663 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800664 if (ref == nullptr) {
665 // OK.
666 return;
667 }
668 collector_->AssertToSpaceInvariant(nullptr, MemberOffset(0), ref);
669 if (kUseBakerReadBarrier) {
670 if (collector_->RegionSpace()->IsInToSpace(ref)) {
671 CHECK(ref->GetReadBarrierPointer() == nullptr)
672 << "To-space ref " << ref << " " << PrettyTypeOf(ref)
673 << " has non-white rb_ptr " << ref->GetReadBarrierPointer();
674 } else {
675 CHECK(ref->GetReadBarrierPointer() == ReadBarrier::BlackPtr() ||
676 (ref->GetReadBarrierPointer() == ReadBarrier::WhitePtr() &&
677 collector_->IsOnAllocStack(ref)))
678 << "Non-moving/unevac from space ref " << ref << " " << PrettyTypeOf(ref)
679 << " has non-black rb_ptr " << ref->GetReadBarrierPointer()
680 << " but isn't on the alloc stack (and has white rb_ptr)."
681 << " Is it in the non-moving space="
682 << (collector_->GetHeap()->GetNonMovingSpace()->HasAddress(ref));
683 }
684 }
685 }
686
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700687 void VisitRoot(mirror::Object* root, const RootInfo& info ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -0700688 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800689 DCHECK(root != nullptr);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700690 operator()(root);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800691 }
692
693 private:
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700694 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800695};
696
697class ConcurrentCopyingVerifyNoFromSpaceRefsFieldVisitor {
698 public:
699 explicit ConcurrentCopyingVerifyNoFromSpaceRefsFieldVisitor(ConcurrentCopying* collector)
700 : collector_(collector) {}
701
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700702 void operator()(mirror::Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700703 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800704 mirror::Object* ref =
705 obj->GetFieldObject<mirror::Object, kDefaultVerifyFlags, kWithoutReadBarrier>(offset);
706 ConcurrentCopyingVerifyNoFromSpaceRefsVisitor visitor(collector_);
707 visitor(ref);
708 }
709 void operator()(mirror::Class* klass, mirror::Reference* ref) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700710 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800711 CHECK(klass->IsTypeOfReferenceClass());
712 this->operator()(ref, mirror::Reference::ReferentOffset(), false);
713 }
714
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700715 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
716 SHARED_REQUIRES(Locks::mutator_lock_) {
717 if (!root->IsNull()) {
718 VisitRoot(root);
719 }
720 }
721
722 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
723 SHARED_REQUIRES(Locks::mutator_lock_) {
724 ConcurrentCopyingVerifyNoFromSpaceRefsVisitor visitor(collector_);
725 visitor(root->AsMirrorPtr());
726 }
727
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800728 private:
Mathieu Chartier97509952015-07-13 14:35:43 -0700729 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800730};
731
732class ConcurrentCopyingVerifyNoFromSpaceRefsObjectVisitor {
733 public:
734 explicit ConcurrentCopyingVerifyNoFromSpaceRefsObjectVisitor(ConcurrentCopying* collector)
735 : collector_(collector) {}
736 void operator()(mirror::Object* obj) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700737 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800738 ObjectCallback(obj, collector_);
739 }
740 static void ObjectCallback(mirror::Object* obj, void *arg)
Mathieu Chartier90443472015-07-16 20:32:27 -0700741 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800742 CHECK(obj != nullptr);
743 ConcurrentCopying* collector = reinterpret_cast<ConcurrentCopying*>(arg);
744 space::RegionSpace* region_space = collector->RegionSpace();
745 CHECK(!region_space->IsInFromSpace(obj)) << "Scanning object " << obj << " in from space";
746 ConcurrentCopyingVerifyNoFromSpaceRefsFieldVisitor visitor(collector);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -0700747 obj->VisitReferences(visitor, visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800748 if (kUseBakerReadBarrier) {
749 if (collector->RegionSpace()->IsInToSpace(obj)) {
750 CHECK(obj->GetReadBarrierPointer() == nullptr)
751 << "obj=" << obj << " non-white rb_ptr " << obj->GetReadBarrierPointer();
752 } else {
753 CHECK(obj->GetReadBarrierPointer() == ReadBarrier::BlackPtr() ||
754 (obj->GetReadBarrierPointer() == ReadBarrier::WhitePtr() &&
755 collector->IsOnAllocStack(obj)))
756 << "Non-moving space/unevac from space ref " << obj << " " << PrettyTypeOf(obj)
757 << " has non-black rb_ptr " << obj->GetReadBarrierPointer()
758 << " but isn't on the alloc stack (and has white rb_ptr). Is it in the non-moving space="
759 << (collector->GetHeap()->GetNonMovingSpace()->HasAddress(obj));
760 }
761 }
762 }
763
764 private:
765 ConcurrentCopying* const collector_;
766};
767
768// Verify there's no from-space references left after the marking phase.
769void ConcurrentCopying::VerifyNoFromSpaceReferences() {
770 Thread* self = Thread::Current();
771 DCHECK(Locks::mutator_lock_->IsExclusiveHeld(self));
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700772 // Verify all threads have is_gc_marking to be false
773 {
774 MutexLock mu(self, *Locks::thread_list_lock_);
775 std::list<Thread*> thread_list = Runtime::Current()->GetThreadList()->GetList();
776 for (Thread* thread : thread_list) {
777 CHECK(!thread->GetIsGcMarking());
778 }
779 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800780 ConcurrentCopyingVerifyNoFromSpaceRefsObjectVisitor visitor(this);
781 // Roots.
782 {
783 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700784 ConcurrentCopyingVerifyNoFromSpaceRefsVisitor ref_visitor(this);
785 Runtime::Current()->VisitRoots(&ref_visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800786 }
787 // The to-space.
788 region_space_->WalkToSpace(ConcurrentCopyingVerifyNoFromSpaceRefsObjectVisitor::ObjectCallback,
789 this);
790 // Non-moving spaces.
791 {
792 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
793 heap_->GetMarkBitmap()->Visit(visitor);
794 }
795 // The alloc stack.
796 {
797 ConcurrentCopyingVerifyNoFromSpaceRefsVisitor ref_visitor(this);
Mathieu Chartiercb535da2015-01-23 13:50:03 -0800798 for (auto* it = heap_->allocation_stack_->Begin(), *end = heap_->allocation_stack_->End();
799 it < end; ++it) {
800 mirror::Object* const obj = it->AsMirrorPtr();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800801 if (obj != nullptr && obj->GetClass() != nullptr) {
802 // TODO: need to call this only if obj is alive?
803 ref_visitor(obj);
804 visitor(obj);
805 }
806 }
807 }
808 // TODO: LOS. But only refs in LOS are classes.
809}
810
811// The following visitors are used to assert the to-space invariant.
812class ConcurrentCopyingAssertToSpaceInvariantRefsVisitor {
813 public:
814 explicit ConcurrentCopyingAssertToSpaceInvariantRefsVisitor(ConcurrentCopying* collector)
815 : collector_(collector) {}
816
817 void operator()(mirror::Object* ref) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700818 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800819 if (ref == nullptr) {
820 // OK.
821 return;
822 }
823 collector_->AssertToSpaceInvariant(nullptr, MemberOffset(0), ref);
824 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800825
826 private:
Mathieu Chartier97509952015-07-13 14:35:43 -0700827 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800828};
829
830class ConcurrentCopyingAssertToSpaceInvariantFieldVisitor {
831 public:
832 explicit ConcurrentCopyingAssertToSpaceInvariantFieldVisitor(ConcurrentCopying* collector)
833 : collector_(collector) {}
834
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700835 void operator()(mirror::Object* obj, MemberOffset offset, bool is_static 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 mirror::Object* ref =
838 obj->GetFieldObject<mirror::Object, kDefaultVerifyFlags, kWithoutReadBarrier>(offset);
839 ConcurrentCopyingAssertToSpaceInvariantRefsVisitor visitor(collector_);
840 visitor(ref);
841 }
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700842 void operator()(mirror::Class* klass, mirror::Reference* ref ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700843 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800844 CHECK(klass->IsTypeOfReferenceClass());
845 }
846
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700847 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
848 SHARED_REQUIRES(Locks::mutator_lock_) {
849 if (!root->IsNull()) {
850 VisitRoot(root);
851 }
852 }
853
854 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
855 SHARED_REQUIRES(Locks::mutator_lock_) {
856 ConcurrentCopyingAssertToSpaceInvariantRefsVisitor visitor(collector_);
857 visitor(root->AsMirrorPtr());
858 }
859
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800860 private:
Mathieu Chartier97509952015-07-13 14:35:43 -0700861 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800862};
863
864class ConcurrentCopyingAssertToSpaceInvariantObjectVisitor {
865 public:
866 explicit ConcurrentCopyingAssertToSpaceInvariantObjectVisitor(ConcurrentCopying* collector)
867 : collector_(collector) {}
868 void operator()(mirror::Object* obj) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700869 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800870 ObjectCallback(obj, collector_);
871 }
872 static void ObjectCallback(mirror::Object* obj, void *arg)
Mathieu Chartier90443472015-07-16 20:32:27 -0700873 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800874 CHECK(obj != nullptr);
875 ConcurrentCopying* collector = reinterpret_cast<ConcurrentCopying*>(arg);
876 space::RegionSpace* region_space = collector->RegionSpace();
877 CHECK(!region_space->IsInFromSpace(obj)) << "Scanning object " << obj << " in from space";
878 collector->AssertToSpaceInvariant(nullptr, MemberOffset(0), obj);
879 ConcurrentCopyingAssertToSpaceInvariantFieldVisitor visitor(collector);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -0700880 obj->VisitReferences(visitor, visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800881 }
882
883 private:
Mathieu Chartier97509952015-07-13 14:35:43 -0700884 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800885};
886
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700887class RevokeThreadLocalMarkStackCheckpoint : public Closure {
888 public:
Roland Levillain3887c462015-08-12 18:15:42 +0100889 RevokeThreadLocalMarkStackCheckpoint(ConcurrentCopying* concurrent_copying,
890 bool disable_weak_ref_access)
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700891 : concurrent_copying_(concurrent_copying),
892 disable_weak_ref_access_(disable_weak_ref_access) {
893 }
894
895 virtual void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
896 // Note: self is not necessarily equal to thread since thread may be suspended.
897 Thread* self = Thread::Current();
898 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
899 << thread->GetState() << " thread " << thread << " self " << self;
900 // Revoke thread local mark stacks.
901 accounting::AtomicStack<mirror::Object>* tl_mark_stack = thread->GetThreadLocalMarkStack();
902 if (tl_mark_stack != nullptr) {
903 MutexLock mu(self, concurrent_copying_->mark_stack_lock_);
904 concurrent_copying_->revoked_mark_stacks_.push_back(tl_mark_stack);
905 thread->SetThreadLocalMarkStack(nullptr);
906 }
907 // Disable weak ref access.
908 if (disable_weak_ref_access_) {
909 thread->SetWeakRefAccessEnabled(false);
910 }
911 // If thread is a running mutator, then act on behalf of the garbage collector.
912 // See the code in ThreadList::RunCheckpoint.
Mathieu Chartier10d25082015-10-28 18:36:09 -0700913 concurrent_copying_->GetBarrier().Pass(self);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700914 }
915
916 private:
917 ConcurrentCopying* const concurrent_copying_;
918 const bool disable_weak_ref_access_;
919};
920
921void ConcurrentCopying::RevokeThreadLocalMarkStacks(bool disable_weak_ref_access) {
922 Thread* self = Thread::Current();
923 RevokeThreadLocalMarkStackCheckpoint check_point(this, disable_weak_ref_access);
924 ThreadList* thread_list = Runtime::Current()->GetThreadList();
925 gc_barrier_->Init(self, 0);
926 size_t barrier_count = thread_list->RunCheckpoint(&check_point);
927 // If there are no threads to wait which implys that all the checkpoint functions are finished,
928 // then no need to release the mutator lock.
929 if (barrier_count == 0) {
930 return;
931 }
932 Locks::mutator_lock_->SharedUnlock(self);
933 {
934 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
935 gc_barrier_->Increment(self, barrier_count);
936 }
937 Locks::mutator_lock_->SharedLock(self);
938}
939
940void ConcurrentCopying::RevokeThreadLocalMarkStack(Thread* thread) {
941 Thread* self = Thread::Current();
942 CHECK_EQ(self, thread);
943 accounting::AtomicStack<mirror::Object>* tl_mark_stack = thread->GetThreadLocalMarkStack();
944 if (tl_mark_stack != nullptr) {
945 CHECK(is_marking_);
946 MutexLock mu(self, mark_stack_lock_);
947 revoked_mark_stacks_.push_back(tl_mark_stack);
948 thread->SetThreadLocalMarkStack(nullptr);
949 }
950}
951
952void ConcurrentCopying::ProcessMarkStack() {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800953 if (kVerboseMode) {
954 LOG(INFO) << "ProcessMarkStack. ";
955 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700956 bool empty_prev = false;
957 while (true) {
958 bool empty = ProcessMarkStackOnce();
959 if (empty_prev && empty) {
960 // Saw empty mark stack for a second time, done.
961 break;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800962 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700963 empty_prev = empty;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800964 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700965}
966
967bool ConcurrentCopying::ProcessMarkStackOnce() {
968 Thread* self = Thread::Current();
969 CHECK(thread_running_gc_ != nullptr);
970 CHECK(self == thread_running_gc_);
971 CHECK(self->GetThreadLocalMarkStack() == nullptr);
972 size_t count = 0;
973 MarkStackMode mark_stack_mode = mark_stack_mode_.LoadRelaxed();
974 if (mark_stack_mode == kMarkStackModeThreadLocal) {
975 // Process the thread-local mark stacks and the GC mark stack.
976 count += ProcessThreadLocalMarkStacks(false);
977 while (!gc_mark_stack_->IsEmpty()) {
978 mirror::Object* to_ref = gc_mark_stack_->PopBack();
979 ProcessMarkStackRef(to_ref);
980 ++count;
981 }
982 gc_mark_stack_->Reset();
983 } else if (mark_stack_mode == kMarkStackModeShared) {
984 // Process the shared GC mark stack with a lock.
985 {
986 MutexLock mu(self, mark_stack_lock_);
987 CHECK(revoked_mark_stacks_.empty());
988 }
989 while (true) {
990 std::vector<mirror::Object*> refs;
991 {
992 // Copy refs with lock. Note the number of refs should be small.
993 MutexLock mu(self, mark_stack_lock_);
994 if (gc_mark_stack_->IsEmpty()) {
995 break;
996 }
997 for (StackReference<mirror::Object>* p = gc_mark_stack_->Begin();
998 p != gc_mark_stack_->End(); ++p) {
999 refs.push_back(p->AsMirrorPtr());
1000 }
1001 gc_mark_stack_->Reset();
1002 }
1003 for (mirror::Object* ref : refs) {
1004 ProcessMarkStackRef(ref);
1005 ++count;
1006 }
1007 }
1008 } else {
1009 CHECK_EQ(static_cast<uint32_t>(mark_stack_mode),
1010 static_cast<uint32_t>(kMarkStackModeGcExclusive));
1011 {
1012 MutexLock mu(self, mark_stack_lock_);
1013 CHECK(revoked_mark_stacks_.empty());
1014 }
1015 // Process the GC mark stack in the exclusive mode. No need to take the lock.
1016 while (!gc_mark_stack_->IsEmpty()) {
1017 mirror::Object* to_ref = gc_mark_stack_->PopBack();
1018 ProcessMarkStackRef(to_ref);
1019 ++count;
1020 }
1021 gc_mark_stack_->Reset();
1022 }
1023
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001024 // Return true if the stack was empty.
1025 return count == 0;
1026}
1027
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001028size_t ConcurrentCopying::ProcessThreadLocalMarkStacks(bool disable_weak_ref_access) {
1029 // Run a checkpoint to collect all thread local mark stacks and iterate over them all.
1030 RevokeThreadLocalMarkStacks(disable_weak_ref_access);
1031 size_t count = 0;
1032 std::vector<accounting::AtomicStack<mirror::Object>*> mark_stacks;
1033 {
1034 MutexLock mu(Thread::Current(), mark_stack_lock_);
1035 // Make a copy of the mark stack vector.
1036 mark_stacks = revoked_mark_stacks_;
1037 revoked_mark_stacks_.clear();
1038 }
1039 for (accounting::AtomicStack<mirror::Object>* mark_stack : mark_stacks) {
1040 for (StackReference<mirror::Object>* p = mark_stack->Begin(); p != mark_stack->End(); ++p) {
1041 mirror::Object* to_ref = p->AsMirrorPtr();
1042 ProcessMarkStackRef(to_ref);
1043 ++count;
1044 }
1045 {
1046 MutexLock mu(Thread::Current(), mark_stack_lock_);
1047 if (pooled_mark_stacks_.size() >= kMarkStackPoolSize) {
1048 // The pool has enough. Delete it.
1049 delete mark_stack;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001050 } else {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001051 // Otherwise, put it into the pool for later reuse.
1052 mark_stack->Reset();
1053 pooled_mark_stacks_.push_back(mark_stack);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001054 }
1055 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001056 }
1057 return count;
1058}
1059
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001060inline void ConcurrentCopying::ProcessMarkStackRef(mirror::Object* to_ref) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001061 DCHECK(!region_space_->IsInFromSpace(to_ref));
1062 if (kUseBakerReadBarrier) {
1063 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr())
1064 << " " << to_ref << " " << to_ref->GetReadBarrierPointer()
1065 << " is_marked=" << IsMarked(to_ref);
1066 }
1067 // Scan ref fields.
1068 Scan(to_ref);
1069 // Mark the gray ref as white or black.
1070 if (kUseBakerReadBarrier) {
1071 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr())
1072 << " " << to_ref << " " << to_ref->GetReadBarrierPointer()
1073 << " is_marked=" << IsMarked(to_ref);
1074 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001075#ifdef USE_BAKER_OR_BROOKS_READ_BARRIER
1076 if (UNLIKELY((to_ref->GetClass<kVerifyNone, kWithoutReadBarrier>()->IsTypeOfReferenceClass() &&
1077 to_ref->AsReference()->GetReferent<kWithoutReadBarrier>() != nullptr &&
1078 !IsInToSpace(to_ref->AsReference()->GetReferent<kWithoutReadBarrier>())))) {
Hiroshi Yamauchi70c08d32015-09-10 16:01:30 -07001079 // Leave this Reference gray in the queue so that GetReferent() will trigger a read barrier. We
1080 // will change it to black or white later in ReferenceQueue::DequeuePendingReference().
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001081 CHECK(to_ref->AsReference()->IsEnqueued()) << "Left unenqueued ref gray " << to_ref;
1082 } else {
Hiroshi Yamauchi70c08d32015-09-10 16:01:30 -07001083 // We may occasionally leave a Reference black or white in the queue if its referent happens to
1084 // be concurrently marked after the Scan() call above has enqueued the Reference, in which case
1085 // the above IsInToSpace() evaluates to true and we change the color from gray to black or white
1086 // here in this else block.
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001087 if (kUseBakerReadBarrier) {
1088 if (region_space_->IsInToSpace(to_ref)) {
1089 // If to-space, change from gray to white.
1090 bool success = to_ref->AtomicSetReadBarrierPointer(ReadBarrier::GrayPtr(),
1091 ReadBarrier::WhitePtr());
1092 CHECK(success) << "Must succeed as we won the race.";
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001093 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::WhitePtr());
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001094 } else {
1095 // If non-moving space/unevac from space, change from gray
1096 // to black. We can't change gray to white because it's not
1097 // safe to use CAS if two threads change values in opposite
1098 // directions (A->B and B->A). So, we change it to black to
1099 // indicate non-moving objects that have been marked
1100 // through. Note we'd need to change from black to white
1101 // later (concurrently).
1102 bool success = to_ref->AtomicSetReadBarrierPointer(ReadBarrier::GrayPtr(),
1103 ReadBarrier::BlackPtr());
1104 CHECK(success) << "Must succeed as we won the race.";
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001105 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::BlackPtr());
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001106 }
1107 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001108 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001109#else
1110 DCHECK(!kUseBakerReadBarrier);
1111#endif
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001112 if (ReadBarrier::kEnableToSpaceInvariantChecks || kIsDebugBuild) {
1113 ConcurrentCopyingAssertToSpaceInvariantObjectVisitor visitor(this);
1114 visitor(to_ref);
1115 }
1116}
1117
1118void ConcurrentCopying::SwitchToSharedMarkStackMode() {
1119 Thread* self = Thread::Current();
1120 CHECK(thread_running_gc_ != nullptr);
1121 CHECK_EQ(self, thread_running_gc_);
1122 CHECK(self->GetThreadLocalMarkStack() == nullptr);
1123 MarkStackMode before_mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1124 CHECK_EQ(static_cast<uint32_t>(before_mark_stack_mode),
1125 static_cast<uint32_t>(kMarkStackModeThreadLocal));
1126 mark_stack_mode_.StoreRelaxed(kMarkStackModeShared);
1127 CHECK(weak_ref_access_enabled_.LoadRelaxed());
1128 weak_ref_access_enabled_.StoreRelaxed(false);
1129 QuasiAtomic::ThreadFenceForConstructor();
1130 // Process the thread local mark stacks one last time after switching to the shared mark stack
1131 // mode and disable weak ref accesses.
1132 ProcessThreadLocalMarkStacks(true);
1133 if (kVerboseMode) {
1134 LOG(INFO) << "Switched to shared mark stack mode and disabled weak ref access";
1135 }
1136}
1137
1138void ConcurrentCopying::SwitchToGcExclusiveMarkStackMode() {
1139 Thread* self = Thread::Current();
1140 CHECK(thread_running_gc_ != nullptr);
1141 CHECK_EQ(self, thread_running_gc_);
1142 CHECK(self->GetThreadLocalMarkStack() == nullptr);
1143 MarkStackMode before_mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1144 CHECK_EQ(static_cast<uint32_t>(before_mark_stack_mode),
1145 static_cast<uint32_t>(kMarkStackModeShared));
1146 mark_stack_mode_.StoreRelaxed(kMarkStackModeGcExclusive);
1147 QuasiAtomic::ThreadFenceForConstructor();
1148 if (kVerboseMode) {
1149 LOG(INFO) << "Switched to GC exclusive mark stack mode";
1150 }
1151}
1152
1153void ConcurrentCopying::CheckEmptyMarkStack() {
1154 Thread* self = Thread::Current();
1155 CHECK(thread_running_gc_ != nullptr);
1156 CHECK_EQ(self, thread_running_gc_);
1157 CHECK(self->GetThreadLocalMarkStack() == nullptr);
1158 MarkStackMode mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1159 if (mark_stack_mode == kMarkStackModeThreadLocal) {
1160 // Thread-local mark stack mode.
1161 RevokeThreadLocalMarkStacks(false);
1162 MutexLock mu(Thread::Current(), mark_stack_lock_);
1163 if (!revoked_mark_stacks_.empty()) {
1164 for (accounting::AtomicStack<mirror::Object>* mark_stack : revoked_mark_stacks_) {
1165 while (!mark_stack->IsEmpty()) {
1166 mirror::Object* obj = mark_stack->PopBack();
1167 if (kUseBakerReadBarrier) {
1168 mirror::Object* rb_ptr = obj->GetReadBarrierPointer();
1169 LOG(INFO) << "On mark queue : " << obj << " " << PrettyTypeOf(obj) << " rb_ptr=" << rb_ptr
1170 << " is_marked=" << IsMarked(obj);
1171 } else {
1172 LOG(INFO) << "On mark queue : " << obj << " " << PrettyTypeOf(obj)
1173 << " is_marked=" << IsMarked(obj);
1174 }
1175 }
1176 }
1177 LOG(FATAL) << "mark stack is not empty";
1178 }
1179 } else {
1180 // Shared, GC-exclusive, or off.
1181 MutexLock mu(Thread::Current(), mark_stack_lock_);
1182 CHECK(gc_mark_stack_->IsEmpty());
1183 CHECK(revoked_mark_stacks_.empty());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001184 }
1185}
1186
1187void ConcurrentCopying::SweepSystemWeaks(Thread* self) {
1188 TimingLogger::ScopedTiming split("SweepSystemWeaks", GetTimings());
1189 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier97509952015-07-13 14:35:43 -07001190 Runtime::Current()->SweepSystemWeaks(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001191}
1192
1193void ConcurrentCopying::Sweep(bool swap_bitmaps) {
1194 {
1195 TimingLogger::ScopedTiming t("MarkStackAsLive", GetTimings());
1196 accounting::ObjectStack* live_stack = heap_->GetLiveStack();
1197 if (kEnableFromSpaceAccountingCheck) {
1198 CHECK_GE(live_stack_freeze_size_, live_stack->Size());
1199 }
1200 heap_->MarkAllocStackAsLive(live_stack);
1201 live_stack->Reset();
1202 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001203 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001204 TimingLogger::ScopedTiming split("Sweep", GetTimings());
1205 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
1206 if (space->IsContinuousMemMapAllocSpace()) {
1207 space::ContinuousMemMapAllocSpace* alloc_space = space->AsContinuousMemMapAllocSpace();
1208 if (space == region_space_ || immune_region_.ContainsSpace(space)) {
1209 continue;
1210 }
1211 TimingLogger::ScopedTiming split2(
1212 alloc_space->IsZygoteSpace() ? "SweepZygoteSpace" : "SweepAllocSpace", GetTimings());
1213 RecordFree(alloc_space->Sweep(swap_bitmaps));
1214 }
1215 }
1216 SweepLargeObjects(swap_bitmaps);
1217}
1218
1219void ConcurrentCopying::SweepLargeObjects(bool swap_bitmaps) {
1220 TimingLogger::ScopedTiming split("SweepLargeObjects", GetTimings());
1221 RecordFreeLOS(heap_->GetLargeObjectsSpace()->Sweep(swap_bitmaps));
1222}
1223
1224class ConcurrentCopyingClearBlackPtrsVisitor {
1225 public:
1226 explicit ConcurrentCopyingClearBlackPtrsVisitor(ConcurrentCopying* cc)
1227 : collector_(cc) {}
Andreas Gampe65b798e2015-04-06 09:35:22 -07001228#ifndef USE_BAKER_OR_BROOKS_READ_BARRIER
1229 NO_RETURN
1230#endif
Mathieu Chartier90443472015-07-16 20:32:27 -07001231 void operator()(mirror::Object* obj) const SHARED_REQUIRES(Locks::mutator_lock_)
1232 SHARED_REQUIRES(Locks::heap_bitmap_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001233 DCHECK(obj != nullptr);
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08001234 DCHECK(collector_->heap_->GetMarkBitmap()->Test(obj)) << obj;
1235 DCHECK_EQ(obj->GetReadBarrierPointer(), ReadBarrier::BlackPtr()) << obj;
Hiroshi Yamauchi60f63f52015-04-23 16:12:40 -07001236 obj->AtomicSetReadBarrierPointer(ReadBarrier::BlackPtr(), ReadBarrier::WhitePtr());
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08001237 DCHECK_EQ(obj->GetReadBarrierPointer(), ReadBarrier::WhitePtr()) << obj;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001238 }
1239
1240 private:
1241 ConcurrentCopying* const collector_;
1242};
1243
1244// Clear the black ptrs in non-moving objects back to white.
1245void ConcurrentCopying::ClearBlackPtrs() {
1246 CHECK(kUseBakerReadBarrier);
1247 TimingLogger::ScopedTiming split("ClearBlackPtrs", GetTimings());
1248 ConcurrentCopyingClearBlackPtrsVisitor visitor(this);
1249 for (auto& space : heap_->GetContinuousSpaces()) {
1250 if (space == region_space_) {
1251 continue;
1252 }
1253 accounting::ContinuousSpaceBitmap* mark_bitmap = space->GetMarkBitmap();
1254 if (kVerboseMode) {
1255 LOG(INFO) << "ClearBlackPtrs: " << *space << " bitmap: " << *mark_bitmap;
1256 }
1257 mark_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()),
1258 reinterpret_cast<uintptr_t>(space->Limit()),
1259 visitor);
1260 }
1261 space::LargeObjectSpace* large_object_space = heap_->GetLargeObjectsSpace();
1262 large_object_space->GetMarkBitmap()->VisitMarkedRange(
1263 reinterpret_cast<uintptr_t>(large_object_space->Begin()),
1264 reinterpret_cast<uintptr_t>(large_object_space->End()),
1265 visitor);
1266 // Objects on the allocation stack?
1267 if (ReadBarrier::kEnableReadBarrierInvariantChecks || kIsDebugBuild) {
1268 size_t count = GetAllocationStack()->Size();
Mathieu Chartiercb535da2015-01-23 13:50:03 -08001269 auto* it = GetAllocationStack()->Begin();
1270 auto* end = GetAllocationStack()->End();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001271 for (size_t i = 0; i < count; ++i, ++it) {
Mathieu Chartiercb535da2015-01-23 13:50:03 -08001272 CHECK_LT(it, end);
1273 mirror::Object* obj = it->AsMirrorPtr();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001274 if (obj != nullptr) {
1275 // Must have been cleared above.
Mathieu Chartiercb535da2015-01-23 13:50:03 -08001276 CHECK_EQ(obj->GetReadBarrierPointer(), ReadBarrier::WhitePtr()) << obj;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001277 }
1278 }
1279 }
1280}
1281
1282void ConcurrentCopying::ReclaimPhase() {
1283 TimingLogger::ScopedTiming split("ReclaimPhase", GetTimings());
1284 if (kVerboseMode) {
1285 LOG(INFO) << "GC ReclaimPhase";
1286 }
1287 Thread* self = Thread::Current();
1288
1289 {
1290 // Double-check that the mark stack is empty.
1291 // Note: need to set this after VerifyNoFromSpaceRef().
1292 is_asserting_to_space_invariant_ = false;
1293 QuasiAtomic::ThreadFenceForConstructor();
1294 if (kVerboseMode) {
1295 LOG(INFO) << "Issue an empty check point. ";
1296 }
1297 IssueEmptyCheckpoint();
1298 // Disable the check.
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001299 is_mark_stack_push_disallowed_.StoreSequentiallyConsistent(0);
1300 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001301 }
1302
1303 {
1304 // Record freed objects.
1305 TimingLogger::ScopedTiming split2("RecordFree", GetTimings());
1306 // Don't include thread-locals that are in the to-space.
1307 uint64_t from_bytes = region_space_->GetBytesAllocatedInFromSpace();
1308 uint64_t from_objects = region_space_->GetObjectsAllocatedInFromSpace();
1309 uint64_t unevac_from_bytes = region_space_->GetBytesAllocatedInUnevacFromSpace();
1310 uint64_t unevac_from_objects = region_space_->GetObjectsAllocatedInUnevacFromSpace();
1311 uint64_t to_bytes = bytes_moved_.LoadSequentiallyConsistent();
1312 uint64_t to_objects = objects_moved_.LoadSequentiallyConsistent();
1313 if (kEnableFromSpaceAccountingCheck) {
1314 CHECK_EQ(from_space_num_objects_at_first_pause_, from_objects + unevac_from_objects);
1315 CHECK_EQ(from_space_num_bytes_at_first_pause_, from_bytes + unevac_from_bytes);
1316 }
1317 CHECK_LE(to_objects, from_objects);
1318 CHECK_LE(to_bytes, from_bytes);
1319 int64_t freed_bytes = from_bytes - to_bytes;
1320 int64_t freed_objects = from_objects - to_objects;
1321 if (kVerboseMode) {
1322 LOG(INFO) << "RecordFree:"
1323 << " from_bytes=" << from_bytes << " from_objects=" << from_objects
1324 << " unevac_from_bytes=" << unevac_from_bytes << " unevac_from_objects=" << unevac_from_objects
1325 << " to_bytes=" << to_bytes << " to_objects=" << to_objects
1326 << " freed_bytes=" << freed_bytes << " freed_objects=" << freed_objects
1327 << " from_space size=" << region_space_->FromSpaceSize()
1328 << " unevac_from_space size=" << region_space_->UnevacFromSpaceSize()
1329 << " to_space size=" << region_space_->ToSpaceSize();
1330 LOG(INFO) << "(before) num_bytes_allocated=" << heap_->num_bytes_allocated_.LoadSequentiallyConsistent();
1331 }
1332 RecordFree(ObjectBytePair(freed_objects, freed_bytes));
1333 if (kVerboseMode) {
1334 LOG(INFO) << "(after) num_bytes_allocated=" << heap_->num_bytes_allocated_.LoadSequentiallyConsistent();
1335 }
1336 }
1337
1338 {
1339 TimingLogger::ScopedTiming split3("ComputeUnevacFromSpaceLiveRatio", GetTimings());
1340 ComputeUnevacFromSpaceLiveRatio();
1341 }
1342
1343 {
1344 TimingLogger::ScopedTiming split4("ClearFromSpace", GetTimings());
1345 region_space_->ClearFromSpace();
1346 }
1347
1348 {
1349 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1350 if (kUseBakerReadBarrier) {
1351 ClearBlackPtrs();
1352 }
1353 Sweep(false);
1354 SwapBitmaps();
1355 heap_->UnBindBitmaps();
1356
1357 // Remove bitmaps for the immune spaces.
1358 while (!cc_bitmaps_.empty()) {
1359 accounting::ContinuousSpaceBitmap* cc_bitmap = cc_bitmaps_.back();
1360 cc_heap_bitmap_->RemoveContinuousSpaceBitmap(cc_bitmap);
1361 delete cc_bitmap;
1362 cc_bitmaps_.pop_back();
1363 }
1364 region_space_bitmap_ = nullptr;
1365 }
1366
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001367 CheckEmptyMarkStack();
1368
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001369 if (kVerboseMode) {
1370 LOG(INFO) << "GC end of ReclaimPhase";
1371 }
1372}
1373
1374class ConcurrentCopyingComputeUnevacFromSpaceLiveRatioVisitor {
1375 public:
1376 explicit ConcurrentCopyingComputeUnevacFromSpaceLiveRatioVisitor(ConcurrentCopying* cc)
1377 : collector_(cc) {}
Mathieu Chartier90443472015-07-16 20:32:27 -07001378 void operator()(mirror::Object* ref) const SHARED_REQUIRES(Locks::mutator_lock_)
1379 SHARED_REQUIRES(Locks::heap_bitmap_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001380 DCHECK(ref != nullptr);
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08001381 DCHECK(collector_->region_space_bitmap_->Test(ref)) << ref;
1382 DCHECK(collector_->region_space_->IsInUnevacFromSpace(ref)) << ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001383 if (kUseBakerReadBarrier) {
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08001384 DCHECK_EQ(ref->GetReadBarrierPointer(), ReadBarrier::BlackPtr()) << ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001385 // Clear the black ptr.
Hiroshi Yamauchi60f63f52015-04-23 16:12:40 -07001386 ref->AtomicSetReadBarrierPointer(ReadBarrier::BlackPtr(), ReadBarrier::WhitePtr());
1387 DCHECK_EQ(ref->GetReadBarrierPointer(), ReadBarrier::WhitePtr()) << ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001388 }
1389 size_t obj_size = ref->SizeOf();
1390 size_t alloc_size = RoundUp(obj_size, space::RegionSpace::kAlignment);
1391 collector_->region_space_->AddLiveBytes(ref, alloc_size);
1392 }
1393
1394 private:
Mathieu Chartier97509952015-07-13 14:35:43 -07001395 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001396};
1397
1398// Compute how much live objects are left in regions.
1399void ConcurrentCopying::ComputeUnevacFromSpaceLiveRatio() {
1400 region_space_->AssertAllRegionLiveBytesZeroOrCleared();
1401 ConcurrentCopyingComputeUnevacFromSpaceLiveRatioVisitor visitor(this);
1402 region_space_bitmap_->VisitMarkedRange(reinterpret_cast<uintptr_t>(region_space_->Begin()),
1403 reinterpret_cast<uintptr_t>(region_space_->Limit()),
1404 visitor);
1405}
1406
1407// Assert the to-space invariant.
1408void ConcurrentCopying::AssertToSpaceInvariant(mirror::Object* obj, MemberOffset offset,
1409 mirror::Object* ref) {
1410 CHECK(heap_->collector_type_ == kCollectorTypeCC) << static_cast<size_t>(heap_->collector_type_);
1411 if (is_asserting_to_space_invariant_) {
1412 if (region_space_->IsInToSpace(ref)) {
1413 // OK.
1414 return;
1415 } else if (region_space_->IsInUnevacFromSpace(ref)) {
1416 CHECK(region_space_bitmap_->Test(ref)) << ref;
1417 } else if (region_space_->IsInFromSpace(ref)) {
1418 // Not OK. Do extra logging.
1419 if (obj != nullptr) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001420 LogFromSpaceRefHolder(obj, offset);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001421 }
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001422 ref->GetLockWord(false).Dump(LOG(INTERNAL_FATAL));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001423 CHECK(false) << "Found from-space ref " << ref << " " << PrettyTypeOf(ref);
1424 } else {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001425 AssertToSpaceInvariantInNonMovingSpace(obj, ref);
1426 }
1427 }
1428}
1429
1430class RootPrinter {
1431 public:
1432 RootPrinter() { }
1433
1434 template <class MirrorType>
1435 ALWAYS_INLINE void VisitRootIfNonNull(mirror::CompressedReference<MirrorType>* root)
Mathieu Chartier90443472015-07-16 20:32:27 -07001436 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001437 if (!root->IsNull()) {
1438 VisitRoot(root);
1439 }
1440 }
1441
1442 template <class MirrorType>
1443 void VisitRoot(mirror::Object** root)
Mathieu Chartier90443472015-07-16 20:32:27 -07001444 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001445 LOG(INTERNAL_FATAL) << "root=" << root << " ref=" << *root;
1446 }
1447
1448 template <class MirrorType>
1449 void VisitRoot(mirror::CompressedReference<MirrorType>* root)
Mathieu Chartier90443472015-07-16 20:32:27 -07001450 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001451 LOG(INTERNAL_FATAL) << "root=" << root << " ref=" << root->AsMirrorPtr();
1452 }
1453};
1454
1455void ConcurrentCopying::AssertToSpaceInvariant(GcRootSource* gc_root_source,
1456 mirror::Object* ref) {
1457 CHECK(heap_->collector_type_ == kCollectorTypeCC) << static_cast<size_t>(heap_->collector_type_);
1458 if (is_asserting_to_space_invariant_) {
1459 if (region_space_->IsInToSpace(ref)) {
1460 // OK.
1461 return;
1462 } else if (region_space_->IsInUnevacFromSpace(ref)) {
1463 CHECK(region_space_bitmap_->Test(ref)) << ref;
1464 } else if (region_space_->IsInFromSpace(ref)) {
1465 // Not OK. Do extra logging.
1466 if (gc_root_source == nullptr) {
1467 // No info.
1468 } else if (gc_root_source->HasArtField()) {
1469 ArtField* field = gc_root_source->GetArtField();
1470 LOG(INTERNAL_FATAL) << "gc root in field " << field << " " << PrettyField(field);
1471 RootPrinter root_printer;
1472 field->VisitRoots(root_printer);
1473 } else if (gc_root_source->HasArtMethod()) {
1474 ArtMethod* method = gc_root_source->GetArtMethod();
1475 LOG(INTERNAL_FATAL) << "gc root in method " << method << " " << PrettyMethod(method);
1476 RootPrinter root_printer;
Mathieu Chartier1147b9b2015-09-14 18:50:08 -07001477 method->VisitRoots(root_printer, sizeof(void*));
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001478 }
1479 ref->GetLockWord(false).Dump(LOG(INTERNAL_FATAL));
1480 region_space_->DumpNonFreeRegions(LOG(INTERNAL_FATAL));
1481 PrintFileToLog("/proc/self/maps", LogSeverity::INTERNAL_FATAL);
1482 MemMap::DumpMaps(LOG(INTERNAL_FATAL), true);
1483 CHECK(false) << "Found from-space ref " << ref << " " << PrettyTypeOf(ref);
1484 } else {
1485 AssertToSpaceInvariantInNonMovingSpace(nullptr, ref);
1486 }
1487 }
1488}
1489
1490void ConcurrentCopying::LogFromSpaceRefHolder(mirror::Object* obj, MemberOffset offset) {
1491 if (kUseBakerReadBarrier) {
1492 LOG(INFO) << "holder=" << obj << " " << PrettyTypeOf(obj)
1493 << " holder rb_ptr=" << obj->GetReadBarrierPointer();
1494 } else {
1495 LOG(INFO) << "holder=" << obj << " " << PrettyTypeOf(obj);
1496 }
1497 if (region_space_->IsInFromSpace(obj)) {
1498 LOG(INFO) << "holder is in the from-space.";
1499 } else if (region_space_->IsInToSpace(obj)) {
1500 LOG(INFO) << "holder is in the to-space.";
1501 } else if (region_space_->IsInUnevacFromSpace(obj)) {
1502 LOG(INFO) << "holder is in the unevac from-space.";
1503 if (region_space_bitmap_->Test(obj)) {
1504 LOG(INFO) << "holder is marked in the region space bitmap.";
1505 } else {
1506 LOG(INFO) << "holder is not marked in the region space bitmap.";
1507 }
1508 } else {
1509 // In a non-moving space.
1510 if (immune_region_.ContainsObject(obj)) {
1511 LOG(INFO) << "holder is in the image or the zygote space.";
1512 accounting::ContinuousSpaceBitmap* cc_bitmap =
1513 cc_heap_bitmap_->GetContinuousSpaceBitmap(obj);
1514 CHECK(cc_bitmap != nullptr)
1515 << "An immune space object must have a bitmap.";
1516 if (cc_bitmap->Test(obj)) {
1517 LOG(INFO) << "holder is marked in the bit map.";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001518 } else {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001519 LOG(INFO) << "holder is NOT marked in the bit map.";
1520 }
1521 } else {
1522 LOG(INFO) << "holder is in a non-moving (or main) space.";
1523 accounting::ContinuousSpaceBitmap* mark_bitmap =
1524 heap_mark_bitmap_->GetContinuousSpaceBitmap(obj);
1525 accounting::LargeObjectBitmap* los_bitmap =
1526 heap_mark_bitmap_->GetLargeObjectBitmap(obj);
1527 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
1528 bool is_los = mark_bitmap == nullptr;
1529 if (!is_los && mark_bitmap->Test(obj)) {
1530 LOG(INFO) << "holder is marked in the mark bit map.";
1531 } else if (is_los && los_bitmap->Test(obj)) {
1532 LOG(INFO) << "holder is marked in the los bit map.";
1533 } else {
1534 // If ref is on the allocation stack, then it is considered
1535 // mark/alive (but not necessarily on the live stack.)
1536 if (IsOnAllocStack(obj)) {
1537 LOG(INFO) << "holder is on the alloc stack.";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001538 } else {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001539 LOG(INFO) << "holder is not marked or on the alloc stack.";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001540 }
1541 }
1542 }
1543 }
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001544 LOG(INFO) << "offset=" << offset.SizeValue();
1545}
1546
1547void ConcurrentCopying::AssertToSpaceInvariantInNonMovingSpace(mirror::Object* obj,
1548 mirror::Object* ref) {
1549 // In a non-moving spaces. Check that the ref is marked.
1550 if (immune_region_.ContainsObject(ref)) {
1551 accounting::ContinuousSpaceBitmap* cc_bitmap =
1552 cc_heap_bitmap_->GetContinuousSpaceBitmap(ref);
1553 CHECK(cc_bitmap != nullptr)
1554 << "An immune space ref must have a bitmap. " << ref;
1555 if (kUseBakerReadBarrier) {
1556 CHECK(cc_bitmap->Test(ref))
1557 << "Unmarked immune space ref. obj=" << obj << " rb_ptr="
1558 << obj->GetReadBarrierPointer() << " ref=" << ref;
1559 } else {
1560 CHECK(cc_bitmap->Test(ref))
1561 << "Unmarked immune space ref. obj=" << obj << " ref=" << ref;
1562 }
1563 } else {
1564 accounting::ContinuousSpaceBitmap* mark_bitmap =
1565 heap_mark_bitmap_->GetContinuousSpaceBitmap(ref);
1566 accounting::LargeObjectBitmap* los_bitmap =
1567 heap_mark_bitmap_->GetLargeObjectBitmap(ref);
1568 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
1569 bool is_los = mark_bitmap == nullptr;
1570 if ((!is_los && mark_bitmap->Test(ref)) ||
1571 (is_los && los_bitmap->Test(ref))) {
1572 // OK.
1573 } else {
1574 // If ref is on the allocation stack, then it may not be
1575 // marked live, but considered marked/alive (but not
1576 // necessarily on the live stack).
1577 CHECK(IsOnAllocStack(ref)) << "Unmarked ref that's not on the allocation stack. "
1578 << "obj=" << obj << " ref=" << ref;
1579 }
1580 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001581}
1582
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001583// Used to scan ref fields of an object.
1584class ConcurrentCopyingRefFieldsVisitor {
1585 public:
1586 explicit ConcurrentCopyingRefFieldsVisitor(ConcurrentCopying* collector)
1587 : collector_(collector) {}
1588
1589 void operator()(mirror::Object* obj, MemberOffset offset, bool /* is_static */)
Mathieu Chartier90443472015-07-16 20:32:27 -07001590 const ALWAYS_INLINE SHARED_REQUIRES(Locks::mutator_lock_)
1591 SHARED_REQUIRES(Locks::heap_bitmap_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001592 collector_->Process(obj, offset);
1593 }
1594
1595 void operator()(mirror::Class* klass, mirror::Reference* ref) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001596 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001597 CHECK(klass->IsTypeOfReferenceClass());
1598 collector_->DelayReferenceReferent(klass, ref);
1599 }
1600
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001601 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001602 ALWAYS_INLINE
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001603 SHARED_REQUIRES(Locks::mutator_lock_) {
1604 if (!root->IsNull()) {
1605 VisitRoot(root);
1606 }
1607 }
1608
1609 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001610 ALWAYS_INLINE
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001611 SHARED_REQUIRES(Locks::mutator_lock_) {
1612 collector_->MarkRoot(root);
1613 }
1614
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001615 private:
1616 ConcurrentCopying* const collector_;
1617};
1618
1619// Scan ref fields of an object.
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001620inline void ConcurrentCopying::Scan(mirror::Object* to_ref) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001621 DCHECK(!region_space_->IsInFromSpace(to_ref));
1622 ConcurrentCopyingRefFieldsVisitor visitor(this);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07001623 to_ref->VisitReferences(visitor, visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001624}
1625
1626// Process a field.
1627inline void ConcurrentCopying::Process(mirror::Object* obj, MemberOffset offset) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001628 mirror::Object* ref = obj->GetFieldObject<
1629 mirror::Object, kVerifyNone, kWithoutReadBarrier, false>(offset);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001630 mirror::Object* to_ref = Mark(ref);
1631 if (to_ref == ref) {
1632 return;
1633 }
1634 // This may fail if the mutator writes to the field at the same time. But it's ok.
1635 mirror::Object* expected_ref = ref;
1636 mirror::Object* new_ref = to_ref;
1637 do {
1638 if (expected_ref !=
1639 obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier, false>(offset)) {
1640 // It was updated by the mutator.
1641 break;
1642 }
Hiroshi Yamauchifed3e2f2015-10-20 11:11:56 -07001643 } while (!obj->CasFieldWeakRelaxedObjectWithoutWriteBarrier<
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001644 false, false, kVerifyNone>(offset, expected_ref, new_ref));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001645}
1646
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001647// Process some roots.
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001648inline void ConcurrentCopying::VisitRoots(
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001649 mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED) {
1650 for (size_t i = 0; i < count; ++i) {
1651 mirror::Object** root = roots[i];
1652 mirror::Object* ref = *root;
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001653 mirror::Object* to_ref = Mark(ref);
1654 if (to_ref == ref) {
Mathieu Chartier4809d0a2015-04-07 10:39:04 -07001655 continue;
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001656 }
1657 Atomic<mirror::Object*>* addr = reinterpret_cast<Atomic<mirror::Object*>*>(root);
1658 mirror::Object* expected_ref = ref;
1659 mirror::Object* new_ref = to_ref;
1660 do {
1661 if (expected_ref != addr->LoadRelaxed()) {
1662 // It was updated by the mutator.
1663 break;
1664 }
Hiroshi Yamauchifed3e2f2015-10-20 11:11:56 -07001665 } while (!addr->CompareExchangeWeakRelaxed(expected_ref, new_ref));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001666 }
1667}
1668
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001669inline void ConcurrentCopying::MarkRoot(mirror::CompressedReference<mirror::Object>* root) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001670 DCHECK(!root->IsNull());
1671 mirror::Object* const ref = root->AsMirrorPtr();
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001672 mirror::Object* to_ref = Mark(ref);
1673 if (to_ref != ref) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001674 auto* addr = reinterpret_cast<Atomic<mirror::CompressedReference<mirror::Object>>*>(root);
1675 auto expected_ref = mirror::CompressedReference<mirror::Object>::FromMirrorPtr(ref);
1676 auto new_ref = mirror::CompressedReference<mirror::Object>::FromMirrorPtr(to_ref);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001677 // If the cas fails, then it was updated by the mutator.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001678 do {
1679 if (ref != addr->LoadRelaxed().AsMirrorPtr()) {
1680 // It was updated by the mutator.
1681 break;
1682 }
Hiroshi Yamauchifed3e2f2015-10-20 11:11:56 -07001683 } while (!addr->CompareExchangeWeakRelaxed(expected_ref, new_ref));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001684 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001685}
1686
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001687inline void ConcurrentCopying::VisitRoots(
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001688 mirror::CompressedReference<mirror::Object>** roots, size_t count,
1689 const RootInfo& info ATTRIBUTE_UNUSED) {
1690 for (size_t i = 0; i < count; ++i) {
1691 mirror::CompressedReference<mirror::Object>* const root = roots[i];
1692 if (!root->IsNull()) {
1693 MarkRoot(root);
1694 }
1695 }
1696}
1697
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001698// Fill the given memory block with a dummy object. Used to fill in a
1699// copy of objects that was lost in race.
1700void ConcurrentCopying::FillWithDummyObject(mirror::Object* dummy_obj, size_t byte_size) {
Roland Levillain14d90572015-07-16 10:52:26 +01001701 CHECK_ALIGNED(byte_size, kObjectAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001702 memset(dummy_obj, 0, byte_size);
1703 mirror::Class* int_array_class = mirror::IntArray::GetArrayClass();
1704 CHECK(int_array_class != nullptr);
1705 AssertToSpaceInvariant(nullptr, MemberOffset(0), int_array_class);
1706 size_t component_size = int_array_class->GetComponentSize();
1707 CHECK_EQ(component_size, sizeof(int32_t));
1708 size_t data_offset = mirror::Array::DataOffset(component_size).SizeValue();
1709 if (data_offset > byte_size) {
1710 // An int array is too big. Use java.lang.Object.
1711 mirror::Class* java_lang_Object = WellKnownClasses::ToClass(WellKnownClasses::java_lang_Object);
1712 AssertToSpaceInvariant(nullptr, MemberOffset(0), java_lang_Object);
1713 CHECK_EQ(byte_size, java_lang_Object->GetObjectSize());
1714 dummy_obj->SetClass(java_lang_Object);
1715 CHECK_EQ(byte_size, dummy_obj->SizeOf());
1716 } else {
1717 // Use an int array.
1718 dummy_obj->SetClass(int_array_class);
1719 CHECK(dummy_obj->IsArrayInstance());
1720 int32_t length = (byte_size - data_offset) / component_size;
1721 dummy_obj->AsArray()->SetLength(length);
1722 CHECK_EQ(dummy_obj->AsArray()->GetLength(), length)
1723 << "byte_size=" << byte_size << " length=" << length
1724 << " component_size=" << component_size << " data_offset=" << data_offset;
1725 CHECK_EQ(byte_size, dummy_obj->SizeOf())
1726 << "byte_size=" << byte_size << " length=" << length
1727 << " component_size=" << component_size << " data_offset=" << data_offset;
1728 }
1729}
1730
1731// Reuse the memory blocks that were copy of objects that were lost in race.
1732mirror::Object* ConcurrentCopying::AllocateInSkippedBlock(size_t alloc_size) {
1733 // Try to reuse the blocks that were unused due to CAS failures.
Roland Levillain14d90572015-07-16 10:52:26 +01001734 CHECK_ALIGNED(alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001735 Thread* self = Thread::Current();
1736 size_t min_object_size = RoundUp(sizeof(mirror::Object), space::RegionSpace::kAlignment);
1737 MutexLock mu(self, skipped_blocks_lock_);
1738 auto it = skipped_blocks_map_.lower_bound(alloc_size);
1739 if (it == skipped_blocks_map_.end()) {
1740 // Not found.
1741 return nullptr;
1742 }
1743 {
1744 size_t byte_size = it->first;
1745 CHECK_GE(byte_size, alloc_size);
1746 if (byte_size > alloc_size && byte_size - alloc_size < min_object_size) {
1747 // If remainder would be too small for a dummy object, retry with a larger request size.
1748 it = skipped_blocks_map_.lower_bound(alloc_size + min_object_size);
1749 if (it == skipped_blocks_map_.end()) {
1750 // Not found.
1751 return nullptr;
1752 }
Roland Levillain14d90572015-07-16 10:52:26 +01001753 CHECK_ALIGNED(it->first - alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001754 CHECK_GE(it->first - alloc_size, min_object_size)
1755 << "byte_size=" << byte_size << " it->first=" << it->first << " alloc_size=" << alloc_size;
1756 }
1757 }
1758 // Found a block.
1759 CHECK(it != skipped_blocks_map_.end());
1760 size_t byte_size = it->first;
1761 uint8_t* addr = it->second;
1762 CHECK_GE(byte_size, alloc_size);
1763 CHECK(region_space_->IsInToSpace(reinterpret_cast<mirror::Object*>(addr)));
Roland Levillain14d90572015-07-16 10:52:26 +01001764 CHECK_ALIGNED(byte_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001765 if (kVerboseMode) {
1766 LOG(INFO) << "Reusing skipped bytes : " << reinterpret_cast<void*>(addr) << ", " << byte_size;
1767 }
1768 skipped_blocks_map_.erase(it);
1769 memset(addr, 0, byte_size);
1770 if (byte_size > alloc_size) {
1771 // Return the remainder to the map.
Roland Levillain14d90572015-07-16 10:52:26 +01001772 CHECK_ALIGNED(byte_size - alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001773 CHECK_GE(byte_size - alloc_size, min_object_size);
1774 FillWithDummyObject(reinterpret_cast<mirror::Object*>(addr + alloc_size),
1775 byte_size - alloc_size);
1776 CHECK(region_space_->IsInToSpace(reinterpret_cast<mirror::Object*>(addr + alloc_size)));
1777 skipped_blocks_map_.insert(std::make_pair(byte_size - alloc_size, addr + alloc_size));
1778 }
1779 return reinterpret_cast<mirror::Object*>(addr);
1780}
1781
1782mirror::Object* ConcurrentCopying::Copy(mirror::Object* from_ref) {
1783 DCHECK(region_space_->IsInFromSpace(from_ref));
1784 // No read barrier to avoid nested RB that might violate the to-space
1785 // invariant. Note that from_ref is a from space ref so the SizeOf()
1786 // call will access the from-space meta objects, but it's ok and necessary.
1787 size_t obj_size = from_ref->SizeOf<kDefaultVerifyFlags, kWithoutReadBarrier>();
1788 size_t region_space_alloc_size = RoundUp(obj_size, space::RegionSpace::kAlignment);
1789 size_t region_space_bytes_allocated = 0U;
1790 size_t non_moving_space_bytes_allocated = 0U;
1791 size_t bytes_allocated = 0U;
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001792 size_t dummy;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001793 mirror::Object* to_ref = region_space_->AllocNonvirtual<true>(
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001794 region_space_alloc_size, &region_space_bytes_allocated, nullptr, &dummy);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001795 bytes_allocated = region_space_bytes_allocated;
1796 if (to_ref != nullptr) {
1797 DCHECK_EQ(region_space_alloc_size, region_space_bytes_allocated);
1798 }
1799 bool fall_back_to_non_moving = false;
1800 if (UNLIKELY(to_ref == nullptr)) {
1801 // Failed to allocate in the region space. Try the skipped blocks.
1802 to_ref = AllocateInSkippedBlock(region_space_alloc_size);
1803 if (to_ref != nullptr) {
1804 // Succeeded to allocate in a skipped block.
1805 if (heap_->use_tlab_) {
1806 // This is necessary for the tlab case as it's not accounted in the space.
1807 region_space_->RecordAlloc(to_ref);
1808 }
1809 bytes_allocated = region_space_alloc_size;
1810 } else {
1811 // Fall back to the non-moving space.
1812 fall_back_to_non_moving = true;
1813 if (kVerboseMode) {
1814 LOG(INFO) << "Out of memory in the to-space. Fall back to non-moving. skipped_bytes="
1815 << to_space_bytes_skipped_.LoadSequentiallyConsistent()
1816 << " skipped_objects=" << to_space_objects_skipped_.LoadSequentiallyConsistent();
1817 }
1818 fall_back_to_non_moving = true;
1819 to_ref = heap_->non_moving_space_->Alloc(Thread::Current(), obj_size,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001820 &non_moving_space_bytes_allocated, nullptr, &dummy);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001821 CHECK(to_ref != nullptr) << "Fall-back non-moving space allocation failed";
1822 bytes_allocated = non_moving_space_bytes_allocated;
1823 // Mark it in the mark bitmap.
1824 accounting::ContinuousSpaceBitmap* mark_bitmap =
1825 heap_mark_bitmap_->GetContinuousSpaceBitmap(to_ref);
1826 CHECK(mark_bitmap != nullptr);
1827 CHECK(!mark_bitmap->AtomicTestAndSet(to_ref));
1828 }
1829 }
1830 DCHECK(to_ref != nullptr);
1831
1832 // Attempt to install the forward pointer. This is in a loop as the
1833 // lock word atomic write can fail.
1834 while (true) {
1835 // Copy the object. TODO: copy only the lockword in the second iteration and on?
1836 memcpy(to_ref, from_ref, obj_size);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001837
1838 LockWord old_lock_word = to_ref->GetLockWord(false);
1839
1840 if (old_lock_word.GetState() == LockWord::kForwardingAddress) {
1841 // Lost the race. Another thread (either GC or mutator) stored
1842 // the forwarding pointer first. Make the lost copy (to_ref)
1843 // look like a valid but dead (dummy) object and keep it for
1844 // future reuse.
1845 FillWithDummyObject(to_ref, bytes_allocated);
1846 if (!fall_back_to_non_moving) {
1847 DCHECK(region_space_->IsInToSpace(to_ref));
1848 if (bytes_allocated > space::RegionSpace::kRegionSize) {
1849 // Free the large alloc.
1850 region_space_->FreeLarge(to_ref, bytes_allocated);
1851 } else {
1852 // Record the lost copy for later reuse.
1853 heap_->num_bytes_allocated_.FetchAndAddSequentiallyConsistent(bytes_allocated);
1854 to_space_bytes_skipped_.FetchAndAddSequentiallyConsistent(bytes_allocated);
1855 to_space_objects_skipped_.FetchAndAddSequentiallyConsistent(1);
1856 MutexLock mu(Thread::Current(), skipped_blocks_lock_);
1857 skipped_blocks_map_.insert(std::make_pair(bytes_allocated,
1858 reinterpret_cast<uint8_t*>(to_ref)));
1859 }
1860 } else {
1861 DCHECK(heap_->non_moving_space_->HasAddress(to_ref));
1862 DCHECK_EQ(bytes_allocated, non_moving_space_bytes_allocated);
1863 // Free the non-moving-space chunk.
1864 accounting::ContinuousSpaceBitmap* mark_bitmap =
1865 heap_mark_bitmap_->GetContinuousSpaceBitmap(to_ref);
1866 CHECK(mark_bitmap != nullptr);
1867 CHECK(mark_bitmap->Clear(to_ref));
1868 heap_->non_moving_space_->Free(Thread::Current(), to_ref);
1869 }
1870
1871 // Get the winner's forward ptr.
1872 mirror::Object* lost_fwd_ptr = to_ref;
1873 to_ref = reinterpret_cast<mirror::Object*>(old_lock_word.ForwardingAddress());
1874 CHECK(to_ref != nullptr);
1875 CHECK_NE(to_ref, lost_fwd_ptr);
1876 CHECK(region_space_->IsInToSpace(to_ref) || heap_->non_moving_space_->HasAddress(to_ref));
1877 CHECK_NE(to_ref->GetLockWord(false).GetState(), LockWord::kForwardingAddress);
1878 return to_ref;
1879 }
1880
Hiroshi Yamauchi60f63f52015-04-23 16:12:40 -07001881 // Set the gray ptr.
1882 if (kUseBakerReadBarrier) {
1883 to_ref->SetReadBarrierPointer(ReadBarrier::GrayPtr());
1884 }
1885
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001886 LockWord new_lock_word = LockWord::FromForwardingAddress(reinterpret_cast<size_t>(to_ref));
1887
1888 // Try to atomically write the fwd ptr.
1889 bool success = from_ref->CasLockWordWeakSequentiallyConsistent(old_lock_word, new_lock_word);
1890 if (LIKELY(success)) {
1891 // The CAS succeeded.
1892 objects_moved_.FetchAndAddSequentiallyConsistent(1);
1893 bytes_moved_.FetchAndAddSequentiallyConsistent(region_space_alloc_size);
1894 if (LIKELY(!fall_back_to_non_moving)) {
1895 DCHECK(region_space_->IsInToSpace(to_ref));
1896 } else {
1897 DCHECK(heap_->non_moving_space_->HasAddress(to_ref));
1898 DCHECK_EQ(bytes_allocated, non_moving_space_bytes_allocated);
1899 }
1900 if (kUseBakerReadBarrier) {
1901 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr());
1902 }
1903 DCHECK(GetFwdPtr(from_ref) == to_ref);
1904 CHECK_NE(to_ref->GetLockWord(false).GetState(), LockWord::kForwardingAddress);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001905 PushOntoMarkStack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001906 return to_ref;
1907 } else {
1908 // The CAS failed. It may have lost the race or may have failed
1909 // due to monitor/hashcode ops. Either way, retry.
1910 }
1911 }
1912}
1913
1914mirror::Object* ConcurrentCopying::IsMarked(mirror::Object* from_ref) {
1915 DCHECK(from_ref != nullptr);
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08001916 space::RegionSpace::RegionType rtype = region_space_->GetRegionType(from_ref);
1917 if (rtype == space::RegionSpace::RegionType::kRegionTypeToSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001918 // It's already marked.
1919 return from_ref;
1920 }
1921 mirror::Object* to_ref;
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08001922 if (rtype == space::RegionSpace::RegionType::kRegionTypeFromSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001923 to_ref = GetFwdPtr(from_ref);
1924 DCHECK(to_ref == nullptr || region_space_->IsInToSpace(to_ref) ||
1925 heap_->non_moving_space_->HasAddress(to_ref))
1926 << "from_ref=" << from_ref << " to_ref=" << to_ref;
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08001927 } else if (rtype == space::RegionSpace::RegionType::kRegionTypeUnevacFromSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001928 if (region_space_bitmap_->Test(from_ref)) {
1929 to_ref = from_ref;
1930 } else {
1931 to_ref = nullptr;
1932 }
1933 } else {
1934 // from_ref is in a non-moving space.
1935 if (immune_region_.ContainsObject(from_ref)) {
1936 accounting::ContinuousSpaceBitmap* cc_bitmap =
1937 cc_heap_bitmap_->GetContinuousSpaceBitmap(from_ref);
1938 DCHECK(cc_bitmap != nullptr)
1939 << "An immune space object must have a bitmap";
1940 if (kIsDebugBuild) {
1941 DCHECK(heap_mark_bitmap_->GetContinuousSpaceBitmap(from_ref)->Test(from_ref))
1942 << "Immune space object must be already marked";
1943 }
1944 if (cc_bitmap->Test(from_ref)) {
1945 // Already marked.
1946 to_ref = from_ref;
1947 } else {
1948 // Newly marked.
1949 to_ref = nullptr;
1950 }
1951 } else {
1952 // Non-immune non-moving space. Use the mark bitmap.
1953 accounting::ContinuousSpaceBitmap* mark_bitmap =
1954 heap_mark_bitmap_->GetContinuousSpaceBitmap(from_ref);
1955 accounting::LargeObjectBitmap* los_bitmap =
1956 heap_mark_bitmap_->GetLargeObjectBitmap(from_ref);
1957 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
1958 bool is_los = mark_bitmap == nullptr;
1959 if (!is_los && mark_bitmap->Test(from_ref)) {
1960 // Already marked.
1961 to_ref = from_ref;
1962 } else if (is_los && los_bitmap->Test(from_ref)) {
1963 // Already marked in LOS.
1964 to_ref = from_ref;
1965 } else {
1966 // Not marked.
1967 if (IsOnAllocStack(from_ref)) {
1968 // If on the allocation stack, it's considered marked.
1969 to_ref = from_ref;
1970 } else {
1971 // Not marked.
1972 to_ref = nullptr;
1973 }
1974 }
1975 }
1976 }
1977 return to_ref;
1978}
1979
1980bool ConcurrentCopying::IsOnAllocStack(mirror::Object* ref) {
1981 QuasiAtomic::ThreadFenceAcquire();
1982 accounting::ObjectStack* alloc_stack = GetAllocationStack();
Mathieu Chartiercb535da2015-01-23 13:50:03 -08001983 return alloc_stack->Contains(ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001984}
1985
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001986mirror::Object* ConcurrentCopying::MarkNonMoving(mirror::Object* ref) {
1987 // ref is in a non-moving space (from_ref == to_ref).
1988 DCHECK(!region_space_->HasAddress(ref)) << ref;
1989 if (immune_region_.ContainsObject(ref)) {
1990 accounting::ContinuousSpaceBitmap* cc_bitmap =
1991 cc_heap_bitmap_->GetContinuousSpaceBitmap(ref);
1992 DCHECK(cc_bitmap != nullptr)
1993 << "An immune space object must have a bitmap";
1994 if (kIsDebugBuild) {
1995 DCHECK(heap_mark_bitmap_->GetContinuousSpaceBitmap(ref)->Test(ref))
1996 << "Immune space object must be already marked";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001997 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001998 // This may or may not succeed, which is ok.
1999 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002000 ref->AtomicSetReadBarrierPointer(ReadBarrier::WhitePtr(), ReadBarrier::GrayPtr());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002001 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002002 if (cc_bitmap->AtomicTestAndSet(ref)) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002003 // Already marked.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002004 } else {
2005 // Newly marked.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002006 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002007 DCHECK_EQ(ref->GetReadBarrierPointer(), ReadBarrier::GrayPtr());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002008 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002009 PushOntoMarkStack(ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002010 }
2011 } else {
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002012 // Use the mark bitmap.
2013 accounting::ContinuousSpaceBitmap* mark_bitmap =
2014 heap_mark_bitmap_->GetContinuousSpaceBitmap(ref);
2015 accounting::LargeObjectBitmap* los_bitmap =
2016 heap_mark_bitmap_->GetLargeObjectBitmap(ref);
2017 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
2018 bool is_los = mark_bitmap == nullptr;
2019 if (!is_los && mark_bitmap->Test(ref)) {
2020 // Already marked.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002021 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002022 DCHECK(ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr() ||
2023 ref->GetReadBarrierPointer() == ReadBarrier::BlackPtr());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002024 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002025 } else if (is_los && los_bitmap->Test(ref)) {
2026 // Already marked in LOS.
2027 if (kUseBakerReadBarrier) {
2028 DCHECK(ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr() ||
2029 ref->GetReadBarrierPointer() == ReadBarrier::BlackPtr());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002030 }
2031 } else {
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002032 // Not marked.
2033 if (IsOnAllocStack(ref)) {
2034 // If it's on the allocation stack, it's considered marked. Keep it white.
2035 // Objects on the allocation stack need not be marked.
2036 if (!is_los) {
2037 DCHECK(!mark_bitmap->Test(ref));
2038 } else {
2039 DCHECK(!los_bitmap->Test(ref));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002040 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002041 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002042 DCHECK_EQ(ref->GetReadBarrierPointer(), ReadBarrier::WhitePtr());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002043 }
2044 } else {
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002045 // Not marked or on the allocation stack. Try to mark it.
2046 // This may or may not succeed, which is ok.
2047 if (kUseBakerReadBarrier) {
2048 ref->AtomicSetReadBarrierPointer(ReadBarrier::WhitePtr(), ReadBarrier::GrayPtr());
2049 }
2050 if (!is_los && mark_bitmap->AtomicTestAndSet(ref)) {
2051 // Already marked.
2052 } else if (is_los && los_bitmap->AtomicTestAndSet(ref)) {
2053 // Already marked in LOS.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002054 } else {
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002055 // Newly marked.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002056 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002057 DCHECK_EQ(ref->GetReadBarrierPointer(), ReadBarrier::GrayPtr());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002058 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002059 PushOntoMarkStack(ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002060 }
2061 }
2062 }
2063 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002064 return ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002065}
2066
2067void ConcurrentCopying::FinishPhase() {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002068 {
2069 MutexLock mu(Thread::Current(), mark_stack_lock_);
2070 CHECK_EQ(pooled_mark_stacks_.size(), kMarkStackPoolSize);
2071 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002072 region_space_ = nullptr;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002073 {
2074 MutexLock mu(Thread::Current(), skipped_blocks_lock_);
2075 skipped_blocks_map_.clear();
2076 }
2077 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
2078 heap_->ClearMarkedObjects();
2079}
2080
Mathieu Chartier97509952015-07-13 14:35:43 -07002081bool ConcurrentCopying::IsMarkedHeapReference(mirror::HeapReference<mirror::Object>* field) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002082 mirror::Object* from_ref = field->AsMirrorPtr();
Mathieu Chartier97509952015-07-13 14:35:43 -07002083 mirror::Object* to_ref = IsMarked(from_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002084 if (to_ref == nullptr) {
2085 return false;
2086 }
2087 if (from_ref != to_ref) {
2088 QuasiAtomic::ThreadFenceRelease();
2089 field->Assign(to_ref);
2090 QuasiAtomic::ThreadFenceSequentiallyConsistent();
2091 }
2092 return true;
2093}
2094
Mathieu Chartier97509952015-07-13 14:35:43 -07002095mirror::Object* ConcurrentCopying::MarkObject(mirror::Object* from_ref) {
2096 return Mark(from_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002097}
2098
2099void ConcurrentCopying::DelayReferenceReferent(mirror::Class* klass, mirror::Reference* reference) {
Mathieu Chartier97509952015-07-13 14:35:43 -07002100 heap_->GetReferenceProcessor()->DelayReferenceReferent(klass, reference, this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002101}
2102
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002103void ConcurrentCopying::ProcessReferences(Thread* self) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002104 TimingLogger::ScopedTiming split("ProcessReferences", GetTimings());
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002105 // 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 -08002106 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
2107 GetHeap()->GetReferenceProcessor()->ProcessReferences(
Mathieu Chartier97509952015-07-13 14:35:43 -07002108 true /*concurrent*/, GetTimings(), GetCurrentIteration()->GetClearSoftReferences(), this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002109}
2110
2111void ConcurrentCopying::RevokeAllThreadLocalBuffers() {
2112 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
2113 region_space_->RevokeAllThreadLocalBuffers();
2114}
2115
Hiroshi Yamauchid5307ec2014-03-27 21:07:51 -07002116} // namespace collector
2117} // namespace gc
2118} // namespace art