blob: 6984c1624fb83465a0343f91a2245dd399426282 [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 Yamauchi2cd334a2015-01-09 14:03:35 -080020#include "gc/accounting/heap_bitmap-inl.h"
21#include "gc/accounting/space_bitmap-inl.h"
22#include "gc/space/image_space.h"
23#include "gc/space/space.h"
24#include "intern_table.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070025#include "mirror/class-inl.h"
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080026#include "mirror/object-inl.h"
27#include "scoped_thread_state_change.h"
28#include "thread-inl.h"
29#include "thread_list.h"
30#include "well_known_classes.h"
31
Hiroshi Yamauchid5307ec2014-03-27 21:07:51 -070032namespace art {
33namespace gc {
34namespace collector {
35
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080036ConcurrentCopying::ConcurrentCopying(Heap* heap, const std::string& name_prefix)
37 : GarbageCollector(heap,
38 name_prefix + (name_prefix.empty() ? "" : " ") +
39 "concurrent copying + mark sweep"),
40 region_space_(nullptr), gc_barrier_(new Barrier(0)), mark_queue_(2 * MB),
41 is_marking_(false), is_active_(false), is_asserting_to_space_invariant_(false),
42 heap_mark_bitmap_(nullptr), live_stack_freeze_size_(0),
43 skipped_blocks_lock_("concurrent copying bytes blocks lock", kMarkSweepMarkStackLock),
44 rb_table_(heap_->GetReadBarrierTable()),
45 force_evacuate_all_(false) {
46 static_assert(space::RegionSpace::kRegionSize == accounting::ReadBarrierTable::kRegionSize,
47 "The region space size and the read barrier table region size must match");
48 cc_heap_bitmap_.reset(new accounting::HeapBitmap(heap));
49 {
50 Thread* self = Thread::Current();
51 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
52 // Cache this so that we won't have to lock heap_bitmap_lock_ in
53 // Mark() which could cause a nested lock on heap_bitmap_lock_
54 // when GC causes a RB while doing GC or a lock order violation
55 // (class_linker_lock_ and heap_bitmap_lock_).
56 heap_mark_bitmap_ = heap->GetMarkBitmap();
57 }
58}
59
60ConcurrentCopying::~ConcurrentCopying() {
61}
62
63void ConcurrentCopying::RunPhases() {
64 CHECK(kUseBakerReadBarrier || kUseTableLookupReadBarrier);
65 CHECK(!is_active_);
66 is_active_ = true;
67 Thread* self = Thread::Current();
68 Locks::mutator_lock_->AssertNotHeld(self);
69 {
70 ReaderMutexLock mu(self, *Locks::mutator_lock_);
71 InitializePhase();
72 }
73 FlipThreadRoots();
74 {
75 ReaderMutexLock mu(self, *Locks::mutator_lock_);
76 MarkingPhase();
77 }
78 // Verify no from space refs. This causes a pause.
79 if (kEnableNoFromSpaceRefsVerification || kIsDebugBuild) {
80 TimingLogger::ScopedTiming split("(Paused)VerifyNoFromSpaceReferences", GetTimings());
81 ScopedPause pause(this);
82 CheckEmptyMarkQueue();
83 if (kVerboseMode) {
84 LOG(INFO) << "Verifying no from-space refs";
85 }
86 VerifyNoFromSpaceReferences();
Mathieu Chartier720e71a2015-04-06 17:10:58 -070087 if (kVerboseMode) {
88 LOG(INFO) << "Done verifying no from-space refs";
89 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080090 CheckEmptyMarkQueue();
91 }
92 {
93 ReaderMutexLock mu(self, *Locks::mutator_lock_);
94 ReclaimPhase();
95 }
96 FinishPhase();
97 CHECK(is_active_);
98 is_active_ = false;
99}
100
101void ConcurrentCopying::BindBitmaps() {
102 Thread* self = Thread::Current();
103 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
104 // Mark all of the spaces we never collect as immune.
105 for (const auto& space : heap_->GetContinuousSpaces()) {
106 if (space->GetGcRetentionPolicy() == space::kGcRetentionPolicyNeverCollect
107 || space->GetGcRetentionPolicy() == space::kGcRetentionPolicyFullCollect) {
108 CHECK(space->IsZygoteSpace() || space->IsImageSpace());
109 CHECK(immune_region_.AddContinuousSpace(space)) << "Failed to add space " << *space;
110 const char* bitmap_name = space->IsImageSpace() ? "cc image space bitmap" :
111 "cc zygote space bitmap";
112 // TODO: try avoiding using bitmaps for image/zygote to save space.
113 accounting::ContinuousSpaceBitmap* bitmap =
114 accounting::ContinuousSpaceBitmap::Create(bitmap_name, space->Begin(), space->Capacity());
115 cc_heap_bitmap_->AddContinuousSpaceBitmap(bitmap);
116 cc_bitmaps_.push_back(bitmap);
117 } else if (space == region_space_) {
118 accounting::ContinuousSpaceBitmap* bitmap =
119 accounting::ContinuousSpaceBitmap::Create("cc region space bitmap",
120 space->Begin(), space->Capacity());
121 cc_heap_bitmap_->AddContinuousSpaceBitmap(bitmap);
122 cc_bitmaps_.push_back(bitmap);
123 region_space_bitmap_ = bitmap;
124 }
125 }
126}
127
128void ConcurrentCopying::InitializePhase() {
129 TimingLogger::ScopedTiming split("InitializePhase", GetTimings());
130 if (kVerboseMode) {
131 LOG(INFO) << "GC InitializePhase";
132 LOG(INFO) << "Region-space : " << reinterpret_cast<void*>(region_space_->Begin()) << "-"
133 << reinterpret_cast<void*>(region_space_->Limit());
134 }
135 CHECK(mark_queue_.IsEmpty());
136 immune_region_.Reset();
137 bytes_moved_.StoreRelaxed(0);
138 objects_moved_.StoreRelaxed(0);
139 if (GetCurrentIteration()->GetGcCause() == kGcCauseExplicit ||
140 GetCurrentIteration()->GetGcCause() == kGcCauseForNativeAlloc ||
141 GetCurrentIteration()->GetClearSoftReferences()) {
142 force_evacuate_all_ = true;
143 } else {
144 force_evacuate_all_ = false;
145 }
146 BindBitmaps();
147 if (kVerboseMode) {
148 LOG(INFO) << "force_evacuate_all=" << force_evacuate_all_;
149 LOG(INFO) << "Immune region: " << immune_region_.Begin() << "-" << immune_region_.End();
150 LOG(INFO) << "GC end of InitializePhase";
151 }
152}
153
154// Used to switch the thread roots of a thread from from-space refs to to-space refs.
155class ThreadFlipVisitor : public Closure {
156 public:
157 explicit ThreadFlipVisitor(ConcurrentCopying* concurrent_copying, bool use_tlab)
158 : concurrent_copying_(concurrent_copying), use_tlab_(use_tlab) {
159 }
160
161 virtual void Run(Thread* thread) OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
162 // Note: self is not necessarily equal to thread since thread may be suspended.
163 Thread* self = Thread::Current();
164 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
165 << thread->GetState() << " thread " << thread << " self " << self;
166 if (use_tlab_ && thread->HasTlab()) {
167 if (ConcurrentCopying::kEnableFromSpaceAccountingCheck) {
168 // This must come before the revoke.
169 size_t thread_local_objects = thread->GetThreadLocalObjectsAllocated();
170 concurrent_copying_->region_space_->RevokeThreadLocalBuffers(thread);
171 reinterpret_cast<Atomic<size_t>*>(&concurrent_copying_->from_space_num_objects_at_first_pause_)->
172 FetchAndAddSequentiallyConsistent(thread_local_objects);
173 } else {
174 concurrent_copying_->region_space_->RevokeThreadLocalBuffers(thread);
175 }
176 }
177 if (kUseThreadLocalAllocationStack) {
178 thread->RevokeThreadLocalAllocationStack();
179 }
180 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700181 thread->VisitRoots(concurrent_copying_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800182 concurrent_copying_->GetBarrier().Pass(self);
183 }
184
185 private:
186 ConcurrentCopying* const concurrent_copying_;
187 const bool use_tlab_;
188};
189
190// Called back from Runtime::FlipThreadRoots() during a pause.
191class FlipCallback : public Closure {
192 public:
193 explicit FlipCallback(ConcurrentCopying* concurrent_copying)
194 : concurrent_copying_(concurrent_copying) {
195 }
196
197 virtual void Run(Thread* thread) OVERRIDE EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_) {
198 ConcurrentCopying* cc = concurrent_copying_;
199 TimingLogger::ScopedTiming split("(Paused)FlipCallback", cc->GetTimings());
200 // Note: self is not necessarily equal to thread since thread may be suspended.
201 Thread* self = Thread::Current();
202 CHECK(thread == self);
203 Locks::mutator_lock_->AssertExclusiveHeld(self);
204 cc->region_space_->SetFromSpace(cc->rb_table_, cc->force_evacuate_all_);
205 cc->SwapStacks(self);
206 if (ConcurrentCopying::kEnableFromSpaceAccountingCheck) {
207 cc->RecordLiveStackFreezeSize(self);
208 cc->from_space_num_objects_at_first_pause_ = cc->region_space_->GetObjectsAllocated();
209 cc->from_space_num_bytes_at_first_pause_ = cc->region_space_->GetBytesAllocated();
210 }
211 cc->is_marking_ = true;
212 if (UNLIKELY(Runtime::Current()->IsActiveTransaction())) {
Mathieu Chartier184c9dc2015-03-05 13:20:54 -0800213 CHECK(Runtime::Current()->IsAotCompiler());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800214 TimingLogger::ScopedTiming split2("(Paused)VisitTransactionRoots", cc->GetTimings());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700215 Runtime::Current()->VisitTransactionRoots(cc);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800216 }
217 }
218
219 private:
220 ConcurrentCopying* const concurrent_copying_;
221};
222
223// Switch threads that from from-space to to-space refs. Forward/mark the thread roots.
224void ConcurrentCopying::FlipThreadRoots() {
225 TimingLogger::ScopedTiming split("FlipThreadRoots", GetTimings());
226 if (kVerboseMode) {
227 LOG(INFO) << "time=" << region_space_->Time();
228 region_space_->DumpNonFreeRegions(LOG(INFO));
229 }
230 Thread* self = Thread::Current();
231 Locks::mutator_lock_->AssertNotHeld(self);
232 gc_barrier_->Init(self, 0);
233 ThreadFlipVisitor thread_flip_visitor(this, heap_->use_tlab_);
234 FlipCallback flip_callback(this);
235 size_t barrier_count = Runtime::Current()->FlipThreadRoots(
236 &thread_flip_visitor, &flip_callback, this);
237 {
238 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
239 gc_barrier_->Increment(self, barrier_count);
240 }
241 is_asserting_to_space_invariant_ = true;
242 QuasiAtomic::ThreadFenceForConstructor();
243 if (kVerboseMode) {
244 LOG(INFO) << "time=" << region_space_->Time();
245 region_space_->DumpNonFreeRegions(LOG(INFO));
246 LOG(INFO) << "GC end of FlipThreadRoots";
247 }
248}
249
250void ConcurrentCopying::SwapStacks(Thread* self) {
251 heap_->SwapStacks(self);
252}
253
254void ConcurrentCopying::RecordLiveStackFreezeSize(Thread* self) {
255 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
256 live_stack_freeze_size_ = heap_->GetLiveStack()->Size();
257}
258
259// Used to visit objects in the immune spaces.
260class ConcurrentCopyingImmuneSpaceObjVisitor {
261 public:
262 explicit ConcurrentCopyingImmuneSpaceObjVisitor(ConcurrentCopying* cc)
263 : collector_(cc) {}
264
265 void operator()(mirror::Object* obj) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
266 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
267 DCHECK(obj != nullptr);
268 DCHECK(collector_->immune_region_.ContainsObject(obj));
269 accounting::ContinuousSpaceBitmap* cc_bitmap =
270 collector_->cc_heap_bitmap_->GetContinuousSpaceBitmap(obj);
271 DCHECK(cc_bitmap != nullptr)
272 << "An immune space object must have a bitmap";
273 if (kIsDebugBuild) {
274 DCHECK(collector_->heap_->GetMarkBitmap()->Test(obj))
275 << "Immune space object must be already marked";
276 }
277 // This may or may not succeed, which is ok.
278 if (kUseBakerReadBarrier) {
279 obj->AtomicSetReadBarrierPointer(ReadBarrier::WhitePtr(), ReadBarrier::GrayPtr());
280 }
281 if (cc_bitmap->AtomicTestAndSet(obj)) {
282 // Already marked. Do nothing.
283 } else {
284 // Newly marked. Set the gray bit and push it onto the mark stack.
285 CHECK(!kUseBakerReadBarrier || obj->GetReadBarrierPointer() == ReadBarrier::GrayPtr());
286 collector_->PushOntoMarkStack<true>(obj);
287 }
288 }
289
290 private:
291 ConcurrentCopying* collector_;
292};
293
294class EmptyCheckpoint : public Closure {
295 public:
296 explicit EmptyCheckpoint(ConcurrentCopying* concurrent_copying)
297 : concurrent_copying_(concurrent_copying) {
298 }
299
300 virtual void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
301 // Note: self is not necessarily equal to thread since thread may be suspended.
302 Thread* self = Thread::Current();
303 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
304 << thread->GetState() << " thread " << thread << " self " << self;
Lei Lidd9943d2015-02-02 14:24:44 +0800305 // If thread is a running mutator, then act on behalf of the garbage collector.
306 // See the code in ThreadList::RunCheckpoint.
307 if (thread->GetState() == kRunnable) {
308 concurrent_copying_->GetBarrier().Pass(self);
309 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800310 }
311
312 private:
313 ConcurrentCopying* const concurrent_copying_;
314};
315
316// Concurrently mark roots that are guarded by read barriers and process the mark stack.
317void ConcurrentCopying::MarkingPhase() {
318 TimingLogger::ScopedTiming split("MarkingPhase", GetTimings());
319 if (kVerboseMode) {
320 LOG(INFO) << "GC MarkingPhase";
321 }
322 {
323 // Mark the image root. The WB-based collectors do not need to
324 // scan the image objects from roots by relying on the card table,
325 // but it's necessary for the RB to-space invariant to hold.
326 TimingLogger::ScopedTiming split1("VisitImageRoots", GetTimings());
327 gc::space::ImageSpace* image = heap_->GetImageSpace();
328 if (image != nullptr) {
329 mirror::ObjectArray<mirror::Object>* image_root = image->GetImageHeader().GetImageRoots();
330 mirror::Object* marked_image_root = Mark(image_root);
331 CHECK_EQ(image_root, marked_image_root) << "An image object does not move";
332 if (ReadBarrier::kEnableToSpaceInvariantChecks) {
333 AssertToSpaceInvariant(nullptr, MemberOffset(0), marked_image_root);
334 }
335 }
336 }
337 {
338 TimingLogger::ScopedTiming split2("VisitConstantRoots", GetTimings());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700339 Runtime::Current()->VisitConstantRoots(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800340 }
341 {
342 TimingLogger::ScopedTiming split3("VisitInternTableRoots", GetTimings());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700343 Runtime::Current()->GetInternTable()->VisitRoots(this, kVisitRootFlagAllRoots);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800344 }
345 {
346 TimingLogger::ScopedTiming split4("VisitClassLinkerRoots", GetTimings());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700347 Runtime::Current()->GetClassLinker()->VisitRoots(this, kVisitRootFlagAllRoots);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800348 }
349 {
350 // TODO: don't visit the transaction roots if it's not active.
351 TimingLogger::ScopedTiming split5("VisitNonThreadRoots", GetTimings());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700352 Runtime::Current()->VisitNonThreadRoots(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800353 }
354
355 // Immune spaces.
356 for (auto& space : heap_->GetContinuousSpaces()) {
357 if (immune_region_.ContainsSpace(space)) {
358 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
359 accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
360 ConcurrentCopyingImmuneSpaceObjVisitor visitor(this);
361 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()),
362 reinterpret_cast<uintptr_t>(space->Limit()),
363 visitor);
364 }
365 }
366
367 Thread* self = Thread::Current();
368 {
369 TimingLogger::ScopedTiming split6("ProcessMarkStack", GetTimings());
370 // Process the mark stack and issue an empty check point. If the
371 // mark stack is still empty after the check point, we're
372 // done. Otherwise, repeat.
373 ProcessMarkStack();
374 size_t count = 0;
375 while (!ProcessMarkStack()) {
376 ++count;
377 if (kVerboseMode) {
378 LOG(INFO) << "Issue an empty check point. " << count;
379 }
380 IssueEmptyCheckpoint();
381 }
382 // Need to ensure the mark stack is empty before reference
383 // processing to get rid of non-reference gray objects.
384 CheckEmptyMarkQueue();
385 // Enable the GetReference slow path and disallow access to the system weaks.
386 GetHeap()->GetReferenceProcessor()->EnableSlowPath();
387 Runtime::Current()->DisallowNewSystemWeaks();
388 QuasiAtomic::ThreadFenceForConstructor();
389 // Lock-unlock the system weak locks so that there's no thread in
390 // the middle of accessing system weaks.
391 Runtime::Current()->EnsureNewSystemWeaksDisallowed();
392 // Note: Do not issue a checkpoint from here to the
393 // SweepSystemWeaks call or else a deadlock due to
394 // WaitHoldingLocks() would occur.
395 if (kVerboseMode) {
396 LOG(INFO) << "Enabled the ref proc slow path & disabled access to system weaks.";
397 LOG(INFO) << "ProcessReferences";
398 }
399 ProcessReferences(self, true);
400 CheckEmptyMarkQueue();
401 if (kVerboseMode) {
402 LOG(INFO) << "SweepSystemWeaks";
403 }
404 SweepSystemWeaks(self);
405 if (kVerboseMode) {
406 LOG(INFO) << "SweepSystemWeaks done";
407 }
408 // Because hash_set::Erase() can call the hash function for
409 // arbitrary elements in the weak intern table in
410 // InternTable::Table::SweepWeaks(), the above SweepSystemWeaks()
411 // call may have marked some objects (strings) alive. So process
412 // the mark stack here once again.
413 ProcessMarkStack();
414 CheckEmptyMarkQueue();
415 // Disable marking.
416 if (kUseTableLookupReadBarrier) {
417 heap_->rb_table_->ClearAll();
418 DCHECK(heap_->rb_table_->IsAllCleared());
419 }
420 is_mark_queue_push_disallowed_.StoreSequentiallyConsistent(1);
421 is_marking_ = false;
422 if (kVerboseMode) {
423 LOG(INFO) << "AllowNewSystemWeaks";
424 }
425 Runtime::Current()->AllowNewSystemWeaks();
426 CheckEmptyMarkQueue();
427 }
428
429 if (kVerboseMode) {
430 LOG(INFO) << "GC end of MarkingPhase";
431 }
432}
433
434void ConcurrentCopying::IssueEmptyCheckpoint() {
435 Thread* self = Thread::Current();
436 EmptyCheckpoint check_point(this);
437 ThreadList* thread_list = Runtime::Current()->GetThreadList();
438 gc_barrier_->Init(self, 0);
439 size_t barrier_count = thread_list->RunCheckpoint(&check_point);
Lei Lidd9943d2015-02-02 14:24:44 +0800440 // If there are no threads to wait which implys that all the checkpoint functions are finished,
441 // then no need to release the mutator lock.
442 if (barrier_count == 0) {
443 return;
444 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800445 // Release locks then wait for all mutator threads to pass the barrier.
446 Locks::mutator_lock_->SharedUnlock(self);
447 {
448 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
449 gc_barrier_->Increment(self, barrier_count);
450 }
451 Locks::mutator_lock_->SharedLock(self);
452}
453
454mirror::Object* ConcurrentCopying::PopOffMarkStack() {
455 return mark_queue_.Dequeue();
456}
457
458template<bool kThreadSafe>
459void ConcurrentCopying::PushOntoMarkStack(mirror::Object* to_ref) {
460 CHECK_EQ(is_mark_queue_push_disallowed_.LoadRelaxed(), 0)
461 << " " << to_ref << " " << PrettyTypeOf(to_ref);
462 if (kThreadSafe) {
463 CHECK(mark_queue_.Enqueue(to_ref)) << "Mark queue overflow";
464 } else {
465 CHECK(mark_queue_.EnqueueThreadUnsafe(to_ref)) << "Mark queue overflow";
466 }
467}
468
469accounting::ObjectStack* ConcurrentCopying::GetAllocationStack() {
470 return heap_->allocation_stack_.get();
471}
472
473accounting::ObjectStack* ConcurrentCopying::GetLiveStack() {
474 return heap_->live_stack_.get();
475}
476
477inline mirror::Object* ConcurrentCopying::GetFwdPtr(mirror::Object* from_ref) {
478 DCHECK(region_space_->IsInFromSpace(from_ref));
479 LockWord lw = from_ref->GetLockWord(false);
480 if (lw.GetState() == LockWord::kForwardingAddress) {
481 mirror::Object* fwd_ptr = reinterpret_cast<mirror::Object*>(lw.ForwardingAddress());
482 CHECK(fwd_ptr != nullptr);
483 return fwd_ptr;
484 } else {
485 return nullptr;
486 }
487}
488
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800489// The following visitors are that used to verify that there's no
490// references to the from-space left after marking.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700491class ConcurrentCopyingVerifyNoFromSpaceRefsVisitor : public SingleRootVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800492 public:
493 explicit ConcurrentCopyingVerifyNoFromSpaceRefsVisitor(ConcurrentCopying* collector)
494 : collector_(collector) {}
495
496 void operator()(mirror::Object* ref) const
497 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) ALWAYS_INLINE {
498 if (ref == nullptr) {
499 // OK.
500 return;
501 }
502 collector_->AssertToSpaceInvariant(nullptr, MemberOffset(0), ref);
503 if (kUseBakerReadBarrier) {
504 if (collector_->RegionSpace()->IsInToSpace(ref)) {
505 CHECK(ref->GetReadBarrierPointer() == nullptr)
506 << "To-space ref " << ref << " " << PrettyTypeOf(ref)
507 << " has non-white rb_ptr " << ref->GetReadBarrierPointer();
508 } else {
509 CHECK(ref->GetReadBarrierPointer() == ReadBarrier::BlackPtr() ||
510 (ref->GetReadBarrierPointer() == ReadBarrier::WhitePtr() &&
511 collector_->IsOnAllocStack(ref)))
512 << "Non-moving/unevac from space ref " << ref << " " << PrettyTypeOf(ref)
513 << " has non-black rb_ptr " << ref->GetReadBarrierPointer()
514 << " but isn't on the alloc stack (and has white rb_ptr)."
515 << " Is it in the non-moving space="
516 << (collector_->GetHeap()->GetNonMovingSpace()->HasAddress(ref));
517 }
518 }
519 }
520
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700521 void VisitRoot(mirror::Object* root, const RootInfo& info ATTRIBUTE_UNUSED)
522 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800523 DCHECK(root != nullptr);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700524 operator()(root);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800525 }
526
527 private:
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700528 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800529};
530
531class ConcurrentCopyingVerifyNoFromSpaceRefsFieldVisitor {
532 public:
533 explicit ConcurrentCopyingVerifyNoFromSpaceRefsFieldVisitor(ConcurrentCopying* collector)
534 : collector_(collector) {}
535
536 void operator()(mirror::Object* obj, MemberOffset offset, bool /* is_static */) const
537 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) ALWAYS_INLINE {
538 mirror::Object* ref =
539 obj->GetFieldObject<mirror::Object, kDefaultVerifyFlags, kWithoutReadBarrier>(offset);
540 ConcurrentCopyingVerifyNoFromSpaceRefsVisitor visitor(collector_);
541 visitor(ref);
542 }
543 void operator()(mirror::Class* klass, mirror::Reference* ref) const
544 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) ALWAYS_INLINE {
545 CHECK(klass->IsTypeOfReferenceClass());
546 this->operator()(ref, mirror::Reference::ReferentOffset(), false);
547 }
548
549 private:
550 ConcurrentCopying* collector_;
551};
552
553class ConcurrentCopyingVerifyNoFromSpaceRefsObjectVisitor {
554 public:
555 explicit ConcurrentCopyingVerifyNoFromSpaceRefsObjectVisitor(ConcurrentCopying* collector)
556 : collector_(collector) {}
557 void operator()(mirror::Object* obj) const
558 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
559 ObjectCallback(obj, collector_);
560 }
561 static void ObjectCallback(mirror::Object* obj, void *arg)
562 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
563 CHECK(obj != nullptr);
564 ConcurrentCopying* collector = reinterpret_cast<ConcurrentCopying*>(arg);
565 space::RegionSpace* region_space = collector->RegionSpace();
566 CHECK(!region_space->IsInFromSpace(obj)) << "Scanning object " << obj << " in from space";
567 ConcurrentCopyingVerifyNoFromSpaceRefsFieldVisitor visitor(collector);
568 obj->VisitReferences<true>(visitor, visitor);
569 if (kUseBakerReadBarrier) {
570 if (collector->RegionSpace()->IsInToSpace(obj)) {
571 CHECK(obj->GetReadBarrierPointer() == nullptr)
572 << "obj=" << obj << " non-white rb_ptr " << obj->GetReadBarrierPointer();
573 } else {
574 CHECK(obj->GetReadBarrierPointer() == ReadBarrier::BlackPtr() ||
575 (obj->GetReadBarrierPointer() == ReadBarrier::WhitePtr() &&
576 collector->IsOnAllocStack(obj)))
577 << "Non-moving space/unevac from space ref " << obj << " " << PrettyTypeOf(obj)
578 << " has non-black rb_ptr " << obj->GetReadBarrierPointer()
579 << " but isn't on the alloc stack (and has white rb_ptr). Is it in the non-moving space="
580 << (collector->GetHeap()->GetNonMovingSpace()->HasAddress(obj));
581 }
582 }
583 }
584
585 private:
586 ConcurrentCopying* const collector_;
587};
588
589// Verify there's no from-space references left after the marking phase.
590void ConcurrentCopying::VerifyNoFromSpaceReferences() {
591 Thread* self = Thread::Current();
592 DCHECK(Locks::mutator_lock_->IsExclusiveHeld(self));
593 ConcurrentCopyingVerifyNoFromSpaceRefsObjectVisitor visitor(this);
594 // Roots.
595 {
596 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700597 ConcurrentCopyingVerifyNoFromSpaceRefsVisitor ref_visitor(this);
598 Runtime::Current()->VisitRoots(&ref_visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800599 }
600 // The to-space.
601 region_space_->WalkToSpace(ConcurrentCopyingVerifyNoFromSpaceRefsObjectVisitor::ObjectCallback,
602 this);
603 // Non-moving spaces.
604 {
605 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
606 heap_->GetMarkBitmap()->Visit(visitor);
607 }
608 // The alloc stack.
609 {
610 ConcurrentCopyingVerifyNoFromSpaceRefsVisitor ref_visitor(this);
Mathieu Chartiercb535da2015-01-23 13:50:03 -0800611 for (auto* it = heap_->allocation_stack_->Begin(), *end = heap_->allocation_stack_->End();
612 it < end; ++it) {
613 mirror::Object* const obj = it->AsMirrorPtr();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800614 if (obj != nullptr && obj->GetClass() != nullptr) {
615 // TODO: need to call this only if obj is alive?
616 ref_visitor(obj);
617 visitor(obj);
618 }
619 }
620 }
621 // TODO: LOS. But only refs in LOS are classes.
622}
623
624// The following visitors are used to assert the to-space invariant.
625class ConcurrentCopyingAssertToSpaceInvariantRefsVisitor {
626 public:
627 explicit ConcurrentCopyingAssertToSpaceInvariantRefsVisitor(ConcurrentCopying* collector)
628 : collector_(collector) {}
629
630 void operator()(mirror::Object* ref) const
631 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) ALWAYS_INLINE {
632 if (ref == nullptr) {
633 // OK.
634 return;
635 }
636 collector_->AssertToSpaceInvariant(nullptr, MemberOffset(0), ref);
637 }
638 static void RootCallback(mirror::Object** root, void *arg, const RootInfo& /*root_info*/)
639 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
640 ConcurrentCopying* collector = reinterpret_cast<ConcurrentCopying*>(arg);
641 ConcurrentCopyingAssertToSpaceInvariantRefsVisitor visitor(collector);
642 DCHECK(root != nullptr);
643 visitor(*root);
644 }
645
646 private:
647 ConcurrentCopying* collector_;
648};
649
650class ConcurrentCopyingAssertToSpaceInvariantFieldVisitor {
651 public:
652 explicit ConcurrentCopyingAssertToSpaceInvariantFieldVisitor(ConcurrentCopying* collector)
653 : collector_(collector) {}
654
655 void operator()(mirror::Object* obj, MemberOffset offset, bool /* is_static */) const
656 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) ALWAYS_INLINE {
657 mirror::Object* ref =
658 obj->GetFieldObject<mirror::Object, kDefaultVerifyFlags, kWithoutReadBarrier>(offset);
659 ConcurrentCopyingAssertToSpaceInvariantRefsVisitor visitor(collector_);
660 visitor(ref);
661 }
662 void operator()(mirror::Class* klass, mirror::Reference* /* ref */) const
663 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) ALWAYS_INLINE {
664 CHECK(klass->IsTypeOfReferenceClass());
665 }
666
667 private:
668 ConcurrentCopying* collector_;
669};
670
671class ConcurrentCopyingAssertToSpaceInvariantObjectVisitor {
672 public:
673 explicit ConcurrentCopyingAssertToSpaceInvariantObjectVisitor(ConcurrentCopying* collector)
674 : collector_(collector) {}
675 void operator()(mirror::Object* obj) const
676 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
677 ObjectCallback(obj, collector_);
678 }
679 static void ObjectCallback(mirror::Object* obj, void *arg)
680 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
681 CHECK(obj != nullptr);
682 ConcurrentCopying* collector = reinterpret_cast<ConcurrentCopying*>(arg);
683 space::RegionSpace* region_space = collector->RegionSpace();
684 CHECK(!region_space->IsInFromSpace(obj)) << "Scanning object " << obj << " in from space";
685 collector->AssertToSpaceInvariant(nullptr, MemberOffset(0), obj);
686 ConcurrentCopyingAssertToSpaceInvariantFieldVisitor visitor(collector);
687 obj->VisitReferences<true>(visitor, visitor);
688 }
689
690 private:
691 ConcurrentCopying* collector_;
692};
693
694bool ConcurrentCopying::ProcessMarkStack() {
695 if (kVerboseMode) {
696 LOG(INFO) << "ProcessMarkStack. ";
697 }
698 size_t count = 0;
699 mirror::Object* to_ref;
700 while ((to_ref = PopOffMarkStack()) != nullptr) {
701 ++count;
702 DCHECK(!region_space_->IsInFromSpace(to_ref));
703 if (kUseBakerReadBarrier) {
704 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr())
705 << " " << to_ref << " " << to_ref->GetReadBarrierPointer()
706 << " is_marked=" << IsMarked(to_ref);
707 }
708 // Scan ref fields.
709 Scan(to_ref);
710 // Mark the gray ref as white or black.
711 if (kUseBakerReadBarrier) {
712 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr())
713 << " " << to_ref << " " << to_ref->GetReadBarrierPointer()
714 << " is_marked=" << IsMarked(to_ref);
715 }
716 if (to_ref->GetClass<kVerifyNone, kWithoutReadBarrier>()->IsTypeOfReferenceClass() &&
717 to_ref->AsReference()->GetReferent<kWithoutReadBarrier>() != nullptr &&
718 !IsInToSpace(to_ref->AsReference()->GetReferent<kWithoutReadBarrier>())) {
719 // Leave References gray so that GetReferent() will trigger RB.
720 CHECK(to_ref->AsReference()->IsEnqueued()) << "Left unenqueued ref gray " << to_ref;
721 } else {
Hiroshi Yamauchi60f63f52015-04-23 16:12:40 -0700722#ifdef USE_BAKER_OR_BROOKS_READ_BARRIER
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800723 if (kUseBakerReadBarrier) {
724 if (region_space_->IsInToSpace(to_ref)) {
725 // If to-space, change from gray to white.
726 bool success = to_ref->AtomicSetReadBarrierPointer(ReadBarrier::GrayPtr(),
727 ReadBarrier::WhitePtr());
728 CHECK(success) << "Must succeed as we won the race.";
729 CHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::WhitePtr());
730 } else {
731 // If non-moving space/unevac from space, change from gray
732 // to black. We can't change gray to white because it's not
733 // safe to use CAS if two threads change values in opposite
734 // directions (A->B and B->A). So, we change it to black to
735 // indicate non-moving objects that have been marked
736 // through. Note we'd need to change from black to white
737 // later (concurrently).
738 bool success = to_ref->AtomicSetReadBarrierPointer(ReadBarrier::GrayPtr(),
739 ReadBarrier::BlackPtr());
740 CHECK(success) << "Must succeed as we won the race.";
741 CHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::BlackPtr());
742 }
743 }
Hiroshi Yamauchi60f63f52015-04-23 16:12:40 -0700744#else
745 DCHECK(!kUseBakerReadBarrier);
746#endif
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800747 }
748 if (ReadBarrier::kEnableToSpaceInvariantChecks || kIsDebugBuild) {
749 ConcurrentCopyingAssertToSpaceInvariantObjectVisitor visitor(this);
750 visitor(to_ref);
751 }
752 }
753 // Return true if the stack was empty.
754 return count == 0;
755}
756
757void ConcurrentCopying::CheckEmptyMarkQueue() {
758 if (!mark_queue_.IsEmpty()) {
759 while (!mark_queue_.IsEmpty()) {
760 mirror::Object* obj = mark_queue_.Dequeue();
761 if (kUseBakerReadBarrier) {
762 mirror::Object* rb_ptr = obj->GetReadBarrierPointer();
763 LOG(INFO) << "On mark queue : " << obj << " " << PrettyTypeOf(obj) << " rb_ptr=" << rb_ptr
764 << " is_marked=" << IsMarked(obj);
765 } else {
766 LOG(INFO) << "On mark queue : " << obj << " " << PrettyTypeOf(obj)
767 << " is_marked=" << IsMarked(obj);
768 }
769 }
770 LOG(FATAL) << "mark queue is not empty";
771 }
772}
773
774void ConcurrentCopying::SweepSystemWeaks(Thread* self) {
775 TimingLogger::ScopedTiming split("SweepSystemWeaks", GetTimings());
776 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
777 Runtime::Current()->SweepSystemWeaks(IsMarkedCallback, this);
778}
779
780void ConcurrentCopying::Sweep(bool swap_bitmaps) {
781 {
782 TimingLogger::ScopedTiming t("MarkStackAsLive", GetTimings());
783 accounting::ObjectStack* live_stack = heap_->GetLiveStack();
784 if (kEnableFromSpaceAccountingCheck) {
785 CHECK_GE(live_stack_freeze_size_, live_stack->Size());
786 }
787 heap_->MarkAllocStackAsLive(live_stack);
788 live_stack->Reset();
789 }
790 CHECK(mark_queue_.IsEmpty());
791 TimingLogger::ScopedTiming split("Sweep", GetTimings());
792 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
793 if (space->IsContinuousMemMapAllocSpace()) {
794 space::ContinuousMemMapAllocSpace* alloc_space = space->AsContinuousMemMapAllocSpace();
795 if (space == region_space_ || immune_region_.ContainsSpace(space)) {
796 continue;
797 }
798 TimingLogger::ScopedTiming split2(
799 alloc_space->IsZygoteSpace() ? "SweepZygoteSpace" : "SweepAllocSpace", GetTimings());
800 RecordFree(alloc_space->Sweep(swap_bitmaps));
801 }
802 }
803 SweepLargeObjects(swap_bitmaps);
804}
805
806void ConcurrentCopying::SweepLargeObjects(bool swap_bitmaps) {
807 TimingLogger::ScopedTiming split("SweepLargeObjects", GetTimings());
808 RecordFreeLOS(heap_->GetLargeObjectsSpace()->Sweep(swap_bitmaps));
809}
810
811class ConcurrentCopyingClearBlackPtrsVisitor {
812 public:
813 explicit ConcurrentCopyingClearBlackPtrsVisitor(ConcurrentCopying* cc)
814 : collector_(cc) {}
Andreas Gampe65b798e2015-04-06 09:35:22 -0700815#ifndef USE_BAKER_OR_BROOKS_READ_BARRIER
816 NO_RETURN
817#endif
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800818 void operator()(mirror::Object* obj) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
819 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
820 DCHECK(obj != nullptr);
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -0800821 DCHECK(collector_->heap_->GetMarkBitmap()->Test(obj)) << obj;
822 DCHECK_EQ(obj->GetReadBarrierPointer(), ReadBarrier::BlackPtr()) << obj;
Hiroshi Yamauchi60f63f52015-04-23 16:12:40 -0700823 obj->AtomicSetReadBarrierPointer(ReadBarrier::BlackPtr(), ReadBarrier::WhitePtr());
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -0800824 DCHECK_EQ(obj->GetReadBarrierPointer(), ReadBarrier::WhitePtr()) << obj;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800825 }
826
827 private:
828 ConcurrentCopying* const collector_;
829};
830
831// Clear the black ptrs in non-moving objects back to white.
832void ConcurrentCopying::ClearBlackPtrs() {
833 CHECK(kUseBakerReadBarrier);
834 TimingLogger::ScopedTiming split("ClearBlackPtrs", GetTimings());
835 ConcurrentCopyingClearBlackPtrsVisitor visitor(this);
836 for (auto& space : heap_->GetContinuousSpaces()) {
837 if (space == region_space_) {
838 continue;
839 }
840 accounting::ContinuousSpaceBitmap* mark_bitmap = space->GetMarkBitmap();
841 if (kVerboseMode) {
842 LOG(INFO) << "ClearBlackPtrs: " << *space << " bitmap: " << *mark_bitmap;
843 }
844 mark_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()),
845 reinterpret_cast<uintptr_t>(space->Limit()),
846 visitor);
847 }
848 space::LargeObjectSpace* large_object_space = heap_->GetLargeObjectsSpace();
849 large_object_space->GetMarkBitmap()->VisitMarkedRange(
850 reinterpret_cast<uintptr_t>(large_object_space->Begin()),
851 reinterpret_cast<uintptr_t>(large_object_space->End()),
852 visitor);
853 // Objects on the allocation stack?
854 if (ReadBarrier::kEnableReadBarrierInvariantChecks || kIsDebugBuild) {
855 size_t count = GetAllocationStack()->Size();
Mathieu Chartiercb535da2015-01-23 13:50:03 -0800856 auto* it = GetAllocationStack()->Begin();
857 auto* end = GetAllocationStack()->End();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800858 for (size_t i = 0; i < count; ++i, ++it) {
Mathieu Chartiercb535da2015-01-23 13:50:03 -0800859 CHECK_LT(it, end);
860 mirror::Object* obj = it->AsMirrorPtr();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800861 if (obj != nullptr) {
862 // Must have been cleared above.
Mathieu Chartiercb535da2015-01-23 13:50:03 -0800863 CHECK_EQ(obj->GetReadBarrierPointer(), ReadBarrier::WhitePtr()) << obj;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800864 }
865 }
866 }
867}
868
869void ConcurrentCopying::ReclaimPhase() {
870 TimingLogger::ScopedTiming split("ReclaimPhase", GetTimings());
871 if (kVerboseMode) {
872 LOG(INFO) << "GC ReclaimPhase";
873 }
874 Thread* self = Thread::Current();
875
876 {
877 // Double-check that the mark stack is empty.
878 // Note: need to set this after VerifyNoFromSpaceRef().
879 is_asserting_to_space_invariant_ = false;
880 QuasiAtomic::ThreadFenceForConstructor();
881 if (kVerboseMode) {
882 LOG(INFO) << "Issue an empty check point. ";
883 }
884 IssueEmptyCheckpoint();
885 // Disable the check.
886 is_mark_queue_push_disallowed_.StoreSequentiallyConsistent(0);
887 CheckEmptyMarkQueue();
888 }
889
890 {
891 // Record freed objects.
892 TimingLogger::ScopedTiming split2("RecordFree", GetTimings());
893 // Don't include thread-locals that are in the to-space.
894 uint64_t from_bytes = region_space_->GetBytesAllocatedInFromSpace();
895 uint64_t from_objects = region_space_->GetObjectsAllocatedInFromSpace();
896 uint64_t unevac_from_bytes = region_space_->GetBytesAllocatedInUnevacFromSpace();
897 uint64_t unevac_from_objects = region_space_->GetObjectsAllocatedInUnevacFromSpace();
898 uint64_t to_bytes = bytes_moved_.LoadSequentiallyConsistent();
899 uint64_t to_objects = objects_moved_.LoadSequentiallyConsistent();
900 if (kEnableFromSpaceAccountingCheck) {
901 CHECK_EQ(from_space_num_objects_at_first_pause_, from_objects + unevac_from_objects);
902 CHECK_EQ(from_space_num_bytes_at_first_pause_, from_bytes + unevac_from_bytes);
903 }
904 CHECK_LE(to_objects, from_objects);
905 CHECK_LE(to_bytes, from_bytes);
906 int64_t freed_bytes = from_bytes - to_bytes;
907 int64_t freed_objects = from_objects - to_objects;
908 if (kVerboseMode) {
909 LOG(INFO) << "RecordFree:"
910 << " from_bytes=" << from_bytes << " from_objects=" << from_objects
911 << " unevac_from_bytes=" << unevac_from_bytes << " unevac_from_objects=" << unevac_from_objects
912 << " to_bytes=" << to_bytes << " to_objects=" << to_objects
913 << " freed_bytes=" << freed_bytes << " freed_objects=" << freed_objects
914 << " from_space size=" << region_space_->FromSpaceSize()
915 << " unevac_from_space size=" << region_space_->UnevacFromSpaceSize()
916 << " to_space size=" << region_space_->ToSpaceSize();
917 LOG(INFO) << "(before) num_bytes_allocated=" << heap_->num_bytes_allocated_.LoadSequentiallyConsistent();
918 }
919 RecordFree(ObjectBytePair(freed_objects, freed_bytes));
920 if (kVerboseMode) {
921 LOG(INFO) << "(after) num_bytes_allocated=" << heap_->num_bytes_allocated_.LoadSequentiallyConsistent();
922 }
923 }
924
925 {
926 TimingLogger::ScopedTiming split3("ComputeUnevacFromSpaceLiveRatio", GetTimings());
927 ComputeUnevacFromSpaceLiveRatio();
928 }
929
930 {
931 TimingLogger::ScopedTiming split4("ClearFromSpace", GetTimings());
932 region_space_->ClearFromSpace();
933 }
934
935 {
936 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
937 if (kUseBakerReadBarrier) {
938 ClearBlackPtrs();
939 }
940 Sweep(false);
941 SwapBitmaps();
942 heap_->UnBindBitmaps();
943
944 // Remove bitmaps for the immune spaces.
945 while (!cc_bitmaps_.empty()) {
946 accounting::ContinuousSpaceBitmap* cc_bitmap = cc_bitmaps_.back();
947 cc_heap_bitmap_->RemoveContinuousSpaceBitmap(cc_bitmap);
948 delete cc_bitmap;
949 cc_bitmaps_.pop_back();
950 }
951 region_space_bitmap_ = nullptr;
952 }
953
954 if (kVerboseMode) {
955 LOG(INFO) << "GC end of ReclaimPhase";
956 }
957}
958
959class ConcurrentCopyingComputeUnevacFromSpaceLiveRatioVisitor {
960 public:
961 explicit ConcurrentCopyingComputeUnevacFromSpaceLiveRatioVisitor(ConcurrentCopying* cc)
962 : collector_(cc) {}
963 void operator()(mirror::Object* ref) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
964 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
965 DCHECK(ref != nullptr);
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -0800966 DCHECK(collector_->region_space_bitmap_->Test(ref)) << ref;
967 DCHECK(collector_->region_space_->IsInUnevacFromSpace(ref)) << ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800968 if (kUseBakerReadBarrier) {
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -0800969 DCHECK_EQ(ref->GetReadBarrierPointer(), ReadBarrier::BlackPtr()) << ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800970 // Clear the black ptr.
Hiroshi Yamauchi60f63f52015-04-23 16:12:40 -0700971 ref->AtomicSetReadBarrierPointer(ReadBarrier::BlackPtr(), ReadBarrier::WhitePtr());
972 DCHECK_EQ(ref->GetReadBarrierPointer(), ReadBarrier::WhitePtr()) << ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800973 }
974 size_t obj_size = ref->SizeOf();
975 size_t alloc_size = RoundUp(obj_size, space::RegionSpace::kAlignment);
976 collector_->region_space_->AddLiveBytes(ref, alloc_size);
977 }
978
979 private:
980 ConcurrentCopying* collector_;
981};
982
983// Compute how much live objects are left in regions.
984void ConcurrentCopying::ComputeUnevacFromSpaceLiveRatio() {
985 region_space_->AssertAllRegionLiveBytesZeroOrCleared();
986 ConcurrentCopyingComputeUnevacFromSpaceLiveRatioVisitor visitor(this);
987 region_space_bitmap_->VisitMarkedRange(reinterpret_cast<uintptr_t>(region_space_->Begin()),
988 reinterpret_cast<uintptr_t>(region_space_->Limit()),
989 visitor);
990}
991
992// Assert the to-space invariant.
993void ConcurrentCopying::AssertToSpaceInvariant(mirror::Object* obj, MemberOffset offset,
994 mirror::Object* ref) {
995 CHECK(heap_->collector_type_ == kCollectorTypeCC) << static_cast<size_t>(heap_->collector_type_);
996 if (is_asserting_to_space_invariant_) {
997 if (region_space_->IsInToSpace(ref)) {
998 // OK.
999 return;
1000 } else if (region_space_->IsInUnevacFromSpace(ref)) {
1001 CHECK(region_space_bitmap_->Test(ref)) << ref;
1002 } else if (region_space_->IsInFromSpace(ref)) {
1003 // Not OK. Do extra logging.
1004 if (obj != nullptr) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001005 LogFromSpaceRefHolder(obj, offset);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001006 }
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001007 ref->GetLockWord(false).Dump(LOG(INTERNAL_FATAL));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001008 CHECK(false) << "Found from-space ref " << ref << " " << PrettyTypeOf(ref);
1009 } else {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001010 AssertToSpaceInvariantInNonMovingSpace(obj, ref);
1011 }
1012 }
1013}
1014
1015class RootPrinter {
1016 public:
1017 RootPrinter() { }
1018
1019 template <class MirrorType>
1020 ALWAYS_INLINE void VisitRootIfNonNull(mirror::CompressedReference<MirrorType>* root)
1021 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1022 if (!root->IsNull()) {
1023 VisitRoot(root);
1024 }
1025 }
1026
1027 template <class MirrorType>
1028 void VisitRoot(mirror::Object** root)
1029 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1030 LOG(INTERNAL_FATAL) << "root=" << root << " ref=" << *root;
1031 }
1032
1033 template <class MirrorType>
1034 void VisitRoot(mirror::CompressedReference<MirrorType>* root)
1035 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1036 LOG(INTERNAL_FATAL) << "root=" << root << " ref=" << root->AsMirrorPtr();
1037 }
1038};
1039
1040void ConcurrentCopying::AssertToSpaceInvariant(GcRootSource* gc_root_source,
1041 mirror::Object* ref) {
1042 CHECK(heap_->collector_type_ == kCollectorTypeCC) << static_cast<size_t>(heap_->collector_type_);
1043 if (is_asserting_to_space_invariant_) {
1044 if (region_space_->IsInToSpace(ref)) {
1045 // OK.
1046 return;
1047 } else if (region_space_->IsInUnevacFromSpace(ref)) {
1048 CHECK(region_space_bitmap_->Test(ref)) << ref;
1049 } else if (region_space_->IsInFromSpace(ref)) {
1050 // Not OK. Do extra logging.
1051 if (gc_root_source == nullptr) {
1052 // No info.
1053 } else if (gc_root_source->HasArtField()) {
1054 ArtField* field = gc_root_source->GetArtField();
1055 LOG(INTERNAL_FATAL) << "gc root in field " << field << " " << PrettyField(field);
1056 RootPrinter root_printer;
1057 field->VisitRoots(root_printer);
1058 } else if (gc_root_source->HasArtMethod()) {
1059 ArtMethod* method = gc_root_source->GetArtMethod();
1060 LOG(INTERNAL_FATAL) << "gc root in method " << method << " " << PrettyMethod(method);
1061 RootPrinter root_printer;
1062 method->VisitRoots(root_printer);
1063 }
1064 ref->GetLockWord(false).Dump(LOG(INTERNAL_FATAL));
1065 region_space_->DumpNonFreeRegions(LOG(INTERNAL_FATAL));
1066 PrintFileToLog("/proc/self/maps", LogSeverity::INTERNAL_FATAL);
1067 MemMap::DumpMaps(LOG(INTERNAL_FATAL), true);
1068 CHECK(false) << "Found from-space ref " << ref << " " << PrettyTypeOf(ref);
1069 } else {
1070 AssertToSpaceInvariantInNonMovingSpace(nullptr, ref);
1071 }
1072 }
1073}
1074
1075void ConcurrentCopying::LogFromSpaceRefHolder(mirror::Object* obj, MemberOffset offset) {
1076 if (kUseBakerReadBarrier) {
1077 LOG(INFO) << "holder=" << obj << " " << PrettyTypeOf(obj)
1078 << " holder rb_ptr=" << obj->GetReadBarrierPointer();
1079 } else {
1080 LOG(INFO) << "holder=" << obj << " " << PrettyTypeOf(obj);
1081 }
1082 if (region_space_->IsInFromSpace(obj)) {
1083 LOG(INFO) << "holder is in the from-space.";
1084 } else if (region_space_->IsInToSpace(obj)) {
1085 LOG(INFO) << "holder is in the to-space.";
1086 } else if (region_space_->IsInUnevacFromSpace(obj)) {
1087 LOG(INFO) << "holder is in the unevac from-space.";
1088 if (region_space_bitmap_->Test(obj)) {
1089 LOG(INFO) << "holder is marked in the region space bitmap.";
1090 } else {
1091 LOG(INFO) << "holder is not marked in the region space bitmap.";
1092 }
1093 } else {
1094 // In a non-moving space.
1095 if (immune_region_.ContainsObject(obj)) {
1096 LOG(INFO) << "holder is in the image or the zygote space.";
1097 accounting::ContinuousSpaceBitmap* cc_bitmap =
1098 cc_heap_bitmap_->GetContinuousSpaceBitmap(obj);
1099 CHECK(cc_bitmap != nullptr)
1100 << "An immune space object must have a bitmap.";
1101 if (cc_bitmap->Test(obj)) {
1102 LOG(INFO) << "holder is marked in the bit map.";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001103 } else {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001104 LOG(INFO) << "holder is NOT marked in the bit map.";
1105 }
1106 } else {
1107 LOG(INFO) << "holder is in a non-moving (or main) space.";
1108 accounting::ContinuousSpaceBitmap* mark_bitmap =
1109 heap_mark_bitmap_->GetContinuousSpaceBitmap(obj);
1110 accounting::LargeObjectBitmap* los_bitmap =
1111 heap_mark_bitmap_->GetLargeObjectBitmap(obj);
1112 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
1113 bool is_los = mark_bitmap == nullptr;
1114 if (!is_los && mark_bitmap->Test(obj)) {
1115 LOG(INFO) << "holder is marked in the mark bit map.";
1116 } else if (is_los && los_bitmap->Test(obj)) {
1117 LOG(INFO) << "holder is marked in the los bit map.";
1118 } else {
1119 // If ref is on the allocation stack, then it is considered
1120 // mark/alive (but not necessarily on the live stack.)
1121 if (IsOnAllocStack(obj)) {
1122 LOG(INFO) << "holder is on the alloc stack.";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001123 } else {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001124 LOG(INFO) << "holder is not marked or on the alloc stack.";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001125 }
1126 }
1127 }
1128 }
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001129 LOG(INFO) << "offset=" << offset.SizeValue();
1130}
1131
1132void ConcurrentCopying::AssertToSpaceInvariantInNonMovingSpace(mirror::Object* obj,
1133 mirror::Object* ref) {
1134 // In a non-moving spaces. Check that the ref is marked.
1135 if (immune_region_.ContainsObject(ref)) {
1136 accounting::ContinuousSpaceBitmap* cc_bitmap =
1137 cc_heap_bitmap_->GetContinuousSpaceBitmap(ref);
1138 CHECK(cc_bitmap != nullptr)
1139 << "An immune space ref must have a bitmap. " << ref;
1140 if (kUseBakerReadBarrier) {
1141 CHECK(cc_bitmap->Test(ref))
1142 << "Unmarked immune space ref. obj=" << obj << " rb_ptr="
1143 << obj->GetReadBarrierPointer() << " ref=" << ref;
1144 } else {
1145 CHECK(cc_bitmap->Test(ref))
1146 << "Unmarked immune space ref. obj=" << obj << " ref=" << ref;
1147 }
1148 } else {
1149 accounting::ContinuousSpaceBitmap* mark_bitmap =
1150 heap_mark_bitmap_->GetContinuousSpaceBitmap(ref);
1151 accounting::LargeObjectBitmap* los_bitmap =
1152 heap_mark_bitmap_->GetLargeObjectBitmap(ref);
1153 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
1154 bool is_los = mark_bitmap == nullptr;
1155 if ((!is_los && mark_bitmap->Test(ref)) ||
1156 (is_los && los_bitmap->Test(ref))) {
1157 // OK.
1158 } else {
1159 // If ref is on the allocation stack, then it may not be
1160 // marked live, but considered marked/alive (but not
1161 // necessarily on the live stack).
1162 CHECK(IsOnAllocStack(ref)) << "Unmarked ref that's not on the allocation stack. "
1163 << "obj=" << obj << " ref=" << ref;
1164 }
1165 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001166}
1167
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001168// Used to scan ref fields of an object.
1169class ConcurrentCopyingRefFieldsVisitor {
1170 public:
1171 explicit ConcurrentCopyingRefFieldsVisitor(ConcurrentCopying* collector)
1172 : collector_(collector) {}
1173
1174 void operator()(mirror::Object* obj, MemberOffset offset, bool /* is_static */)
1175 const ALWAYS_INLINE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1176 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
1177 collector_->Process(obj, offset);
1178 }
1179
1180 void operator()(mirror::Class* klass, mirror::Reference* ref) const
1181 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) ALWAYS_INLINE {
1182 CHECK(klass->IsTypeOfReferenceClass());
1183 collector_->DelayReferenceReferent(klass, ref);
1184 }
1185
1186 private:
1187 ConcurrentCopying* const collector_;
1188};
1189
1190// Scan ref fields of an object.
1191void ConcurrentCopying::Scan(mirror::Object* to_ref) {
1192 DCHECK(!region_space_->IsInFromSpace(to_ref));
1193 ConcurrentCopyingRefFieldsVisitor visitor(this);
1194 to_ref->VisitReferences<true>(visitor, visitor);
1195}
1196
1197// Process a field.
1198inline void ConcurrentCopying::Process(mirror::Object* obj, MemberOffset offset) {
1199 mirror::Object* ref = obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier, false>(offset);
1200 if (ref == nullptr || region_space_->IsInToSpace(ref)) {
1201 return;
1202 }
1203 mirror::Object* to_ref = Mark(ref);
1204 if (to_ref == ref) {
1205 return;
1206 }
1207 // This may fail if the mutator writes to the field at the same time. But it's ok.
1208 mirror::Object* expected_ref = ref;
1209 mirror::Object* new_ref = to_ref;
1210 do {
1211 if (expected_ref !=
1212 obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier, false>(offset)) {
1213 // It was updated by the mutator.
1214 break;
1215 }
1216 } while (!obj->CasFieldWeakSequentiallyConsistentObjectWithoutWriteBarrier<false, false, kVerifyNone>(
1217 offset, expected_ref, new_ref));
1218}
1219
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001220// Process some roots.
1221void ConcurrentCopying::VisitRoots(
1222 mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED) {
1223 for (size_t i = 0; i < count; ++i) {
1224 mirror::Object** root = roots[i];
1225 mirror::Object* ref = *root;
1226 if (ref == nullptr || region_space_->IsInToSpace(ref)) {
Mathieu Chartier4809d0a2015-04-07 10:39:04 -07001227 continue;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001228 }
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001229 mirror::Object* to_ref = Mark(ref);
1230 if (to_ref == ref) {
Mathieu Chartier4809d0a2015-04-07 10:39:04 -07001231 continue;
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001232 }
1233 Atomic<mirror::Object*>* addr = reinterpret_cast<Atomic<mirror::Object*>*>(root);
1234 mirror::Object* expected_ref = ref;
1235 mirror::Object* new_ref = to_ref;
1236 do {
1237 if (expected_ref != addr->LoadRelaxed()) {
1238 // It was updated by the mutator.
1239 break;
1240 }
1241 } while (!addr->CompareExchangeWeakSequentiallyConsistent(expected_ref, new_ref));
1242 }
1243}
1244
1245void ConcurrentCopying::VisitRoots(
1246 mirror::CompressedReference<mirror::Object>** roots, size_t count,
1247 const RootInfo& info ATTRIBUTE_UNUSED) {
1248 for (size_t i = 0; i < count; ++i) {
1249 mirror::CompressedReference<mirror::Object>* root = roots[i];
1250 mirror::Object* ref = root->AsMirrorPtr();
1251 if (ref == nullptr || region_space_->IsInToSpace(ref)) {
Mathieu Chartier4809d0a2015-04-07 10:39:04 -07001252 continue;
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001253 }
1254 mirror::Object* to_ref = Mark(ref);
1255 if (to_ref == ref) {
Mathieu Chartier4809d0a2015-04-07 10:39:04 -07001256 continue;
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001257 }
1258 auto* addr = reinterpret_cast<Atomic<mirror::CompressedReference<mirror::Object>>*>(root);
1259 auto expected_ref = mirror::CompressedReference<mirror::Object>::FromMirrorPtr(ref);
1260 auto new_ref = mirror::CompressedReference<mirror::Object>::FromMirrorPtr(to_ref);
1261 do {
1262 if (ref != addr->LoadRelaxed().AsMirrorPtr()) {
1263 // It was updated by the mutator.
1264 break;
1265 }
1266 } while (!addr->CompareExchangeWeakSequentiallyConsistent(expected_ref, new_ref));
1267 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001268}
1269
1270// Fill the given memory block with a dummy object. Used to fill in a
1271// copy of objects that was lost in race.
1272void ConcurrentCopying::FillWithDummyObject(mirror::Object* dummy_obj, size_t byte_size) {
1273 CHECK(IsAligned<kObjectAlignment>(byte_size));
1274 memset(dummy_obj, 0, byte_size);
1275 mirror::Class* int_array_class = mirror::IntArray::GetArrayClass();
1276 CHECK(int_array_class != nullptr);
1277 AssertToSpaceInvariant(nullptr, MemberOffset(0), int_array_class);
1278 size_t component_size = int_array_class->GetComponentSize();
1279 CHECK_EQ(component_size, sizeof(int32_t));
1280 size_t data_offset = mirror::Array::DataOffset(component_size).SizeValue();
1281 if (data_offset > byte_size) {
1282 // An int array is too big. Use java.lang.Object.
1283 mirror::Class* java_lang_Object = WellKnownClasses::ToClass(WellKnownClasses::java_lang_Object);
1284 AssertToSpaceInvariant(nullptr, MemberOffset(0), java_lang_Object);
1285 CHECK_EQ(byte_size, java_lang_Object->GetObjectSize());
1286 dummy_obj->SetClass(java_lang_Object);
1287 CHECK_EQ(byte_size, dummy_obj->SizeOf());
1288 } else {
1289 // Use an int array.
1290 dummy_obj->SetClass(int_array_class);
1291 CHECK(dummy_obj->IsArrayInstance());
1292 int32_t length = (byte_size - data_offset) / component_size;
1293 dummy_obj->AsArray()->SetLength(length);
1294 CHECK_EQ(dummy_obj->AsArray()->GetLength(), length)
1295 << "byte_size=" << byte_size << " length=" << length
1296 << " component_size=" << component_size << " data_offset=" << data_offset;
1297 CHECK_EQ(byte_size, dummy_obj->SizeOf())
1298 << "byte_size=" << byte_size << " length=" << length
1299 << " component_size=" << component_size << " data_offset=" << data_offset;
1300 }
1301}
1302
1303// Reuse the memory blocks that were copy of objects that were lost in race.
1304mirror::Object* ConcurrentCopying::AllocateInSkippedBlock(size_t alloc_size) {
1305 // Try to reuse the blocks that were unused due to CAS failures.
1306 CHECK(IsAligned<space::RegionSpace::kAlignment>(alloc_size));
1307 Thread* self = Thread::Current();
1308 size_t min_object_size = RoundUp(sizeof(mirror::Object), space::RegionSpace::kAlignment);
1309 MutexLock mu(self, skipped_blocks_lock_);
1310 auto it = skipped_blocks_map_.lower_bound(alloc_size);
1311 if (it == skipped_blocks_map_.end()) {
1312 // Not found.
1313 return nullptr;
1314 }
1315 {
1316 size_t byte_size = it->first;
1317 CHECK_GE(byte_size, alloc_size);
1318 if (byte_size > alloc_size && byte_size - alloc_size < min_object_size) {
1319 // If remainder would be too small for a dummy object, retry with a larger request size.
1320 it = skipped_blocks_map_.lower_bound(alloc_size + min_object_size);
1321 if (it == skipped_blocks_map_.end()) {
1322 // Not found.
1323 return nullptr;
1324 }
1325 CHECK(IsAligned<space::RegionSpace::kAlignment>(it->first - alloc_size));
1326 CHECK_GE(it->first - alloc_size, min_object_size)
1327 << "byte_size=" << byte_size << " it->first=" << it->first << " alloc_size=" << alloc_size;
1328 }
1329 }
1330 // Found a block.
1331 CHECK(it != skipped_blocks_map_.end());
1332 size_t byte_size = it->first;
1333 uint8_t* addr = it->second;
1334 CHECK_GE(byte_size, alloc_size);
1335 CHECK(region_space_->IsInToSpace(reinterpret_cast<mirror::Object*>(addr)));
1336 CHECK(IsAligned<space::RegionSpace::kAlignment>(byte_size));
1337 if (kVerboseMode) {
1338 LOG(INFO) << "Reusing skipped bytes : " << reinterpret_cast<void*>(addr) << ", " << byte_size;
1339 }
1340 skipped_blocks_map_.erase(it);
1341 memset(addr, 0, byte_size);
1342 if (byte_size > alloc_size) {
1343 // Return the remainder to the map.
1344 CHECK(IsAligned<space::RegionSpace::kAlignment>(byte_size - alloc_size));
1345 CHECK_GE(byte_size - alloc_size, min_object_size);
1346 FillWithDummyObject(reinterpret_cast<mirror::Object*>(addr + alloc_size),
1347 byte_size - alloc_size);
1348 CHECK(region_space_->IsInToSpace(reinterpret_cast<mirror::Object*>(addr + alloc_size)));
1349 skipped_blocks_map_.insert(std::make_pair(byte_size - alloc_size, addr + alloc_size));
1350 }
1351 return reinterpret_cast<mirror::Object*>(addr);
1352}
1353
1354mirror::Object* ConcurrentCopying::Copy(mirror::Object* from_ref) {
1355 DCHECK(region_space_->IsInFromSpace(from_ref));
1356 // No read barrier to avoid nested RB that might violate the to-space
1357 // invariant. Note that from_ref is a from space ref so the SizeOf()
1358 // call will access the from-space meta objects, but it's ok and necessary.
1359 size_t obj_size = from_ref->SizeOf<kDefaultVerifyFlags, kWithoutReadBarrier>();
1360 size_t region_space_alloc_size = RoundUp(obj_size, space::RegionSpace::kAlignment);
1361 size_t region_space_bytes_allocated = 0U;
1362 size_t non_moving_space_bytes_allocated = 0U;
1363 size_t bytes_allocated = 0U;
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001364 size_t dummy;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001365 mirror::Object* to_ref = region_space_->AllocNonvirtual<true>(
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001366 region_space_alloc_size, &region_space_bytes_allocated, nullptr, &dummy);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001367 bytes_allocated = region_space_bytes_allocated;
1368 if (to_ref != nullptr) {
1369 DCHECK_EQ(region_space_alloc_size, region_space_bytes_allocated);
1370 }
1371 bool fall_back_to_non_moving = false;
1372 if (UNLIKELY(to_ref == nullptr)) {
1373 // Failed to allocate in the region space. Try the skipped blocks.
1374 to_ref = AllocateInSkippedBlock(region_space_alloc_size);
1375 if (to_ref != nullptr) {
1376 // Succeeded to allocate in a skipped block.
1377 if (heap_->use_tlab_) {
1378 // This is necessary for the tlab case as it's not accounted in the space.
1379 region_space_->RecordAlloc(to_ref);
1380 }
1381 bytes_allocated = region_space_alloc_size;
1382 } else {
1383 // Fall back to the non-moving space.
1384 fall_back_to_non_moving = true;
1385 if (kVerboseMode) {
1386 LOG(INFO) << "Out of memory in the to-space. Fall back to non-moving. skipped_bytes="
1387 << to_space_bytes_skipped_.LoadSequentiallyConsistent()
1388 << " skipped_objects=" << to_space_objects_skipped_.LoadSequentiallyConsistent();
1389 }
1390 fall_back_to_non_moving = true;
1391 to_ref = heap_->non_moving_space_->Alloc(Thread::Current(), obj_size,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001392 &non_moving_space_bytes_allocated, nullptr, &dummy);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001393 CHECK(to_ref != nullptr) << "Fall-back non-moving space allocation failed";
1394 bytes_allocated = non_moving_space_bytes_allocated;
1395 // Mark it in the mark bitmap.
1396 accounting::ContinuousSpaceBitmap* mark_bitmap =
1397 heap_mark_bitmap_->GetContinuousSpaceBitmap(to_ref);
1398 CHECK(mark_bitmap != nullptr);
1399 CHECK(!mark_bitmap->AtomicTestAndSet(to_ref));
1400 }
1401 }
1402 DCHECK(to_ref != nullptr);
1403
1404 // Attempt to install the forward pointer. This is in a loop as the
1405 // lock word atomic write can fail.
1406 while (true) {
1407 // Copy the object. TODO: copy only the lockword in the second iteration and on?
1408 memcpy(to_ref, from_ref, obj_size);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001409
1410 LockWord old_lock_word = to_ref->GetLockWord(false);
1411
1412 if (old_lock_word.GetState() == LockWord::kForwardingAddress) {
1413 // Lost the race. Another thread (either GC or mutator) stored
1414 // the forwarding pointer first. Make the lost copy (to_ref)
1415 // look like a valid but dead (dummy) object and keep it for
1416 // future reuse.
1417 FillWithDummyObject(to_ref, bytes_allocated);
1418 if (!fall_back_to_non_moving) {
1419 DCHECK(region_space_->IsInToSpace(to_ref));
1420 if (bytes_allocated > space::RegionSpace::kRegionSize) {
1421 // Free the large alloc.
1422 region_space_->FreeLarge(to_ref, bytes_allocated);
1423 } else {
1424 // Record the lost copy for later reuse.
1425 heap_->num_bytes_allocated_.FetchAndAddSequentiallyConsistent(bytes_allocated);
1426 to_space_bytes_skipped_.FetchAndAddSequentiallyConsistent(bytes_allocated);
1427 to_space_objects_skipped_.FetchAndAddSequentiallyConsistent(1);
1428 MutexLock mu(Thread::Current(), skipped_blocks_lock_);
1429 skipped_blocks_map_.insert(std::make_pair(bytes_allocated,
1430 reinterpret_cast<uint8_t*>(to_ref)));
1431 }
1432 } else {
1433 DCHECK(heap_->non_moving_space_->HasAddress(to_ref));
1434 DCHECK_EQ(bytes_allocated, non_moving_space_bytes_allocated);
1435 // Free the non-moving-space chunk.
1436 accounting::ContinuousSpaceBitmap* mark_bitmap =
1437 heap_mark_bitmap_->GetContinuousSpaceBitmap(to_ref);
1438 CHECK(mark_bitmap != nullptr);
1439 CHECK(mark_bitmap->Clear(to_ref));
1440 heap_->non_moving_space_->Free(Thread::Current(), to_ref);
1441 }
1442
1443 // Get the winner's forward ptr.
1444 mirror::Object* lost_fwd_ptr = to_ref;
1445 to_ref = reinterpret_cast<mirror::Object*>(old_lock_word.ForwardingAddress());
1446 CHECK(to_ref != nullptr);
1447 CHECK_NE(to_ref, lost_fwd_ptr);
1448 CHECK(region_space_->IsInToSpace(to_ref) || heap_->non_moving_space_->HasAddress(to_ref));
1449 CHECK_NE(to_ref->GetLockWord(false).GetState(), LockWord::kForwardingAddress);
1450 return to_ref;
1451 }
1452
Hiroshi Yamauchi60f63f52015-04-23 16:12:40 -07001453 // Set the gray ptr.
1454 if (kUseBakerReadBarrier) {
1455 to_ref->SetReadBarrierPointer(ReadBarrier::GrayPtr());
1456 }
1457
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001458 LockWord new_lock_word = LockWord::FromForwardingAddress(reinterpret_cast<size_t>(to_ref));
1459
1460 // Try to atomically write the fwd ptr.
1461 bool success = from_ref->CasLockWordWeakSequentiallyConsistent(old_lock_word, new_lock_word);
1462 if (LIKELY(success)) {
1463 // The CAS succeeded.
1464 objects_moved_.FetchAndAddSequentiallyConsistent(1);
1465 bytes_moved_.FetchAndAddSequentiallyConsistent(region_space_alloc_size);
1466 if (LIKELY(!fall_back_to_non_moving)) {
1467 DCHECK(region_space_->IsInToSpace(to_ref));
1468 } else {
1469 DCHECK(heap_->non_moving_space_->HasAddress(to_ref));
1470 DCHECK_EQ(bytes_allocated, non_moving_space_bytes_allocated);
1471 }
1472 if (kUseBakerReadBarrier) {
1473 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr());
1474 }
1475 DCHECK(GetFwdPtr(from_ref) == to_ref);
1476 CHECK_NE(to_ref->GetLockWord(false).GetState(), LockWord::kForwardingAddress);
1477 PushOntoMarkStack<true>(to_ref);
1478 return to_ref;
1479 } else {
1480 // The CAS failed. It may have lost the race or may have failed
1481 // due to monitor/hashcode ops. Either way, retry.
1482 }
1483 }
1484}
1485
1486mirror::Object* ConcurrentCopying::IsMarked(mirror::Object* from_ref) {
1487 DCHECK(from_ref != nullptr);
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08001488 space::RegionSpace::RegionType rtype = region_space_->GetRegionType(from_ref);
1489 if (rtype == space::RegionSpace::RegionType::kRegionTypeToSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001490 // It's already marked.
1491 return from_ref;
1492 }
1493 mirror::Object* to_ref;
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08001494 if (rtype == space::RegionSpace::RegionType::kRegionTypeFromSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001495 to_ref = GetFwdPtr(from_ref);
1496 DCHECK(to_ref == nullptr || region_space_->IsInToSpace(to_ref) ||
1497 heap_->non_moving_space_->HasAddress(to_ref))
1498 << "from_ref=" << from_ref << " to_ref=" << to_ref;
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08001499 } else if (rtype == space::RegionSpace::RegionType::kRegionTypeUnevacFromSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001500 if (region_space_bitmap_->Test(from_ref)) {
1501 to_ref = from_ref;
1502 } else {
1503 to_ref = nullptr;
1504 }
1505 } else {
1506 // from_ref is in a non-moving space.
1507 if (immune_region_.ContainsObject(from_ref)) {
1508 accounting::ContinuousSpaceBitmap* cc_bitmap =
1509 cc_heap_bitmap_->GetContinuousSpaceBitmap(from_ref);
1510 DCHECK(cc_bitmap != nullptr)
1511 << "An immune space object must have a bitmap";
1512 if (kIsDebugBuild) {
1513 DCHECK(heap_mark_bitmap_->GetContinuousSpaceBitmap(from_ref)->Test(from_ref))
1514 << "Immune space object must be already marked";
1515 }
1516 if (cc_bitmap->Test(from_ref)) {
1517 // Already marked.
1518 to_ref = from_ref;
1519 } else {
1520 // Newly marked.
1521 to_ref = nullptr;
1522 }
1523 } else {
1524 // Non-immune non-moving space. Use the mark bitmap.
1525 accounting::ContinuousSpaceBitmap* mark_bitmap =
1526 heap_mark_bitmap_->GetContinuousSpaceBitmap(from_ref);
1527 accounting::LargeObjectBitmap* los_bitmap =
1528 heap_mark_bitmap_->GetLargeObjectBitmap(from_ref);
1529 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
1530 bool is_los = mark_bitmap == nullptr;
1531 if (!is_los && mark_bitmap->Test(from_ref)) {
1532 // Already marked.
1533 to_ref = from_ref;
1534 } else if (is_los && los_bitmap->Test(from_ref)) {
1535 // Already marked in LOS.
1536 to_ref = from_ref;
1537 } else {
1538 // Not marked.
1539 if (IsOnAllocStack(from_ref)) {
1540 // If on the allocation stack, it's considered marked.
1541 to_ref = from_ref;
1542 } else {
1543 // Not marked.
1544 to_ref = nullptr;
1545 }
1546 }
1547 }
1548 }
1549 return to_ref;
1550}
1551
1552bool ConcurrentCopying::IsOnAllocStack(mirror::Object* ref) {
1553 QuasiAtomic::ThreadFenceAcquire();
1554 accounting::ObjectStack* alloc_stack = GetAllocationStack();
Mathieu Chartiercb535da2015-01-23 13:50:03 -08001555 return alloc_stack->Contains(ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001556}
1557
1558mirror::Object* ConcurrentCopying::Mark(mirror::Object* from_ref) {
1559 if (from_ref == nullptr) {
1560 return nullptr;
1561 }
1562 DCHECK(from_ref != nullptr);
1563 DCHECK(heap_->collector_type_ == kCollectorTypeCC);
Hiroshi Yamauchi60f63f52015-04-23 16:12:40 -07001564 if (kUseBakerReadBarrier && !is_active_) {
1565 // In the lock word forward address state, the read barrier bits
1566 // in the lock word are part of the stored forwarding address and
1567 // invalid. This is usually OK as the from-space copy of objects
1568 // aren't accessed by mutators due to the to-space
1569 // invariant. However, during the dex2oat image writing relocation
1570 // and the zygote compaction, objects can be in the forward
1571 // address state (to store the forward/relocation addresses) and
1572 // they can still be accessed and the invalid read barrier bits
1573 // are consulted. If they look like gray but aren't really, the
1574 // read barriers slow path can trigger when it shouldn't. To guard
1575 // against this, return here if the CC collector isn't running.
1576 return from_ref;
1577 }
1578 DCHECK(region_space_ != nullptr) << "Read barrier slow path taken when CC isn't running?";
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08001579 space::RegionSpace::RegionType rtype = region_space_->GetRegionType(from_ref);
1580 if (rtype == space::RegionSpace::RegionType::kRegionTypeToSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001581 // It's already marked.
1582 return from_ref;
1583 }
1584 mirror::Object* to_ref;
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08001585 if (rtype == space::RegionSpace::RegionType::kRegionTypeFromSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001586 to_ref = GetFwdPtr(from_ref);
1587 if (kUseBakerReadBarrier) {
1588 DCHECK(to_ref != ReadBarrier::GrayPtr()) << "from_ref=" << from_ref << " to_ref=" << to_ref;
1589 }
1590 if (to_ref == nullptr) {
1591 // It isn't marked yet. Mark it by copying it to the to-space.
1592 to_ref = Copy(from_ref);
1593 }
1594 DCHECK(region_space_->IsInToSpace(to_ref) || heap_->non_moving_space_->HasAddress(to_ref))
1595 << "from_ref=" << from_ref << " to_ref=" << to_ref;
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08001596 } else if (rtype == space::RegionSpace::RegionType::kRegionTypeUnevacFromSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001597 // This may or may not succeed, which is ok.
1598 if (kUseBakerReadBarrier) {
1599 from_ref->AtomicSetReadBarrierPointer(ReadBarrier::WhitePtr(), ReadBarrier::GrayPtr());
1600 }
1601 if (region_space_bitmap_->AtomicTestAndSet(from_ref)) {
1602 // Already marked.
1603 to_ref = from_ref;
1604 } else {
1605 // Newly marked.
1606 to_ref = from_ref;
1607 if (kUseBakerReadBarrier) {
1608 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr());
1609 }
1610 PushOntoMarkStack<true>(to_ref);
1611 }
1612 } else {
1613 // from_ref is in a non-moving space.
1614 DCHECK(!region_space_->HasAddress(from_ref)) << from_ref;
1615 if (immune_region_.ContainsObject(from_ref)) {
1616 accounting::ContinuousSpaceBitmap* cc_bitmap =
1617 cc_heap_bitmap_->GetContinuousSpaceBitmap(from_ref);
1618 DCHECK(cc_bitmap != nullptr)
1619 << "An immune space object must have a bitmap";
1620 if (kIsDebugBuild) {
1621 DCHECK(heap_mark_bitmap_->GetContinuousSpaceBitmap(from_ref)->Test(from_ref))
1622 << "Immune space object must be already marked";
1623 }
1624 // This may or may not succeed, which is ok.
1625 if (kUseBakerReadBarrier) {
1626 from_ref->AtomicSetReadBarrierPointer(ReadBarrier::WhitePtr(), ReadBarrier::GrayPtr());
1627 }
1628 if (cc_bitmap->AtomicTestAndSet(from_ref)) {
1629 // Already marked.
1630 to_ref = from_ref;
1631 } else {
1632 // Newly marked.
1633 to_ref = from_ref;
1634 if (kUseBakerReadBarrier) {
1635 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr());
1636 }
1637 PushOntoMarkStack<true>(to_ref);
1638 }
1639 } else {
1640 // Use the mark bitmap.
1641 accounting::ContinuousSpaceBitmap* mark_bitmap =
1642 heap_mark_bitmap_->GetContinuousSpaceBitmap(from_ref);
1643 accounting::LargeObjectBitmap* los_bitmap =
1644 heap_mark_bitmap_->GetLargeObjectBitmap(from_ref);
1645 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
1646 bool is_los = mark_bitmap == nullptr;
1647 if (!is_los && mark_bitmap->Test(from_ref)) {
1648 // Already marked.
1649 to_ref = from_ref;
1650 if (kUseBakerReadBarrier) {
1651 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr() ||
1652 to_ref->GetReadBarrierPointer() == ReadBarrier::BlackPtr());
1653 }
1654 } else if (is_los && los_bitmap->Test(from_ref)) {
1655 // Already marked in LOS.
1656 to_ref = from_ref;
1657 if (kUseBakerReadBarrier) {
1658 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr() ||
1659 to_ref->GetReadBarrierPointer() == ReadBarrier::BlackPtr());
1660 }
1661 } else {
1662 // Not marked.
1663 if (IsOnAllocStack(from_ref)) {
1664 // If it's on the allocation stack, it's considered marked. Keep it white.
1665 to_ref = from_ref;
1666 // Objects on the allocation stack need not be marked.
1667 if (!is_los) {
1668 DCHECK(!mark_bitmap->Test(to_ref));
1669 } else {
1670 DCHECK(!los_bitmap->Test(to_ref));
1671 }
1672 if (kUseBakerReadBarrier) {
1673 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::WhitePtr());
1674 }
1675 } else {
1676 // Not marked or on the allocation stack. Try to mark it.
1677 // This may or may not succeed, which is ok.
1678 if (kUseBakerReadBarrier) {
1679 from_ref->AtomicSetReadBarrierPointer(ReadBarrier::WhitePtr(), ReadBarrier::GrayPtr());
1680 }
1681 if (!is_los && mark_bitmap->AtomicTestAndSet(from_ref)) {
1682 // Already marked.
1683 to_ref = from_ref;
1684 } else if (is_los && los_bitmap->AtomicTestAndSet(from_ref)) {
1685 // Already marked in LOS.
1686 to_ref = from_ref;
1687 } else {
1688 // Newly marked.
1689 to_ref = from_ref;
1690 if (kUseBakerReadBarrier) {
1691 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr());
1692 }
1693 PushOntoMarkStack<true>(to_ref);
1694 }
1695 }
1696 }
1697 }
1698 }
1699 return to_ref;
1700}
1701
1702void ConcurrentCopying::FinishPhase() {
1703 region_space_ = nullptr;
1704 CHECK(mark_queue_.IsEmpty());
1705 mark_queue_.Clear();
1706 {
1707 MutexLock mu(Thread::Current(), skipped_blocks_lock_);
1708 skipped_blocks_map_.clear();
1709 }
1710 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
1711 heap_->ClearMarkedObjects();
1712}
1713
1714mirror::Object* ConcurrentCopying::IsMarkedCallback(mirror::Object* from_ref, void* arg) {
1715 return reinterpret_cast<ConcurrentCopying*>(arg)->IsMarked(from_ref);
1716}
1717
1718bool ConcurrentCopying::IsHeapReferenceMarkedCallback(
1719 mirror::HeapReference<mirror::Object>* field, void* arg) {
1720 mirror::Object* from_ref = field->AsMirrorPtr();
1721 mirror::Object* to_ref = reinterpret_cast<ConcurrentCopying*>(arg)->IsMarked(from_ref);
1722 if (to_ref == nullptr) {
1723 return false;
1724 }
1725 if (from_ref != to_ref) {
1726 QuasiAtomic::ThreadFenceRelease();
1727 field->Assign(to_ref);
1728 QuasiAtomic::ThreadFenceSequentiallyConsistent();
1729 }
1730 return true;
1731}
1732
1733mirror::Object* ConcurrentCopying::MarkCallback(mirror::Object* from_ref, void* arg) {
1734 return reinterpret_cast<ConcurrentCopying*>(arg)->Mark(from_ref);
1735}
1736
1737void ConcurrentCopying::ProcessMarkStackCallback(void* arg) {
1738 reinterpret_cast<ConcurrentCopying*>(arg)->ProcessMarkStack();
1739}
1740
1741void ConcurrentCopying::DelayReferenceReferent(mirror::Class* klass, mirror::Reference* reference) {
1742 heap_->GetReferenceProcessor()->DelayReferenceReferent(
1743 klass, reference, &IsHeapReferenceMarkedCallback, this);
1744}
1745
1746void ConcurrentCopying::ProcessReferences(Thread* self, bool concurrent) {
1747 TimingLogger::ScopedTiming split("ProcessReferences", GetTimings());
1748 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1749 GetHeap()->GetReferenceProcessor()->ProcessReferences(
1750 concurrent, GetTimings(), GetCurrentIteration()->GetClearSoftReferences(),
1751 &IsHeapReferenceMarkedCallback, &MarkCallback, &ProcessMarkStackCallback, this);
1752}
1753
1754void ConcurrentCopying::RevokeAllThreadLocalBuffers() {
1755 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
1756 region_space_->RevokeAllThreadLocalBuffers();
1757}
1758
Hiroshi Yamauchid5307ec2014-03-27 21:07:51 -07001759} // namespace collector
1760} // namespace gc
1761} // namespace art