blob: 5e69b797e0676ef1388ff7fc1a48825d366ccc97 [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 }
Man Cao41656de2015-07-06 18:53:15 -0700337 // TODO: Other garbage collectors uses Runtime::VisitConcurrentRoots(), refactor this part
338 // to also use the same function.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800339 {
340 TimingLogger::ScopedTiming split2("VisitConstantRoots", GetTimings());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700341 Runtime::Current()->VisitConstantRoots(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800342 }
343 {
344 TimingLogger::ScopedTiming split3("VisitInternTableRoots", GetTimings());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700345 Runtime::Current()->GetInternTable()->VisitRoots(this, kVisitRootFlagAllRoots);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800346 }
347 {
348 TimingLogger::ScopedTiming split4("VisitClassLinkerRoots", GetTimings());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700349 Runtime::Current()->GetClassLinker()->VisitRoots(this, kVisitRootFlagAllRoots);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800350 }
351 {
352 // TODO: don't visit the transaction roots if it's not active.
353 TimingLogger::ScopedTiming split5("VisitNonThreadRoots", GetTimings());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700354 Runtime::Current()->VisitNonThreadRoots(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800355 }
Man Cao41656de2015-07-06 18:53:15 -0700356 Runtime::Current()->GetHeap()->VisitAllocationRecords(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800357
358 // Immune spaces.
359 for (auto& space : heap_->GetContinuousSpaces()) {
360 if (immune_region_.ContainsSpace(space)) {
361 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
362 accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
363 ConcurrentCopyingImmuneSpaceObjVisitor visitor(this);
364 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()),
365 reinterpret_cast<uintptr_t>(space->Limit()),
366 visitor);
367 }
368 }
369
370 Thread* self = Thread::Current();
371 {
372 TimingLogger::ScopedTiming split6("ProcessMarkStack", GetTimings());
373 // Process the mark stack and issue an empty check point. If the
374 // mark stack is still empty after the check point, we're
375 // done. Otherwise, repeat.
376 ProcessMarkStack();
377 size_t count = 0;
378 while (!ProcessMarkStack()) {
379 ++count;
380 if (kVerboseMode) {
381 LOG(INFO) << "Issue an empty check point. " << count;
382 }
383 IssueEmptyCheckpoint();
384 }
385 // Need to ensure the mark stack is empty before reference
386 // processing to get rid of non-reference gray objects.
387 CheckEmptyMarkQueue();
388 // Enable the GetReference slow path and disallow access to the system weaks.
389 GetHeap()->GetReferenceProcessor()->EnableSlowPath();
390 Runtime::Current()->DisallowNewSystemWeaks();
391 QuasiAtomic::ThreadFenceForConstructor();
392 // Lock-unlock the system weak locks so that there's no thread in
393 // the middle of accessing system weaks.
394 Runtime::Current()->EnsureNewSystemWeaksDisallowed();
395 // Note: Do not issue a checkpoint from here to the
396 // SweepSystemWeaks call or else a deadlock due to
397 // WaitHoldingLocks() would occur.
398 if (kVerboseMode) {
399 LOG(INFO) << "Enabled the ref proc slow path & disabled access to system weaks.";
400 LOG(INFO) << "ProcessReferences";
401 }
402 ProcessReferences(self, true);
403 CheckEmptyMarkQueue();
404 if (kVerboseMode) {
405 LOG(INFO) << "SweepSystemWeaks";
406 }
407 SweepSystemWeaks(self);
408 if (kVerboseMode) {
409 LOG(INFO) << "SweepSystemWeaks done";
410 }
411 // Because hash_set::Erase() can call the hash function for
412 // arbitrary elements in the weak intern table in
413 // InternTable::Table::SweepWeaks(), the above SweepSystemWeaks()
414 // call may have marked some objects (strings) alive. So process
415 // the mark stack here once again.
416 ProcessMarkStack();
417 CheckEmptyMarkQueue();
Hiroshi Yamauchi46ec5202015-06-19 17:39:45 -0700418 if (kVerboseMode) {
419 LOG(INFO) << "AllowNewSystemWeaks";
420 }
421 Runtime::Current()->AllowNewSystemWeaks();
422 IssueEmptyCheckpoint();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800423 // Disable marking.
424 if (kUseTableLookupReadBarrier) {
425 heap_->rb_table_->ClearAll();
426 DCHECK(heap_->rb_table_->IsAllCleared());
427 }
428 is_mark_queue_push_disallowed_.StoreSequentiallyConsistent(1);
429 is_marking_ = false;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800430 CheckEmptyMarkQueue();
431 }
432
433 if (kVerboseMode) {
434 LOG(INFO) << "GC end of MarkingPhase";
435 }
436}
437
438void ConcurrentCopying::IssueEmptyCheckpoint() {
439 Thread* self = Thread::Current();
440 EmptyCheckpoint check_point(this);
441 ThreadList* thread_list = Runtime::Current()->GetThreadList();
442 gc_barrier_->Init(self, 0);
443 size_t barrier_count = thread_list->RunCheckpoint(&check_point);
Lei Lidd9943d2015-02-02 14:24:44 +0800444 // If there are no threads to wait which implys that all the checkpoint functions are finished,
445 // then no need to release the mutator lock.
446 if (barrier_count == 0) {
447 return;
448 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800449 // Release locks then wait for all mutator threads to pass the barrier.
450 Locks::mutator_lock_->SharedUnlock(self);
451 {
452 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
453 gc_barrier_->Increment(self, barrier_count);
454 }
455 Locks::mutator_lock_->SharedLock(self);
456}
457
458mirror::Object* ConcurrentCopying::PopOffMarkStack() {
459 return mark_queue_.Dequeue();
460}
461
462template<bool kThreadSafe>
463void ConcurrentCopying::PushOntoMarkStack(mirror::Object* to_ref) {
464 CHECK_EQ(is_mark_queue_push_disallowed_.LoadRelaxed(), 0)
465 << " " << to_ref << " " << PrettyTypeOf(to_ref);
466 if (kThreadSafe) {
467 CHECK(mark_queue_.Enqueue(to_ref)) << "Mark queue overflow";
468 } else {
469 CHECK(mark_queue_.EnqueueThreadUnsafe(to_ref)) << "Mark queue overflow";
470 }
471}
472
473accounting::ObjectStack* ConcurrentCopying::GetAllocationStack() {
474 return heap_->allocation_stack_.get();
475}
476
477accounting::ObjectStack* ConcurrentCopying::GetLiveStack() {
478 return heap_->live_stack_.get();
479}
480
481inline mirror::Object* ConcurrentCopying::GetFwdPtr(mirror::Object* from_ref) {
482 DCHECK(region_space_->IsInFromSpace(from_ref));
483 LockWord lw = from_ref->GetLockWord(false);
484 if (lw.GetState() == LockWord::kForwardingAddress) {
485 mirror::Object* fwd_ptr = reinterpret_cast<mirror::Object*>(lw.ForwardingAddress());
486 CHECK(fwd_ptr != nullptr);
487 return fwd_ptr;
488 } else {
489 return nullptr;
490 }
491}
492
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800493// The following visitors are that used to verify that there's no
494// references to the from-space left after marking.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700495class ConcurrentCopyingVerifyNoFromSpaceRefsVisitor : public SingleRootVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800496 public:
497 explicit ConcurrentCopyingVerifyNoFromSpaceRefsVisitor(ConcurrentCopying* collector)
498 : collector_(collector) {}
499
500 void operator()(mirror::Object* ref) const
501 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) ALWAYS_INLINE {
502 if (ref == nullptr) {
503 // OK.
504 return;
505 }
506 collector_->AssertToSpaceInvariant(nullptr, MemberOffset(0), ref);
507 if (kUseBakerReadBarrier) {
508 if (collector_->RegionSpace()->IsInToSpace(ref)) {
509 CHECK(ref->GetReadBarrierPointer() == nullptr)
510 << "To-space ref " << ref << " " << PrettyTypeOf(ref)
511 << " has non-white rb_ptr " << ref->GetReadBarrierPointer();
512 } else {
513 CHECK(ref->GetReadBarrierPointer() == ReadBarrier::BlackPtr() ||
514 (ref->GetReadBarrierPointer() == ReadBarrier::WhitePtr() &&
515 collector_->IsOnAllocStack(ref)))
516 << "Non-moving/unevac from space ref " << ref << " " << PrettyTypeOf(ref)
517 << " has non-black rb_ptr " << ref->GetReadBarrierPointer()
518 << " but isn't on the alloc stack (and has white rb_ptr)."
519 << " Is it in the non-moving space="
520 << (collector_->GetHeap()->GetNonMovingSpace()->HasAddress(ref));
521 }
522 }
523 }
524
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700525 void VisitRoot(mirror::Object* root, const RootInfo& info ATTRIBUTE_UNUSED)
526 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800527 DCHECK(root != nullptr);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700528 operator()(root);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800529 }
530
531 private:
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700532 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800533};
534
535class ConcurrentCopyingVerifyNoFromSpaceRefsFieldVisitor {
536 public:
537 explicit ConcurrentCopyingVerifyNoFromSpaceRefsFieldVisitor(ConcurrentCopying* collector)
538 : collector_(collector) {}
539
540 void operator()(mirror::Object* obj, MemberOffset offset, bool /* is_static */) const
541 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) ALWAYS_INLINE {
542 mirror::Object* ref =
543 obj->GetFieldObject<mirror::Object, kDefaultVerifyFlags, kWithoutReadBarrier>(offset);
544 ConcurrentCopyingVerifyNoFromSpaceRefsVisitor visitor(collector_);
545 visitor(ref);
546 }
547 void operator()(mirror::Class* klass, mirror::Reference* ref) const
548 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) ALWAYS_INLINE {
549 CHECK(klass->IsTypeOfReferenceClass());
550 this->operator()(ref, mirror::Reference::ReferentOffset(), false);
551 }
552
553 private:
554 ConcurrentCopying* collector_;
555};
556
557class ConcurrentCopyingVerifyNoFromSpaceRefsObjectVisitor {
558 public:
559 explicit ConcurrentCopyingVerifyNoFromSpaceRefsObjectVisitor(ConcurrentCopying* collector)
560 : collector_(collector) {}
561 void operator()(mirror::Object* obj) const
562 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
563 ObjectCallback(obj, collector_);
564 }
565 static void ObjectCallback(mirror::Object* obj, void *arg)
566 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
567 CHECK(obj != nullptr);
568 ConcurrentCopying* collector = reinterpret_cast<ConcurrentCopying*>(arg);
569 space::RegionSpace* region_space = collector->RegionSpace();
570 CHECK(!region_space->IsInFromSpace(obj)) << "Scanning object " << obj << " in from space";
571 ConcurrentCopyingVerifyNoFromSpaceRefsFieldVisitor visitor(collector);
572 obj->VisitReferences<true>(visitor, visitor);
573 if (kUseBakerReadBarrier) {
574 if (collector->RegionSpace()->IsInToSpace(obj)) {
575 CHECK(obj->GetReadBarrierPointer() == nullptr)
576 << "obj=" << obj << " non-white rb_ptr " << obj->GetReadBarrierPointer();
577 } else {
578 CHECK(obj->GetReadBarrierPointer() == ReadBarrier::BlackPtr() ||
579 (obj->GetReadBarrierPointer() == ReadBarrier::WhitePtr() &&
580 collector->IsOnAllocStack(obj)))
581 << "Non-moving space/unevac from space ref " << obj << " " << PrettyTypeOf(obj)
582 << " has non-black rb_ptr " << obj->GetReadBarrierPointer()
583 << " but isn't on the alloc stack (and has white rb_ptr). Is it in the non-moving space="
584 << (collector->GetHeap()->GetNonMovingSpace()->HasAddress(obj));
585 }
586 }
587 }
588
589 private:
590 ConcurrentCopying* const collector_;
591};
592
593// Verify there's no from-space references left after the marking phase.
594void ConcurrentCopying::VerifyNoFromSpaceReferences() {
595 Thread* self = Thread::Current();
596 DCHECK(Locks::mutator_lock_->IsExclusiveHeld(self));
597 ConcurrentCopyingVerifyNoFromSpaceRefsObjectVisitor visitor(this);
598 // Roots.
599 {
600 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700601 ConcurrentCopyingVerifyNoFromSpaceRefsVisitor ref_visitor(this);
602 Runtime::Current()->VisitRoots(&ref_visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800603 }
604 // The to-space.
605 region_space_->WalkToSpace(ConcurrentCopyingVerifyNoFromSpaceRefsObjectVisitor::ObjectCallback,
606 this);
607 // Non-moving spaces.
608 {
609 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
610 heap_->GetMarkBitmap()->Visit(visitor);
611 }
612 // The alloc stack.
613 {
614 ConcurrentCopyingVerifyNoFromSpaceRefsVisitor ref_visitor(this);
Mathieu Chartiercb535da2015-01-23 13:50:03 -0800615 for (auto* it = heap_->allocation_stack_->Begin(), *end = heap_->allocation_stack_->End();
616 it < end; ++it) {
617 mirror::Object* const obj = it->AsMirrorPtr();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800618 if (obj != nullptr && obj->GetClass() != nullptr) {
619 // TODO: need to call this only if obj is alive?
620 ref_visitor(obj);
621 visitor(obj);
622 }
623 }
624 }
625 // TODO: LOS. But only refs in LOS are classes.
626}
627
628// The following visitors are used to assert the to-space invariant.
629class ConcurrentCopyingAssertToSpaceInvariantRefsVisitor {
630 public:
631 explicit ConcurrentCopyingAssertToSpaceInvariantRefsVisitor(ConcurrentCopying* collector)
632 : collector_(collector) {}
633
634 void operator()(mirror::Object* ref) const
635 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) ALWAYS_INLINE {
636 if (ref == nullptr) {
637 // OK.
638 return;
639 }
640 collector_->AssertToSpaceInvariant(nullptr, MemberOffset(0), ref);
641 }
642 static void RootCallback(mirror::Object** root, void *arg, const RootInfo& /*root_info*/)
643 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
644 ConcurrentCopying* collector = reinterpret_cast<ConcurrentCopying*>(arg);
645 ConcurrentCopyingAssertToSpaceInvariantRefsVisitor visitor(collector);
646 DCHECK(root != nullptr);
647 visitor(*root);
648 }
649
650 private:
651 ConcurrentCopying* collector_;
652};
653
654class ConcurrentCopyingAssertToSpaceInvariantFieldVisitor {
655 public:
656 explicit ConcurrentCopyingAssertToSpaceInvariantFieldVisitor(ConcurrentCopying* collector)
657 : collector_(collector) {}
658
659 void operator()(mirror::Object* obj, MemberOffset offset, bool /* is_static */) const
660 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) ALWAYS_INLINE {
661 mirror::Object* ref =
662 obj->GetFieldObject<mirror::Object, kDefaultVerifyFlags, kWithoutReadBarrier>(offset);
663 ConcurrentCopyingAssertToSpaceInvariantRefsVisitor visitor(collector_);
664 visitor(ref);
665 }
666 void operator()(mirror::Class* klass, mirror::Reference* /* ref */) const
667 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) ALWAYS_INLINE {
668 CHECK(klass->IsTypeOfReferenceClass());
669 }
670
671 private:
672 ConcurrentCopying* collector_;
673};
674
675class ConcurrentCopyingAssertToSpaceInvariantObjectVisitor {
676 public:
677 explicit ConcurrentCopyingAssertToSpaceInvariantObjectVisitor(ConcurrentCopying* collector)
678 : collector_(collector) {}
679 void operator()(mirror::Object* obj) const
680 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
681 ObjectCallback(obj, collector_);
682 }
683 static void ObjectCallback(mirror::Object* obj, void *arg)
684 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
685 CHECK(obj != nullptr);
686 ConcurrentCopying* collector = reinterpret_cast<ConcurrentCopying*>(arg);
687 space::RegionSpace* region_space = collector->RegionSpace();
688 CHECK(!region_space->IsInFromSpace(obj)) << "Scanning object " << obj << " in from space";
689 collector->AssertToSpaceInvariant(nullptr, MemberOffset(0), obj);
690 ConcurrentCopyingAssertToSpaceInvariantFieldVisitor visitor(collector);
691 obj->VisitReferences<true>(visitor, visitor);
692 }
693
694 private:
695 ConcurrentCopying* collector_;
696};
697
698bool ConcurrentCopying::ProcessMarkStack() {
699 if (kVerboseMode) {
700 LOG(INFO) << "ProcessMarkStack. ";
701 }
702 size_t count = 0;
703 mirror::Object* to_ref;
704 while ((to_ref = PopOffMarkStack()) != nullptr) {
705 ++count;
706 DCHECK(!region_space_->IsInFromSpace(to_ref));
707 if (kUseBakerReadBarrier) {
708 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr())
709 << " " << to_ref << " " << to_ref->GetReadBarrierPointer()
710 << " is_marked=" << IsMarked(to_ref);
711 }
712 // Scan ref fields.
713 Scan(to_ref);
714 // Mark the gray ref as white or black.
715 if (kUseBakerReadBarrier) {
716 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr())
717 << " " << to_ref << " " << to_ref->GetReadBarrierPointer()
718 << " is_marked=" << IsMarked(to_ref);
719 }
720 if (to_ref->GetClass<kVerifyNone, kWithoutReadBarrier>()->IsTypeOfReferenceClass() &&
721 to_ref->AsReference()->GetReferent<kWithoutReadBarrier>() != nullptr &&
722 !IsInToSpace(to_ref->AsReference()->GetReferent<kWithoutReadBarrier>())) {
723 // Leave References gray so that GetReferent() will trigger RB.
724 CHECK(to_ref->AsReference()->IsEnqueued()) << "Left unenqueued ref gray " << to_ref;
725 } else {
Hiroshi Yamauchi60f63f52015-04-23 16:12:40 -0700726#ifdef USE_BAKER_OR_BROOKS_READ_BARRIER
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800727 if (kUseBakerReadBarrier) {
728 if (region_space_->IsInToSpace(to_ref)) {
729 // If to-space, change from gray to white.
730 bool success = to_ref->AtomicSetReadBarrierPointer(ReadBarrier::GrayPtr(),
731 ReadBarrier::WhitePtr());
732 CHECK(success) << "Must succeed as we won the race.";
733 CHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::WhitePtr());
734 } else {
735 // If non-moving space/unevac from space, change from gray
736 // to black. We can't change gray to white because it's not
737 // safe to use CAS if two threads change values in opposite
738 // directions (A->B and B->A). So, we change it to black to
739 // indicate non-moving objects that have been marked
740 // through. Note we'd need to change from black to white
741 // later (concurrently).
742 bool success = to_ref->AtomicSetReadBarrierPointer(ReadBarrier::GrayPtr(),
743 ReadBarrier::BlackPtr());
744 CHECK(success) << "Must succeed as we won the race.";
745 CHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::BlackPtr());
746 }
747 }
Hiroshi Yamauchi60f63f52015-04-23 16:12:40 -0700748#else
749 DCHECK(!kUseBakerReadBarrier);
750#endif
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800751 }
752 if (ReadBarrier::kEnableToSpaceInvariantChecks || kIsDebugBuild) {
753 ConcurrentCopyingAssertToSpaceInvariantObjectVisitor visitor(this);
754 visitor(to_ref);
755 }
756 }
757 // Return true if the stack was empty.
758 return count == 0;
759}
760
761void ConcurrentCopying::CheckEmptyMarkQueue() {
762 if (!mark_queue_.IsEmpty()) {
763 while (!mark_queue_.IsEmpty()) {
764 mirror::Object* obj = mark_queue_.Dequeue();
765 if (kUseBakerReadBarrier) {
766 mirror::Object* rb_ptr = obj->GetReadBarrierPointer();
767 LOG(INFO) << "On mark queue : " << obj << " " << PrettyTypeOf(obj) << " rb_ptr=" << rb_ptr
768 << " is_marked=" << IsMarked(obj);
769 } else {
770 LOG(INFO) << "On mark queue : " << obj << " " << PrettyTypeOf(obj)
771 << " is_marked=" << IsMarked(obj);
772 }
773 }
774 LOG(FATAL) << "mark queue is not empty";
775 }
776}
777
778void ConcurrentCopying::SweepSystemWeaks(Thread* self) {
779 TimingLogger::ScopedTiming split("SweepSystemWeaks", GetTimings());
780 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
781 Runtime::Current()->SweepSystemWeaks(IsMarkedCallback, this);
782}
783
784void ConcurrentCopying::Sweep(bool swap_bitmaps) {
785 {
786 TimingLogger::ScopedTiming t("MarkStackAsLive", GetTimings());
787 accounting::ObjectStack* live_stack = heap_->GetLiveStack();
788 if (kEnableFromSpaceAccountingCheck) {
789 CHECK_GE(live_stack_freeze_size_, live_stack->Size());
790 }
791 heap_->MarkAllocStackAsLive(live_stack);
792 live_stack->Reset();
793 }
794 CHECK(mark_queue_.IsEmpty());
795 TimingLogger::ScopedTiming split("Sweep", GetTimings());
796 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
797 if (space->IsContinuousMemMapAllocSpace()) {
798 space::ContinuousMemMapAllocSpace* alloc_space = space->AsContinuousMemMapAllocSpace();
799 if (space == region_space_ || immune_region_.ContainsSpace(space)) {
800 continue;
801 }
802 TimingLogger::ScopedTiming split2(
803 alloc_space->IsZygoteSpace() ? "SweepZygoteSpace" : "SweepAllocSpace", GetTimings());
804 RecordFree(alloc_space->Sweep(swap_bitmaps));
805 }
806 }
807 SweepLargeObjects(swap_bitmaps);
808}
809
810void ConcurrentCopying::SweepLargeObjects(bool swap_bitmaps) {
811 TimingLogger::ScopedTiming split("SweepLargeObjects", GetTimings());
812 RecordFreeLOS(heap_->GetLargeObjectsSpace()->Sweep(swap_bitmaps));
813}
814
815class ConcurrentCopyingClearBlackPtrsVisitor {
816 public:
817 explicit ConcurrentCopyingClearBlackPtrsVisitor(ConcurrentCopying* cc)
818 : collector_(cc) {}
Andreas Gampe65b798e2015-04-06 09:35:22 -0700819#ifndef USE_BAKER_OR_BROOKS_READ_BARRIER
820 NO_RETURN
821#endif
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800822 void operator()(mirror::Object* obj) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
823 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
824 DCHECK(obj != nullptr);
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -0800825 DCHECK(collector_->heap_->GetMarkBitmap()->Test(obj)) << obj;
826 DCHECK_EQ(obj->GetReadBarrierPointer(), ReadBarrier::BlackPtr()) << obj;
Hiroshi Yamauchi60f63f52015-04-23 16:12:40 -0700827 obj->AtomicSetReadBarrierPointer(ReadBarrier::BlackPtr(), ReadBarrier::WhitePtr());
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -0800828 DCHECK_EQ(obj->GetReadBarrierPointer(), ReadBarrier::WhitePtr()) << obj;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800829 }
830
831 private:
832 ConcurrentCopying* const collector_;
833};
834
835// Clear the black ptrs in non-moving objects back to white.
836void ConcurrentCopying::ClearBlackPtrs() {
837 CHECK(kUseBakerReadBarrier);
838 TimingLogger::ScopedTiming split("ClearBlackPtrs", GetTimings());
839 ConcurrentCopyingClearBlackPtrsVisitor visitor(this);
840 for (auto& space : heap_->GetContinuousSpaces()) {
841 if (space == region_space_) {
842 continue;
843 }
844 accounting::ContinuousSpaceBitmap* mark_bitmap = space->GetMarkBitmap();
845 if (kVerboseMode) {
846 LOG(INFO) << "ClearBlackPtrs: " << *space << " bitmap: " << *mark_bitmap;
847 }
848 mark_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()),
849 reinterpret_cast<uintptr_t>(space->Limit()),
850 visitor);
851 }
852 space::LargeObjectSpace* large_object_space = heap_->GetLargeObjectsSpace();
853 large_object_space->GetMarkBitmap()->VisitMarkedRange(
854 reinterpret_cast<uintptr_t>(large_object_space->Begin()),
855 reinterpret_cast<uintptr_t>(large_object_space->End()),
856 visitor);
857 // Objects on the allocation stack?
858 if (ReadBarrier::kEnableReadBarrierInvariantChecks || kIsDebugBuild) {
859 size_t count = GetAllocationStack()->Size();
Mathieu Chartiercb535da2015-01-23 13:50:03 -0800860 auto* it = GetAllocationStack()->Begin();
861 auto* end = GetAllocationStack()->End();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800862 for (size_t i = 0; i < count; ++i, ++it) {
Mathieu Chartiercb535da2015-01-23 13:50:03 -0800863 CHECK_LT(it, end);
864 mirror::Object* obj = it->AsMirrorPtr();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800865 if (obj != nullptr) {
866 // Must have been cleared above.
Mathieu Chartiercb535da2015-01-23 13:50:03 -0800867 CHECK_EQ(obj->GetReadBarrierPointer(), ReadBarrier::WhitePtr()) << obj;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800868 }
869 }
870 }
871}
872
873void ConcurrentCopying::ReclaimPhase() {
874 TimingLogger::ScopedTiming split("ReclaimPhase", GetTimings());
875 if (kVerboseMode) {
876 LOG(INFO) << "GC ReclaimPhase";
877 }
878 Thread* self = Thread::Current();
879
880 {
881 // Double-check that the mark stack is empty.
882 // Note: need to set this after VerifyNoFromSpaceRef().
883 is_asserting_to_space_invariant_ = false;
884 QuasiAtomic::ThreadFenceForConstructor();
885 if (kVerboseMode) {
886 LOG(INFO) << "Issue an empty check point. ";
887 }
888 IssueEmptyCheckpoint();
889 // Disable the check.
890 is_mark_queue_push_disallowed_.StoreSequentiallyConsistent(0);
891 CheckEmptyMarkQueue();
892 }
893
894 {
895 // Record freed objects.
896 TimingLogger::ScopedTiming split2("RecordFree", GetTimings());
897 // Don't include thread-locals that are in the to-space.
898 uint64_t from_bytes = region_space_->GetBytesAllocatedInFromSpace();
899 uint64_t from_objects = region_space_->GetObjectsAllocatedInFromSpace();
900 uint64_t unevac_from_bytes = region_space_->GetBytesAllocatedInUnevacFromSpace();
901 uint64_t unevac_from_objects = region_space_->GetObjectsAllocatedInUnevacFromSpace();
902 uint64_t to_bytes = bytes_moved_.LoadSequentiallyConsistent();
903 uint64_t to_objects = objects_moved_.LoadSequentiallyConsistent();
904 if (kEnableFromSpaceAccountingCheck) {
905 CHECK_EQ(from_space_num_objects_at_first_pause_, from_objects + unevac_from_objects);
906 CHECK_EQ(from_space_num_bytes_at_first_pause_, from_bytes + unevac_from_bytes);
907 }
908 CHECK_LE(to_objects, from_objects);
909 CHECK_LE(to_bytes, from_bytes);
910 int64_t freed_bytes = from_bytes - to_bytes;
911 int64_t freed_objects = from_objects - to_objects;
912 if (kVerboseMode) {
913 LOG(INFO) << "RecordFree:"
914 << " from_bytes=" << from_bytes << " from_objects=" << from_objects
915 << " unevac_from_bytes=" << unevac_from_bytes << " unevac_from_objects=" << unevac_from_objects
916 << " to_bytes=" << to_bytes << " to_objects=" << to_objects
917 << " freed_bytes=" << freed_bytes << " freed_objects=" << freed_objects
918 << " from_space size=" << region_space_->FromSpaceSize()
919 << " unevac_from_space size=" << region_space_->UnevacFromSpaceSize()
920 << " to_space size=" << region_space_->ToSpaceSize();
921 LOG(INFO) << "(before) num_bytes_allocated=" << heap_->num_bytes_allocated_.LoadSequentiallyConsistent();
922 }
923 RecordFree(ObjectBytePair(freed_objects, freed_bytes));
924 if (kVerboseMode) {
925 LOG(INFO) << "(after) num_bytes_allocated=" << heap_->num_bytes_allocated_.LoadSequentiallyConsistent();
926 }
927 }
928
929 {
930 TimingLogger::ScopedTiming split3("ComputeUnevacFromSpaceLiveRatio", GetTimings());
931 ComputeUnevacFromSpaceLiveRatio();
932 }
933
934 {
935 TimingLogger::ScopedTiming split4("ClearFromSpace", GetTimings());
936 region_space_->ClearFromSpace();
937 }
938
939 {
940 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
941 if (kUseBakerReadBarrier) {
942 ClearBlackPtrs();
943 }
944 Sweep(false);
945 SwapBitmaps();
946 heap_->UnBindBitmaps();
947
948 // Remove bitmaps for the immune spaces.
949 while (!cc_bitmaps_.empty()) {
950 accounting::ContinuousSpaceBitmap* cc_bitmap = cc_bitmaps_.back();
951 cc_heap_bitmap_->RemoveContinuousSpaceBitmap(cc_bitmap);
952 delete cc_bitmap;
953 cc_bitmaps_.pop_back();
954 }
955 region_space_bitmap_ = nullptr;
956 }
957
958 if (kVerboseMode) {
959 LOG(INFO) << "GC end of ReclaimPhase";
960 }
961}
962
963class ConcurrentCopyingComputeUnevacFromSpaceLiveRatioVisitor {
964 public:
965 explicit ConcurrentCopyingComputeUnevacFromSpaceLiveRatioVisitor(ConcurrentCopying* cc)
966 : collector_(cc) {}
967 void operator()(mirror::Object* ref) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
968 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
969 DCHECK(ref != nullptr);
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -0800970 DCHECK(collector_->region_space_bitmap_->Test(ref)) << ref;
971 DCHECK(collector_->region_space_->IsInUnevacFromSpace(ref)) << ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800972 if (kUseBakerReadBarrier) {
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -0800973 DCHECK_EQ(ref->GetReadBarrierPointer(), ReadBarrier::BlackPtr()) << ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800974 // Clear the black ptr.
Hiroshi Yamauchi60f63f52015-04-23 16:12:40 -0700975 ref->AtomicSetReadBarrierPointer(ReadBarrier::BlackPtr(), ReadBarrier::WhitePtr());
976 DCHECK_EQ(ref->GetReadBarrierPointer(), ReadBarrier::WhitePtr()) << ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800977 }
978 size_t obj_size = ref->SizeOf();
979 size_t alloc_size = RoundUp(obj_size, space::RegionSpace::kAlignment);
980 collector_->region_space_->AddLiveBytes(ref, alloc_size);
981 }
982
983 private:
984 ConcurrentCopying* collector_;
985};
986
987// Compute how much live objects are left in regions.
988void ConcurrentCopying::ComputeUnevacFromSpaceLiveRatio() {
989 region_space_->AssertAllRegionLiveBytesZeroOrCleared();
990 ConcurrentCopyingComputeUnevacFromSpaceLiveRatioVisitor visitor(this);
991 region_space_bitmap_->VisitMarkedRange(reinterpret_cast<uintptr_t>(region_space_->Begin()),
992 reinterpret_cast<uintptr_t>(region_space_->Limit()),
993 visitor);
994}
995
996// Assert the to-space invariant.
997void ConcurrentCopying::AssertToSpaceInvariant(mirror::Object* obj, MemberOffset offset,
998 mirror::Object* ref) {
999 CHECK(heap_->collector_type_ == kCollectorTypeCC) << static_cast<size_t>(heap_->collector_type_);
1000 if (is_asserting_to_space_invariant_) {
1001 if (region_space_->IsInToSpace(ref)) {
1002 // OK.
1003 return;
1004 } else if (region_space_->IsInUnevacFromSpace(ref)) {
1005 CHECK(region_space_bitmap_->Test(ref)) << ref;
1006 } else if (region_space_->IsInFromSpace(ref)) {
1007 // Not OK. Do extra logging.
1008 if (obj != nullptr) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001009 LogFromSpaceRefHolder(obj, offset);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001010 }
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001011 ref->GetLockWord(false).Dump(LOG(INTERNAL_FATAL));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001012 CHECK(false) << "Found from-space ref " << ref << " " << PrettyTypeOf(ref);
1013 } else {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001014 AssertToSpaceInvariantInNonMovingSpace(obj, ref);
1015 }
1016 }
1017}
1018
1019class RootPrinter {
1020 public:
1021 RootPrinter() { }
1022
1023 template <class MirrorType>
1024 ALWAYS_INLINE void VisitRootIfNonNull(mirror::CompressedReference<MirrorType>* root)
1025 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1026 if (!root->IsNull()) {
1027 VisitRoot(root);
1028 }
1029 }
1030
1031 template <class MirrorType>
1032 void VisitRoot(mirror::Object** root)
1033 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1034 LOG(INTERNAL_FATAL) << "root=" << root << " ref=" << *root;
1035 }
1036
1037 template <class MirrorType>
1038 void VisitRoot(mirror::CompressedReference<MirrorType>* root)
1039 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1040 LOG(INTERNAL_FATAL) << "root=" << root << " ref=" << root->AsMirrorPtr();
1041 }
1042};
1043
1044void ConcurrentCopying::AssertToSpaceInvariant(GcRootSource* gc_root_source,
1045 mirror::Object* ref) {
1046 CHECK(heap_->collector_type_ == kCollectorTypeCC) << static_cast<size_t>(heap_->collector_type_);
1047 if (is_asserting_to_space_invariant_) {
1048 if (region_space_->IsInToSpace(ref)) {
1049 // OK.
1050 return;
1051 } else if (region_space_->IsInUnevacFromSpace(ref)) {
1052 CHECK(region_space_bitmap_->Test(ref)) << ref;
1053 } else if (region_space_->IsInFromSpace(ref)) {
1054 // Not OK. Do extra logging.
1055 if (gc_root_source == nullptr) {
1056 // No info.
1057 } else if (gc_root_source->HasArtField()) {
1058 ArtField* field = gc_root_source->GetArtField();
1059 LOG(INTERNAL_FATAL) << "gc root in field " << field << " " << PrettyField(field);
1060 RootPrinter root_printer;
1061 field->VisitRoots(root_printer);
1062 } else if (gc_root_source->HasArtMethod()) {
1063 ArtMethod* method = gc_root_source->GetArtMethod();
1064 LOG(INTERNAL_FATAL) << "gc root in method " << method << " " << PrettyMethod(method);
1065 RootPrinter root_printer;
1066 method->VisitRoots(root_printer);
1067 }
1068 ref->GetLockWord(false).Dump(LOG(INTERNAL_FATAL));
1069 region_space_->DumpNonFreeRegions(LOG(INTERNAL_FATAL));
1070 PrintFileToLog("/proc/self/maps", LogSeverity::INTERNAL_FATAL);
1071 MemMap::DumpMaps(LOG(INTERNAL_FATAL), true);
1072 CHECK(false) << "Found from-space ref " << ref << " " << PrettyTypeOf(ref);
1073 } else {
1074 AssertToSpaceInvariantInNonMovingSpace(nullptr, ref);
1075 }
1076 }
1077}
1078
1079void ConcurrentCopying::LogFromSpaceRefHolder(mirror::Object* obj, MemberOffset offset) {
1080 if (kUseBakerReadBarrier) {
1081 LOG(INFO) << "holder=" << obj << " " << PrettyTypeOf(obj)
1082 << " holder rb_ptr=" << obj->GetReadBarrierPointer();
1083 } else {
1084 LOG(INFO) << "holder=" << obj << " " << PrettyTypeOf(obj);
1085 }
1086 if (region_space_->IsInFromSpace(obj)) {
1087 LOG(INFO) << "holder is in the from-space.";
1088 } else if (region_space_->IsInToSpace(obj)) {
1089 LOG(INFO) << "holder is in the to-space.";
1090 } else if (region_space_->IsInUnevacFromSpace(obj)) {
1091 LOG(INFO) << "holder is in the unevac from-space.";
1092 if (region_space_bitmap_->Test(obj)) {
1093 LOG(INFO) << "holder is marked in the region space bitmap.";
1094 } else {
1095 LOG(INFO) << "holder is not marked in the region space bitmap.";
1096 }
1097 } else {
1098 // In a non-moving space.
1099 if (immune_region_.ContainsObject(obj)) {
1100 LOG(INFO) << "holder is in the image or the zygote space.";
1101 accounting::ContinuousSpaceBitmap* cc_bitmap =
1102 cc_heap_bitmap_->GetContinuousSpaceBitmap(obj);
1103 CHECK(cc_bitmap != nullptr)
1104 << "An immune space object must have a bitmap.";
1105 if (cc_bitmap->Test(obj)) {
1106 LOG(INFO) << "holder is marked in the bit map.";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001107 } else {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001108 LOG(INFO) << "holder is NOT marked in the bit map.";
1109 }
1110 } else {
1111 LOG(INFO) << "holder is in a non-moving (or main) space.";
1112 accounting::ContinuousSpaceBitmap* mark_bitmap =
1113 heap_mark_bitmap_->GetContinuousSpaceBitmap(obj);
1114 accounting::LargeObjectBitmap* los_bitmap =
1115 heap_mark_bitmap_->GetLargeObjectBitmap(obj);
1116 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
1117 bool is_los = mark_bitmap == nullptr;
1118 if (!is_los && mark_bitmap->Test(obj)) {
1119 LOG(INFO) << "holder is marked in the mark bit map.";
1120 } else if (is_los && los_bitmap->Test(obj)) {
1121 LOG(INFO) << "holder is marked in the los bit map.";
1122 } else {
1123 // If ref is on the allocation stack, then it is considered
1124 // mark/alive (but not necessarily on the live stack.)
1125 if (IsOnAllocStack(obj)) {
1126 LOG(INFO) << "holder is on the alloc stack.";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001127 } else {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001128 LOG(INFO) << "holder is not marked or on the alloc stack.";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001129 }
1130 }
1131 }
1132 }
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001133 LOG(INFO) << "offset=" << offset.SizeValue();
1134}
1135
1136void ConcurrentCopying::AssertToSpaceInvariantInNonMovingSpace(mirror::Object* obj,
1137 mirror::Object* ref) {
1138 // In a non-moving spaces. Check that the ref is marked.
1139 if (immune_region_.ContainsObject(ref)) {
1140 accounting::ContinuousSpaceBitmap* cc_bitmap =
1141 cc_heap_bitmap_->GetContinuousSpaceBitmap(ref);
1142 CHECK(cc_bitmap != nullptr)
1143 << "An immune space ref must have a bitmap. " << ref;
1144 if (kUseBakerReadBarrier) {
1145 CHECK(cc_bitmap->Test(ref))
1146 << "Unmarked immune space ref. obj=" << obj << " rb_ptr="
1147 << obj->GetReadBarrierPointer() << " ref=" << ref;
1148 } else {
1149 CHECK(cc_bitmap->Test(ref))
1150 << "Unmarked immune space ref. obj=" << obj << " ref=" << ref;
1151 }
1152 } else {
1153 accounting::ContinuousSpaceBitmap* mark_bitmap =
1154 heap_mark_bitmap_->GetContinuousSpaceBitmap(ref);
1155 accounting::LargeObjectBitmap* los_bitmap =
1156 heap_mark_bitmap_->GetLargeObjectBitmap(ref);
1157 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
1158 bool is_los = mark_bitmap == nullptr;
1159 if ((!is_los && mark_bitmap->Test(ref)) ||
1160 (is_los && los_bitmap->Test(ref))) {
1161 // OK.
1162 } else {
1163 // If ref is on the allocation stack, then it may not be
1164 // marked live, but considered marked/alive (but not
1165 // necessarily on the live stack).
1166 CHECK(IsOnAllocStack(ref)) << "Unmarked ref that's not on the allocation stack. "
1167 << "obj=" << obj << " ref=" << ref;
1168 }
1169 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001170}
1171
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001172// Used to scan ref fields of an object.
1173class ConcurrentCopyingRefFieldsVisitor {
1174 public:
1175 explicit ConcurrentCopyingRefFieldsVisitor(ConcurrentCopying* collector)
1176 : collector_(collector) {}
1177
1178 void operator()(mirror::Object* obj, MemberOffset offset, bool /* is_static */)
1179 const ALWAYS_INLINE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1180 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
1181 collector_->Process(obj, offset);
1182 }
1183
1184 void operator()(mirror::Class* klass, mirror::Reference* ref) const
1185 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) ALWAYS_INLINE {
1186 CHECK(klass->IsTypeOfReferenceClass());
1187 collector_->DelayReferenceReferent(klass, ref);
1188 }
1189
1190 private:
1191 ConcurrentCopying* const collector_;
1192};
1193
1194// Scan ref fields of an object.
1195void ConcurrentCopying::Scan(mirror::Object* to_ref) {
1196 DCHECK(!region_space_->IsInFromSpace(to_ref));
1197 ConcurrentCopyingRefFieldsVisitor visitor(this);
1198 to_ref->VisitReferences<true>(visitor, visitor);
1199}
1200
1201// Process a field.
1202inline void ConcurrentCopying::Process(mirror::Object* obj, MemberOffset offset) {
1203 mirror::Object* ref = obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier, false>(offset);
1204 if (ref == nullptr || region_space_->IsInToSpace(ref)) {
1205 return;
1206 }
1207 mirror::Object* to_ref = Mark(ref);
1208 if (to_ref == ref) {
1209 return;
1210 }
1211 // This may fail if the mutator writes to the field at the same time. But it's ok.
1212 mirror::Object* expected_ref = ref;
1213 mirror::Object* new_ref = to_ref;
1214 do {
1215 if (expected_ref !=
1216 obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier, false>(offset)) {
1217 // It was updated by the mutator.
1218 break;
1219 }
1220 } while (!obj->CasFieldWeakSequentiallyConsistentObjectWithoutWriteBarrier<false, false, kVerifyNone>(
1221 offset, expected_ref, new_ref));
1222}
1223
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001224// Process some roots.
1225void ConcurrentCopying::VisitRoots(
1226 mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED) {
1227 for (size_t i = 0; i < count; ++i) {
1228 mirror::Object** root = roots[i];
1229 mirror::Object* ref = *root;
1230 if (ref == nullptr || region_space_->IsInToSpace(ref)) {
Mathieu Chartier4809d0a2015-04-07 10:39:04 -07001231 continue;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001232 }
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001233 mirror::Object* to_ref = Mark(ref);
1234 if (to_ref == ref) {
Mathieu Chartier4809d0a2015-04-07 10:39:04 -07001235 continue;
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001236 }
1237 Atomic<mirror::Object*>* addr = reinterpret_cast<Atomic<mirror::Object*>*>(root);
1238 mirror::Object* expected_ref = ref;
1239 mirror::Object* new_ref = to_ref;
1240 do {
1241 if (expected_ref != addr->LoadRelaxed()) {
1242 // It was updated by the mutator.
1243 break;
1244 }
1245 } while (!addr->CompareExchangeWeakSequentiallyConsistent(expected_ref, new_ref));
1246 }
1247}
1248
1249void ConcurrentCopying::VisitRoots(
1250 mirror::CompressedReference<mirror::Object>** roots, size_t count,
1251 const RootInfo& info ATTRIBUTE_UNUSED) {
1252 for (size_t i = 0; i < count; ++i) {
1253 mirror::CompressedReference<mirror::Object>* root = roots[i];
1254 mirror::Object* ref = root->AsMirrorPtr();
1255 if (ref == nullptr || region_space_->IsInToSpace(ref)) {
Mathieu Chartier4809d0a2015-04-07 10:39:04 -07001256 continue;
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001257 }
1258 mirror::Object* to_ref = Mark(ref);
1259 if (to_ref == ref) {
Mathieu Chartier4809d0a2015-04-07 10:39:04 -07001260 continue;
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001261 }
1262 auto* addr = reinterpret_cast<Atomic<mirror::CompressedReference<mirror::Object>>*>(root);
1263 auto expected_ref = mirror::CompressedReference<mirror::Object>::FromMirrorPtr(ref);
1264 auto new_ref = mirror::CompressedReference<mirror::Object>::FromMirrorPtr(to_ref);
1265 do {
1266 if (ref != addr->LoadRelaxed().AsMirrorPtr()) {
1267 // It was updated by the mutator.
1268 break;
1269 }
1270 } while (!addr->CompareExchangeWeakSequentiallyConsistent(expected_ref, new_ref));
1271 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001272}
1273
1274// Fill the given memory block with a dummy object. Used to fill in a
1275// copy of objects that was lost in race.
1276void ConcurrentCopying::FillWithDummyObject(mirror::Object* dummy_obj, size_t byte_size) {
1277 CHECK(IsAligned<kObjectAlignment>(byte_size));
1278 memset(dummy_obj, 0, byte_size);
1279 mirror::Class* int_array_class = mirror::IntArray::GetArrayClass();
1280 CHECK(int_array_class != nullptr);
1281 AssertToSpaceInvariant(nullptr, MemberOffset(0), int_array_class);
1282 size_t component_size = int_array_class->GetComponentSize();
1283 CHECK_EQ(component_size, sizeof(int32_t));
1284 size_t data_offset = mirror::Array::DataOffset(component_size).SizeValue();
1285 if (data_offset > byte_size) {
1286 // An int array is too big. Use java.lang.Object.
1287 mirror::Class* java_lang_Object = WellKnownClasses::ToClass(WellKnownClasses::java_lang_Object);
1288 AssertToSpaceInvariant(nullptr, MemberOffset(0), java_lang_Object);
1289 CHECK_EQ(byte_size, java_lang_Object->GetObjectSize());
1290 dummy_obj->SetClass(java_lang_Object);
1291 CHECK_EQ(byte_size, dummy_obj->SizeOf());
1292 } else {
1293 // Use an int array.
1294 dummy_obj->SetClass(int_array_class);
1295 CHECK(dummy_obj->IsArrayInstance());
1296 int32_t length = (byte_size - data_offset) / component_size;
1297 dummy_obj->AsArray()->SetLength(length);
1298 CHECK_EQ(dummy_obj->AsArray()->GetLength(), length)
1299 << "byte_size=" << byte_size << " length=" << length
1300 << " component_size=" << component_size << " data_offset=" << data_offset;
1301 CHECK_EQ(byte_size, dummy_obj->SizeOf())
1302 << "byte_size=" << byte_size << " length=" << length
1303 << " component_size=" << component_size << " data_offset=" << data_offset;
1304 }
1305}
1306
1307// Reuse the memory blocks that were copy of objects that were lost in race.
1308mirror::Object* ConcurrentCopying::AllocateInSkippedBlock(size_t alloc_size) {
1309 // Try to reuse the blocks that were unused due to CAS failures.
1310 CHECK(IsAligned<space::RegionSpace::kAlignment>(alloc_size));
1311 Thread* self = Thread::Current();
1312 size_t min_object_size = RoundUp(sizeof(mirror::Object), space::RegionSpace::kAlignment);
1313 MutexLock mu(self, skipped_blocks_lock_);
1314 auto it = skipped_blocks_map_.lower_bound(alloc_size);
1315 if (it == skipped_blocks_map_.end()) {
1316 // Not found.
1317 return nullptr;
1318 }
1319 {
1320 size_t byte_size = it->first;
1321 CHECK_GE(byte_size, alloc_size);
1322 if (byte_size > alloc_size && byte_size - alloc_size < min_object_size) {
1323 // If remainder would be too small for a dummy object, retry with a larger request size.
1324 it = skipped_blocks_map_.lower_bound(alloc_size + min_object_size);
1325 if (it == skipped_blocks_map_.end()) {
1326 // Not found.
1327 return nullptr;
1328 }
1329 CHECK(IsAligned<space::RegionSpace::kAlignment>(it->first - alloc_size));
1330 CHECK_GE(it->first - alloc_size, min_object_size)
1331 << "byte_size=" << byte_size << " it->first=" << it->first << " alloc_size=" << alloc_size;
1332 }
1333 }
1334 // Found a block.
1335 CHECK(it != skipped_blocks_map_.end());
1336 size_t byte_size = it->first;
1337 uint8_t* addr = it->second;
1338 CHECK_GE(byte_size, alloc_size);
1339 CHECK(region_space_->IsInToSpace(reinterpret_cast<mirror::Object*>(addr)));
1340 CHECK(IsAligned<space::RegionSpace::kAlignment>(byte_size));
1341 if (kVerboseMode) {
1342 LOG(INFO) << "Reusing skipped bytes : " << reinterpret_cast<void*>(addr) << ", " << byte_size;
1343 }
1344 skipped_blocks_map_.erase(it);
1345 memset(addr, 0, byte_size);
1346 if (byte_size > alloc_size) {
1347 // Return the remainder to the map.
1348 CHECK(IsAligned<space::RegionSpace::kAlignment>(byte_size - alloc_size));
1349 CHECK_GE(byte_size - alloc_size, min_object_size);
1350 FillWithDummyObject(reinterpret_cast<mirror::Object*>(addr + alloc_size),
1351 byte_size - alloc_size);
1352 CHECK(region_space_->IsInToSpace(reinterpret_cast<mirror::Object*>(addr + alloc_size)));
1353 skipped_blocks_map_.insert(std::make_pair(byte_size - alloc_size, addr + alloc_size));
1354 }
1355 return reinterpret_cast<mirror::Object*>(addr);
1356}
1357
1358mirror::Object* ConcurrentCopying::Copy(mirror::Object* from_ref) {
1359 DCHECK(region_space_->IsInFromSpace(from_ref));
1360 // No read barrier to avoid nested RB that might violate the to-space
1361 // invariant. Note that from_ref is a from space ref so the SizeOf()
1362 // call will access the from-space meta objects, but it's ok and necessary.
1363 size_t obj_size = from_ref->SizeOf<kDefaultVerifyFlags, kWithoutReadBarrier>();
1364 size_t region_space_alloc_size = RoundUp(obj_size, space::RegionSpace::kAlignment);
1365 size_t region_space_bytes_allocated = 0U;
1366 size_t non_moving_space_bytes_allocated = 0U;
1367 size_t bytes_allocated = 0U;
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001368 size_t dummy;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001369 mirror::Object* to_ref = region_space_->AllocNonvirtual<true>(
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001370 region_space_alloc_size, &region_space_bytes_allocated, nullptr, &dummy);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001371 bytes_allocated = region_space_bytes_allocated;
1372 if (to_ref != nullptr) {
1373 DCHECK_EQ(region_space_alloc_size, region_space_bytes_allocated);
1374 }
1375 bool fall_back_to_non_moving = false;
1376 if (UNLIKELY(to_ref == nullptr)) {
1377 // Failed to allocate in the region space. Try the skipped blocks.
1378 to_ref = AllocateInSkippedBlock(region_space_alloc_size);
1379 if (to_ref != nullptr) {
1380 // Succeeded to allocate in a skipped block.
1381 if (heap_->use_tlab_) {
1382 // This is necessary for the tlab case as it's not accounted in the space.
1383 region_space_->RecordAlloc(to_ref);
1384 }
1385 bytes_allocated = region_space_alloc_size;
1386 } else {
1387 // Fall back to the non-moving space.
1388 fall_back_to_non_moving = true;
1389 if (kVerboseMode) {
1390 LOG(INFO) << "Out of memory in the to-space. Fall back to non-moving. skipped_bytes="
1391 << to_space_bytes_skipped_.LoadSequentiallyConsistent()
1392 << " skipped_objects=" << to_space_objects_skipped_.LoadSequentiallyConsistent();
1393 }
1394 fall_back_to_non_moving = true;
1395 to_ref = heap_->non_moving_space_->Alloc(Thread::Current(), obj_size,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001396 &non_moving_space_bytes_allocated, nullptr, &dummy);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001397 CHECK(to_ref != nullptr) << "Fall-back non-moving space allocation failed";
1398 bytes_allocated = non_moving_space_bytes_allocated;
1399 // Mark it in the mark bitmap.
1400 accounting::ContinuousSpaceBitmap* mark_bitmap =
1401 heap_mark_bitmap_->GetContinuousSpaceBitmap(to_ref);
1402 CHECK(mark_bitmap != nullptr);
1403 CHECK(!mark_bitmap->AtomicTestAndSet(to_ref));
1404 }
1405 }
1406 DCHECK(to_ref != nullptr);
1407
1408 // Attempt to install the forward pointer. This is in a loop as the
1409 // lock word atomic write can fail.
1410 while (true) {
1411 // Copy the object. TODO: copy only the lockword in the second iteration and on?
1412 memcpy(to_ref, from_ref, obj_size);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001413
1414 LockWord old_lock_word = to_ref->GetLockWord(false);
1415
1416 if (old_lock_word.GetState() == LockWord::kForwardingAddress) {
1417 // Lost the race. Another thread (either GC or mutator) stored
1418 // the forwarding pointer first. Make the lost copy (to_ref)
1419 // look like a valid but dead (dummy) object and keep it for
1420 // future reuse.
1421 FillWithDummyObject(to_ref, bytes_allocated);
1422 if (!fall_back_to_non_moving) {
1423 DCHECK(region_space_->IsInToSpace(to_ref));
1424 if (bytes_allocated > space::RegionSpace::kRegionSize) {
1425 // Free the large alloc.
1426 region_space_->FreeLarge(to_ref, bytes_allocated);
1427 } else {
1428 // Record the lost copy for later reuse.
1429 heap_->num_bytes_allocated_.FetchAndAddSequentiallyConsistent(bytes_allocated);
1430 to_space_bytes_skipped_.FetchAndAddSequentiallyConsistent(bytes_allocated);
1431 to_space_objects_skipped_.FetchAndAddSequentiallyConsistent(1);
1432 MutexLock mu(Thread::Current(), skipped_blocks_lock_);
1433 skipped_blocks_map_.insert(std::make_pair(bytes_allocated,
1434 reinterpret_cast<uint8_t*>(to_ref)));
1435 }
1436 } else {
1437 DCHECK(heap_->non_moving_space_->HasAddress(to_ref));
1438 DCHECK_EQ(bytes_allocated, non_moving_space_bytes_allocated);
1439 // Free the non-moving-space chunk.
1440 accounting::ContinuousSpaceBitmap* mark_bitmap =
1441 heap_mark_bitmap_->GetContinuousSpaceBitmap(to_ref);
1442 CHECK(mark_bitmap != nullptr);
1443 CHECK(mark_bitmap->Clear(to_ref));
1444 heap_->non_moving_space_->Free(Thread::Current(), to_ref);
1445 }
1446
1447 // Get the winner's forward ptr.
1448 mirror::Object* lost_fwd_ptr = to_ref;
1449 to_ref = reinterpret_cast<mirror::Object*>(old_lock_word.ForwardingAddress());
1450 CHECK(to_ref != nullptr);
1451 CHECK_NE(to_ref, lost_fwd_ptr);
1452 CHECK(region_space_->IsInToSpace(to_ref) || heap_->non_moving_space_->HasAddress(to_ref));
1453 CHECK_NE(to_ref->GetLockWord(false).GetState(), LockWord::kForwardingAddress);
1454 return to_ref;
1455 }
1456
Hiroshi Yamauchi60f63f52015-04-23 16:12:40 -07001457 // Set the gray ptr.
1458 if (kUseBakerReadBarrier) {
1459 to_ref->SetReadBarrierPointer(ReadBarrier::GrayPtr());
1460 }
1461
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001462 LockWord new_lock_word = LockWord::FromForwardingAddress(reinterpret_cast<size_t>(to_ref));
1463
1464 // Try to atomically write the fwd ptr.
1465 bool success = from_ref->CasLockWordWeakSequentiallyConsistent(old_lock_word, new_lock_word);
1466 if (LIKELY(success)) {
1467 // The CAS succeeded.
1468 objects_moved_.FetchAndAddSequentiallyConsistent(1);
1469 bytes_moved_.FetchAndAddSequentiallyConsistent(region_space_alloc_size);
1470 if (LIKELY(!fall_back_to_non_moving)) {
1471 DCHECK(region_space_->IsInToSpace(to_ref));
1472 } else {
1473 DCHECK(heap_->non_moving_space_->HasAddress(to_ref));
1474 DCHECK_EQ(bytes_allocated, non_moving_space_bytes_allocated);
1475 }
1476 if (kUseBakerReadBarrier) {
1477 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr());
1478 }
1479 DCHECK(GetFwdPtr(from_ref) == to_ref);
1480 CHECK_NE(to_ref->GetLockWord(false).GetState(), LockWord::kForwardingAddress);
1481 PushOntoMarkStack<true>(to_ref);
1482 return to_ref;
1483 } else {
1484 // The CAS failed. It may have lost the race or may have failed
1485 // due to monitor/hashcode ops. Either way, retry.
1486 }
1487 }
1488}
1489
1490mirror::Object* ConcurrentCopying::IsMarked(mirror::Object* from_ref) {
1491 DCHECK(from_ref != nullptr);
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08001492 space::RegionSpace::RegionType rtype = region_space_->GetRegionType(from_ref);
1493 if (rtype == space::RegionSpace::RegionType::kRegionTypeToSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001494 // It's already marked.
1495 return from_ref;
1496 }
1497 mirror::Object* to_ref;
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08001498 if (rtype == space::RegionSpace::RegionType::kRegionTypeFromSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001499 to_ref = GetFwdPtr(from_ref);
1500 DCHECK(to_ref == nullptr || region_space_->IsInToSpace(to_ref) ||
1501 heap_->non_moving_space_->HasAddress(to_ref))
1502 << "from_ref=" << from_ref << " to_ref=" << to_ref;
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08001503 } else if (rtype == space::RegionSpace::RegionType::kRegionTypeUnevacFromSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001504 if (region_space_bitmap_->Test(from_ref)) {
1505 to_ref = from_ref;
1506 } else {
1507 to_ref = nullptr;
1508 }
1509 } else {
1510 // from_ref is in a non-moving space.
1511 if (immune_region_.ContainsObject(from_ref)) {
1512 accounting::ContinuousSpaceBitmap* cc_bitmap =
1513 cc_heap_bitmap_->GetContinuousSpaceBitmap(from_ref);
1514 DCHECK(cc_bitmap != nullptr)
1515 << "An immune space object must have a bitmap";
1516 if (kIsDebugBuild) {
1517 DCHECK(heap_mark_bitmap_->GetContinuousSpaceBitmap(from_ref)->Test(from_ref))
1518 << "Immune space object must be already marked";
1519 }
1520 if (cc_bitmap->Test(from_ref)) {
1521 // Already marked.
1522 to_ref = from_ref;
1523 } else {
1524 // Newly marked.
1525 to_ref = nullptr;
1526 }
1527 } else {
1528 // Non-immune non-moving space. Use the mark bitmap.
1529 accounting::ContinuousSpaceBitmap* mark_bitmap =
1530 heap_mark_bitmap_->GetContinuousSpaceBitmap(from_ref);
1531 accounting::LargeObjectBitmap* los_bitmap =
1532 heap_mark_bitmap_->GetLargeObjectBitmap(from_ref);
1533 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
1534 bool is_los = mark_bitmap == nullptr;
1535 if (!is_los && mark_bitmap->Test(from_ref)) {
1536 // Already marked.
1537 to_ref = from_ref;
1538 } else if (is_los && los_bitmap->Test(from_ref)) {
1539 // Already marked in LOS.
1540 to_ref = from_ref;
1541 } else {
1542 // Not marked.
1543 if (IsOnAllocStack(from_ref)) {
1544 // If on the allocation stack, it's considered marked.
1545 to_ref = from_ref;
1546 } else {
1547 // Not marked.
1548 to_ref = nullptr;
1549 }
1550 }
1551 }
1552 }
1553 return to_ref;
1554}
1555
1556bool ConcurrentCopying::IsOnAllocStack(mirror::Object* ref) {
1557 QuasiAtomic::ThreadFenceAcquire();
1558 accounting::ObjectStack* alloc_stack = GetAllocationStack();
Mathieu Chartiercb535da2015-01-23 13:50:03 -08001559 return alloc_stack->Contains(ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001560}
1561
1562mirror::Object* ConcurrentCopying::Mark(mirror::Object* from_ref) {
1563 if (from_ref == nullptr) {
1564 return nullptr;
1565 }
1566 DCHECK(from_ref != nullptr);
1567 DCHECK(heap_->collector_type_ == kCollectorTypeCC);
Hiroshi Yamauchi60f63f52015-04-23 16:12:40 -07001568 if (kUseBakerReadBarrier && !is_active_) {
1569 // In the lock word forward address state, the read barrier bits
1570 // in the lock word are part of the stored forwarding address and
1571 // invalid. This is usually OK as the from-space copy of objects
1572 // aren't accessed by mutators due to the to-space
1573 // invariant. However, during the dex2oat image writing relocation
1574 // and the zygote compaction, objects can be in the forward
1575 // address state (to store the forward/relocation addresses) and
1576 // they can still be accessed and the invalid read barrier bits
1577 // are consulted. If they look like gray but aren't really, the
1578 // read barriers slow path can trigger when it shouldn't. To guard
1579 // against this, return here if the CC collector isn't running.
1580 return from_ref;
1581 }
1582 DCHECK(region_space_ != nullptr) << "Read barrier slow path taken when CC isn't running?";
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08001583 space::RegionSpace::RegionType rtype = region_space_->GetRegionType(from_ref);
1584 if (rtype == space::RegionSpace::RegionType::kRegionTypeToSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001585 // It's already marked.
1586 return from_ref;
1587 }
1588 mirror::Object* to_ref;
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08001589 if (rtype == space::RegionSpace::RegionType::kRegionTypeFromSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001590 to_ref = GetFwdPtr(from_ref);
1591 if (kUseBakerReadBarrier) {
1592 DCHECK(to_ref != ReadBarrier::GrayPtr()) << "from_ref=" << from_ref << " to_ref=" << to_ref;
1593 }
1594 if (to_ref == nullptr) {
1595 // It isn't marked yet. Mark it by copying it to the to-space.
1596 to_ref = Copy(from_ref);
1597 }
1598 DCHECK(region_space_->IsInToSpace(to_ref) || heap_->non_moving_space_->HasAddress(to_ref))
1599 << "from_ref=" << from_ref << " to_ref=" << to_ref;
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08001600 } else if (rtype == space::RegionSpace::RegionType::kRegionTypeUnevacFromSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001601 // This may or may not succeed, which is ok.
1602 if (kUseBakerReadBarrier) {
1603 from_ref->AtomicSetReadBarrierPointer(ReadBarrier::WhitePtr(), ReadBarrier::GrayPtr());
1604 }
1605 if (region_space_bitmap_->AtomicTestAndSet(from_ref)) {
1606 // Already marked.
1607 to_ref = from_ref;
1608 } else {
1609 // Newly marked.
1610 to_ref = from_ref;
1611 if (kUseBakerReadBarrier) {
1612 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr());
1613 }
1614 PushOntoMarkStack<true>(to_ref);
1615 }
1616 } else {
1617 // from_ref is in a non-moving space.
1618 DCHECK(!region_space_->HasAddress(from_ref)) << from_ref;
1619 if (immune_region_.ContainsObject(from_ref)) {
1620 accounting::ContinuousSpaceBitmap* cc_bitmap =
1621 cc_heap_bitmap_->GetContinuousSpaceBitmap(from_ref);
1622 DCHECK(cc_bitmap != nullptr)
1623 << "An immune space object must have a bitmap";
1624 if (kIsDebugBuild) {
1625 DCHECK(heap_mark_bitmap_->GetContinuousSpaceBitmap(from_ref)->Test(from_ref))
1626 << "Immune space object must be already marked";
1627 }
1628 // This may or may not succeed, which is ok.
1629 if (kUseBakerReadBarrier) {
1630 from_ref->AtomicSetReadBarrierPointer(ReadBarrier::WhitePtr(), ReadBarrier::GrayPtr());
1631 }
1632 if (cc_bitmap->AtomicTestAndSet(from_ref)) {
1633 // Already marked.
1634 to_ref = from_ref;
1635 } else {
1636 // Newly marked.
1637 to_ref = from_ref;
1638 if (kUseBakerReadBarrier) {
1639 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr());
1640 }
1641 PushOntoMarkStack<true>(to_ref);
1642 }
1643 } else {
1644 // Use the mark bitmap.
1645 accounting::ContinuousSpaceBitmap* mark_bitmap =
1646 heap_mark_bitmap_->GetContinuousSpaceBitmap(from_ref);
1647 accounting::LargeObjectBitmap* los_bitmap =
1648 heap_mark_bitmap_->GetLargeObjectBitmap(from_ref);
1649 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
1650 bool is_los = mark_bitmap == nullptr;
1651 if (!is_los && mark_bitmap->Test(from_ref)) {
1652 // Already marked.
1653 to_ref = from_ref;
1654 if (kUseBakerReadBarrier) {
1655 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr() ||
1656 to_ref->GetReadBarrierPointer() == ReadBarrier::BlackPtr());
1657 }
1658 } else if (is_los && los_bitmap->Test(from_ref)) {
1659 // Already marked in LOS.
1660 to_ref = from_ref;
1661 if (kUseBakerReadBarrier) {
1662 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr() ||
1663 to_ref->GetReadBarrierPointer() == ReadBarrier::BlackPtr());
1664 }
1665 } else {
1666 // Not marked.
1667 if (IsOnAllocStack(from_ref)) {
1668 // If it's on the allocation stack, it's considered marked. Keep it white.
1669 to_ref = from_ref;
1670 // Objects on the allocation stack need not be marked.
1671 if (!is_los) {
1672 DCHECK(!mark_bitmap->Test(to_ref));
1673 } else {
1674 DCHECK(!los_bitmap->Test(to_ref));
1675 }
1676 if (kUseBakerReadBarrier) {
1677 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::WhitePtr());
1678 }
1679 } else {
1680 // Not marked or on the allocation stack. Try to mark it.
1681 // This may or may not succeed, which is ok.
1682 if (kUseBakerReadBarrier) {
1683 from_ref->AtomicSetReadBarrierPointer(ReadBarrier::WhitePtr(), ReadBarrier::GrayPtr());
1684 }
1685 if (!is_los && mark_bitmap->AtomicTestAndSet(from_ref)) {
1686 // Already marked.
1687 to_ref = from_ref;
1688 } else if (is_los && los_bitmap->AtomicTestAndSet(from_ref)) {
1689 // Already marked in LOS.
1690 to_ref = from_ref;
1691 } else {
1692 // Newly marked.
1693 to_ref = from_ref;
1694 if (kUseBakerReadBarrier) {
1695 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr());
1696 }
1697 PushOntoMarkStack<true>(to_ref);
1698 }
1699 }
1700 }
1701 }
1702 }
1703 return to_ref;
1704}
1705
1706void ConcurrentCopying::FinishPhase() {
1707 region_space_ = nullptr;
1708 CHECK(mark_queue_.IsEmpty());
1709 mark_queue_.Clear();
1710 {
1711 MutexLock mu(Thread::Current(), skipped_blocks_lock_);
1712 skipped_blocks_map_.clear();
1713 }
1714 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
1715 heap_->ClearMarkedObjects();
1716}
1717
1718mirror::Object* ConcurrentCopying::IsMarkedCallback(mirror::Object* from_ref, void* arg) {
1719 return reinterpret_cast<ConcurrentCopying*>(arg)->IsMarked(from_ref);
1720}
1721
1722bool ConcurrentCopying::IsHeapReferenceMarkedCallback(
1723 mirror::HeapReference<mirror::Object>* field, void* arg) {
1724 mirror::Object* from_ref = field->AsMirrorPtr();
1725 mirror::Object* to_ref = reinterpret_cast<ConcurrentCopying*>(arg)->IsMarked(from_ref);
1726 if (to_ref == nullptr) {
1727 return false;
1728 }
1729 if (from_ref != to_ref) {
1730 QuasiAtomic::ThreadFenceRelease();
1731 field->Assign(to_ref);
1732 QuasiAtomic::ThreadFenceSequentiallyConsistent();
1733 }
1734 return true;
1735}
1736
1737mirror::Object* ConcurrentCopying::MarkCallback(mirror::Object* from_ref, void* arg) {
1738 return reinterpret_cast<ConcurrentCopying*>(arg)->Mark(from_ref);
1739}
1740
1741void ConcurrentCopying::ProcessMarkStackCallback(void* arg) {
1742 reinterpret_cast<ConcurrentCopying*>(arg)->ProcessMarkStack();
1743}
1744
1745void ConcurrentCopying::DelayReferenceReferent(mirror::Class* klass, mirror::Reference* reference) {
1746 heap_->GetReferenceProcessor()->DelayReferenceReferent(
1747 klass, reference, &IsHeapReferenceMarkedCallback, this);
1748}
1749
1750void ConcurrentCopying::ProcessReferences(Thread* self, bool concurrent) {
1751 TimingLogger::ScopedTiming split("ProcessReferences", GetTimings());
1752 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1753 GetHeap()->GetReferenceProcessor()->ProcessReferences(
1754 concurrent, GetTimings(), GetCurrentIteration()->GetClearSoftReferences(),
1755 &IsHeapReferenceMarkedCallback, &MarkCallback, &ProcessMarkStackCallback, this);
1756}
1757
1758void ConcurrentCopying::RevokeAllThreadLocalBuffers() {
1759 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
1760 region_space_->RevokeAllThreadLocalBuffers();
1761}
1762
Hiroshi Yamauchid5307ec2014-03-27 21:07:51 -07001763} // namespace collector
1764} // namespace gc
1765} // namespace art