blob: d413a50534466853ea06345fb8d602a4ea562ee5 [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"
Mathieu Chartier56fe2582016-07-14 13:30:03 -070020#include "base/histogram-inl.h"
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070021#include "base/stl_util.h"
Mathieu Chartier56fe2582016-07-14 13:30:03 -070022#include "base/systrace.h"
Mathieu Chartiera6b1ead2015-10-06 10:32:38 -070023#include "debugger.h"
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080024#include "gc/accounting/heap_bitmap-inl.h"
Mathieu Chartier21328a12016-07-22 10:47:45 -070025#include "gc/accounting/mod_union_table-inl.h"
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080026#include "gc/accounting/space_bitmap-inl.h"
Mathieu Chartier3cf22532015-07-09 15:15:09 -070027#include "gc/reference_processor.h"
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080028#include "gc/space/image_space.h"
Mathieu Chartier073b16c2015-11-10 14:13:23 -080029#include "gc/space/space-inl.h"
Mathieu Chartier4a26f172016-01-26 14:26:18 -080030#include "image-inl.h"
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080031#include "intern_table.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070032#include "mirror/class-inl.h"
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080033#include "mirror/object-inl.h"
34#include "scoped_thread_state_change.h"
35#include "thread-inl.h"
36#include "thread_list.h"
37#include "well_known_classes.h"
38
Hiroshi Yamauchid5307ec2014-03-27 21:07:51 -070039namespace art {
40namespace gc {
41namespace collector {
42
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -070043static constexpr size_t kDefaultGcMarkStackSize = 2 * MB;
Mathieu Chartier21328a12016-07-22 10:47:45 -070044// If kGrayDirtyImmuneObjects is true then we gray dirty objects in the GC pause to prevent dirty
45// pages.
46static constexpr bool kGrayDirtyImmuneObjects = true;
47// If kFilterModUnionCards then we attempt to filter cards that don't need to be dirty in the mod
48// union table. Disabled since it does not seem to help the pause much.
49static constexpr bool kFilterModUnionCards = kIsDebugBuild;
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -070050
Mathieu Chartier56fe2582016-07-14 13:30:03 -070051ConcurrentCopying::ConcurrentCopying(Heap* heap,
52 const std::string& name_prefix,
53 bool measure_read_barrier_slow_path)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080054 : GarbageCollector(heap,
55 name_prefix + (name_prefix.empty() ? "" : " ") +
56 "concurrent copying + mark sweep"),
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070057 region_space_(nullptr), gc_barrier_(new Barrier(0)),
58 gc_mark_stack_(accounting::ObjectStack::Create("concurrent copying gc mark stack",
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -070059 kDefaultGcMarkStackSize,
60 kDefaultGcMarkStackSize)),
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070061 mark_stack_lock_("concurrent copying mark stack lock", kMarkSweepMarkStackLock),
62 thread_running_gc_(nullptr),
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080063 is_marking_(false), is_active_(false), is_asserting_to_space_invariant_(false),
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -070064 region_space_bitmap_(nullptr),
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070065 heap_mark_bitmap_(nullptr), live_stack_freeze_size_(0), mark_stack_mode_(kMarkStackModeOff),
66 weak_ref_access_enabled_(true),
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080067 skipped_blocks_lock_("concurrent copying bytes blocks lock", kMarkSweepMarkStackLock),
Mathieu Chartier56fe2582016-07-14 13:30:03 -070068 measure_read_barrier_slow_path_(measure_read_barrier_slow_path),
69 rb_slow_path_ns_(0),
70 rb_slow_path_count_(0),
71 rb_slow_path_count_gc_(0),
72 rb_slow_path_histogram_lock_("Read barrier histogram lock"),
73 rb_slow_path_time_histogram_("Mutator time in read barrier slow path", 500, 32),
74 rb_slow_path_count_total_(0),
75 rb_slow_path_count_gc_total_(0),
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080076 rb_table_(heap_->GetReadBarrierTable()),
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -070077 force_evacuate_all_(false),
78 immune_gray_stack_lock_("concurrent copying immune gray stack lock",
79 kMarkSweepMarkStackLock) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080080 static_assert(space::RegionSpace::kRegionSize == accounting::ReadBarrierTable::kRegionSize,
81 "The region space size and the read barrier table region size must match");
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070082 Thread* self = Thread::Current();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080083 {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080084 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
85 // Cache this so that we won't have to lock heap_bitmap_lock_ in
86 // Mark() which could cause a nested lock on heap_bitmap_lock_
87 // when GC causes a RB while doing GC or a lock order violation
88 // (class_linker_lock_ and heap_bitmap_lock_).
89 heap_mark_bitmap_ = heap->GetMarkBitmap();
90 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070091 {
92 MutexLock mu(self, mark_stack_lock_);
93 for (size_t i = 0; i < kMarkStackPoolSize; ++i) {
94 accounting::AtomicStack<mirror::Object>* mark_stack =
95 accounting::AtomicStack<mirror::Object>::Create(
96 "thread local mark stack", kMarkStackSize, kMarkStackSize);
97 pooled_mark_stacks_.push_back(mark_stack);
98 }
99 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800100}
101
Mathieu Chartierb19ccb12015-07-15 10:24:16 -0700102void ConcurrentCopying::MarkHeapReference(mirror::HeapReference<mirror::Object>* from_ref) {
103 // Used for preserving soft references, should be OK to not have a CAS here since there should be
104 // no other threads which can trigger read barriers on the same referent during reference
105 // processing.
106 from_ref->Assign(Mark(from_ref->AsMirrorPtr()));
Mathieu Chartier81187812015-07-15 14:24:07 -0700107 DCHECK(!from_ref->IsNull());
Mathieu Chartier97509952015-07-13 14:35:43 -0700108}
109
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800110ConcurrentCopying::~ConcurrentCopying() {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700111 STLDeleteElements(&pooled_mark_stacks_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800112}
113
114void ConcurrentCopying::RunPhases() {
115 CHECK(kUseBakerReadBarrier || kUseTableLookupReadBarrier);
116 CHECK(!is_active_);
117 is_active_ = true;
118 Thread* self = Thread::Current();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700119 thread_running_gc_ = self;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800120 Locks::mutator_lock_->AssertNotHeld(self);
121 {
122 ReaderMutexLock mu(self, *Locks::mutator_lock_);
123 InitializePhase();
124 }
125 FlipThreadRoots();
126 {
127 ReaderMutexLock mu(self, *Locks::mutator_lock_);
128 MarkingPhase();
129 }
130 // Verify no from space refs. This causes a pause.
131 if (kEnableNoFromSpaceRefsVerification || kIsDebugBuild) {
132 TimingLogger::ScopedTiming split("(Paused)VerifyNoFromSpaceReferences", GetTimings());
133 ScopedPause pause(this);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700134 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800135 if (kVerboseMode) {
136 LOG(INFO) << "Verifying no from-space refs";
137 }
138 VerifyNoFromSpaceReferences();
Mathieu Chartier720e71a2015-04-06 17:10:58 -0700139 if (kVerboseMode) {
140 LOG(INFO) << "Done verifying no from-space refs";
141 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700142 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800143 }
144 {
145 ReaderMutexLock mu(self, *Locks::mutator_lock_);
146 ReclaimPhase();
147 }
148 FinishPhase();
149 CHECK(is_active_);
150 is_active_ = false;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700151 thread_running_gc_ = nullptr;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800152}
153
154void ConcurrentCopying::BindBitmaps() {
155 Thread* self = Thread::Current();
156 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
157 // Mark all of the spaces we never collect as immune.
158 for (const auto& space : heap_->GetContinuousSpaces()) {
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800159 if (space->GetGcRetentionPolicy() == space::kGcRetentionPolicyNeverCollect ||
160 space->GetGcRetentionPolicy() == space::kGcRetentionPolicyFullCollect) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800161 CHECK(space->IsZygoteSpace() || space->IsImageSpace());
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800162 immune_spaces_.AddSpace(space);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800163 } else if (space == region_space_) {
164 accounting::ContinuousSpaceBitmap* bitmap =
165 accounting::ContinuousSpaceBitmap::Create("cc region space bitmap",
166 space->Begin(), space->Capacity());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800167 region_space_bitmap_ = bitmap;
168 }
169 }
170}
171
172void ConcurrentCopying::InitializePhase() {
173 TimingLogger::ScopedTiming split("InitializePhase", GetTimings());
174 if (kVerboseMode) {
175 LOG(INFO) << "GC InitializePhase";
176 LOG(INFO) << "Region-space : " << reinterpret_cast<void*>(region_space_->Begin()) << "-"
177 << reinterpret_cast<void*>(region_space_->Limit());
178 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700179 CheckEmptyMarkStack();
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800180 if (kIsDebugBuild) {
181 MutexLock mu(Thread::Current(), mark_stack_lock_);
182 CHECK(false_gray_stack_.empty());
183 }
Mathieu Chartier56fe2582016-07-14 13:30:03 -0700184
185 mark_from_read_barrier_measurements_ = measure_read_barrier_slow_path_;
186 if (measure_read_barrier_slow_path_) {
187 rb_slow_path_ns_.StoreRelaxed(0);
188 rb_slow_path_count_.StoreRelaxed(0);
189 rb_slow_path_count_gc_.StoreRelaxed(0);
190 }
191
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800192 immune_spaces_.Reset();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800193 bytes_moved_.StoreRelaxed(0);
194 objects_moved_.StoreRelaxed(0);
195 if (GetCurrentIteration()->GetGcCause() == kGcCauseExplicit ||
196 GetCurrentIteration()->GetGcCause() == kGcCauseForNativeAlloc ||
197 GetCurrentIteration()->GetClearSoftReferences()) {
198 force_evacuate_all_ = true;
199 } else {
200 force_evacuate_all_ = false;
201 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700202 if (kUseBakerReadBarrier) {
203 updated_all_immune_objects_.StoreRelaxed(false);
204 // GC may gray immune objects in the thread flip.
205 gc_grays_immune_objects_ = true;
206 if (kIsDebugBuild) {
207 MutexLock mu(Thread::Current(), immune_gray_stack_lock_);
208 DCHECK(immune_gray_stack_.empty());
209 }
210 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800211 BindBitmaps();
212 if (kVerboseMode) {
213 LOG(INFO) << "force_evacuate_all=" << force_evacuate_all_;
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800214 LOG(INFO) << "Largest immune region: " << immune_spaces_.GetLargestImmuneRegion().Begin()
215 << "-" << immune_spaces_.GetLargestImmuneRegion().End();
216 for (space::ContinuousSpace* space : immune_spaces_.GetSpaces()) {
217 LOG(INFO) << "Immune space: " << *space;
218 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800219 LOG(INFO) << "GC end of InitializePhase";
220 }
221}
222
223// Used to switch the thread roots of a thread from from-space refs to to-space refs.
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700224class ConcurrentCopying::ThreadFlipVisitor : public Closure, public RootVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800225 public:
Roland Levillain3887c462015-08-12 18:15:42 +0100226 ThreadFlipVisitor(ConcurrentCopying* concurrent_copying, bool use_tlab)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800227 : concurrent_copying_(concurrent_copying), use_tlab_(use_tlab) {
228 }
229
Mathieu Chartier90443472015-07-16 20:32:27 -0700230 virtual void Run(Thread* thread) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800231 // Note: self is not necessarily equal to thread since thread may be suspended.
232 Thread* self = Thread::Current();
233 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
234 << thread->GetState() << " thread " << thread << " self " << self;
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700235 thread->SetIsGcMarking(true);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800236 if (use_tlab_ && thread->HasTlab()) {
237 if (ConcurrentCopying::kEnableFromSpaceAccountingCheck) {
238 // This must come before the revoke.
239 size_t thread_local_objects = thread->GetThreadLocalObjectsAllocated();
240 concurrent_copying_->region_space_->RevokeThreadLocalBuffers(thread);
241 reinterpret_cast<Atomic<size_t>*>(&concurrent_copying_->from_space_num_objects_at_first_pause_)->
242 FetchAndAddSequentiallyConsistent(thread_local_objects);
243 } else {
244 concurrent_copying_->region_space_->RevokeThreadLocalBuffers(thread);
245 }
246 }
247 if (kUseThreadLocalAllocationStack) {
248 thread->RevokeThreadLocalAllocationStack();
249 }
250 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700251 // We can use the non-CAS VisitRoots functions below because we update thread-local GC roots
252 // only.
253 thread->VisitRoots(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800254 concurrent_copying_->GetBarrier().Pass(self);
255 }
256
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700257 void VisitRoots(mirror::Object*** roots,
258 size_t count,
259 const RootInfo& info ATTRIBUTE_UNUSED)
260 SHARED_REQUIRES(Locks::mutator_lock_) {
261 for (size_t i = 0; i < count; ++i) {
262 mirror::Object** root = roots[i];
263 mirror::Object* ref = *root;
264 if (ref != nullptr) {
265 mirror::Object* to_ref = concurrent_copying_->Mark(ref);
266 if (to_ref != ref) {
267 *root = to_ref;
268 }
269 }
270 }
271 }
272
273 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots,
274 size_t count,
275 const RootInfo& info ATTRIBUTE_UNUSED)
276 SHARED_REQUIRES(Locks::mutator_lock_) {
277 for (size_t i = 0; i < count; ++i) {
278 mirror::CompressedReference<mirror::Object>* const root = roots[i];
279 if (!root->IsNull()) {
280 mirror::Object* ref = root->AsMirrorPtr();
281 mirror::Object* to_ref = concurrent_copying_->Mark(ref);
282 if (to_ref != ref) {
283 root->Assign(to_ref);
284 }
285 }
286 }
287 }
288
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800289 private:
290 ConcurrentCopying* const concurrent_copying_;
291 const bool use_tlab_;
292};
293
294// Called back from Runtime::FlipThreadRoots() during a pause.
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700295class ConcurrentCopying::FlipCallback : public Closure {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800296 public:
297 explicit FlipCallback(ConcurrentCopying* concurrent_copying)
298 : concurrent_copying_(concurrent_copying) {
299 }
300
Mathieu Chartier90443472015-07-16 20:32:27 -0700301 virtual void Run(Thread* thread) OVERRIDE REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800302 ConcurrentCopying* cc = concurrent_copying_;
303 TimingLogger::ScopedTiming split("(Paused)FlipCallback", cc->GetTimings());
304 // Note: self is not necessarily equal to thread since thread may be suspended.
305 Thread* self = Thread::Current();
306 CHECK(thread == self);
307 Locks::mutator_lock_->AssertExclusiveHeld(self);
308 cc->region_space_->SetFromSpace(cc->rb_table_, cc->force_evacuate_all_);
Mathieu Chartiera4f6af92015-08-11 17:35:25 -0700309 cc->SwapStacks();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800310 if (ConcurrentCopying::kEnableFromSpaceAccountingCheck) {
311 cc->RecordLiveStackFreezeSize(self);
312 cc->from_space_num_objects_at_first_pause_ = cc->region_space_->GetObjectsAllocated();
313 cc->from_space_num_bytes_at_first_pause_ = cc->region_space_->GetBytesAllocated();
314 }
315 cc->is_marking_ = true;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700316 cc->mark_stack_mode_.StoreRelaxed(ConcurrentCopying::kMarkStackModeThreadLocal);
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800317 if (kIsDebugBuild) {
318 cc->region_space_->AssertAllRegionLiveBytesZeroOrCleared();
319 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800320 if (UNLIKELY(Runtime::Current()->IsActiveTransaction())) {
Mathieu Chartier184c9dc2015-03-05 13:20:54 -0800321 CHECK(Runtime::Current()->IsAotCompiler());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800322 TimingLogger::ScopedTiming split2("(Paused)VisitTransactionRoots", cc->GetTimings());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700323 Runtime::Current()->VisitTransactionRoots(cc);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800324 }
Mathieu Chartier21328a12016-07-22 10:47:45 -0700325 if (kUseBakerReadBarrier && kGrayDirtyImmuneObjects) {
326 cc->GrayAllDirtyImmuneObjects();
327 if (kIsDebugBuild) {
328 // Check that all non-gray immune objects only refernce immune objects.
329 cc->VerifyGrayImmuneObjects();
330 }
331 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800332 }
333
334 private:
335 ConcurrentCopying* const concurrent_copying_;
336};
337
Mathieu Chartier21328a12016-07-22 10:47:45 -0700338class ConcurrentCopying::VerifyGrayImmuneObjectsVisitor {
339 public:
340 explicit VerifyGrayImmuneObjectsVisitor(ConcurrentCopying* collector)
341 : collector_(collector) {}
342
343 void operator()(mirror::Object* obj, MemberOffset offset, bool /* is_static */)
344 const ALWAYS_INLINE SHARED_REQUIRES(Locks::mutator_lock_)
345 SHARED_REQUIRES(Locks::heap_bitmap_lock_) {
346 CheckReference(obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(offset),
347 obj, offset);
348 }
349
350 void operator()(mirror::Class* klass, mirror::Reference* ref) const
351 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
352 CHECK(klass->IsTypeOfReferenceClass());
353 CheckReference(ref->GetReferent<kWithoutReadBarrier>(),
354 ref,
355 mirror::Reference::ReferentOffset());
356 }
357
358 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
359 ALWAYS_INLINE
360 SHARED_REQUIRES(Locks::mutator_lock_) {
361 if (!root->IsNull()) {
362 VisitRoot(root);
363 }
364 }
365
366 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
367 ALWAYS_INLINE
368 SHARED_REQUIRES(Locks::mutator_lock_) {
369 CheckReference(root->AsMirrorPtr(), nullptr, MemberOffset(0));
370 }
371
372 private:
373 ConcurrentCopying* const collector_;
374
375 void CheckReference(mirror::Object* ref, mirror::Object* holder, MemberOffset offset) const
376 SHARED_REQUIRES(Locks::mutator_lock_) {
377 if (ref != nullptr) {
378 CHECK(collector_->immune_spaces_.ContainsObject(ref))
379 << "Non gray object references non immune object "<< ref << " " << PrettyTypeOf(ref)
380 << " in holder " << holder << " " << PrettyTypeOf(holder) << " offset="
381 << offset.Uint32Value();
382 }
383 }
384};
385
386void ConcurrentCopying::VerifyGrayImmuneObjects() {
387 TimingLogger::ScopedTiming split(__FUNCTION__, GetTimings());
388 for (auto& space : immune_spaces_.GetSpaces()) {
389 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
390 accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
391 VerifyGrayImmuneObjectsVisitor visitor(this);
392 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()),
393 reinterpret_cast<uintptr_t>(space->Limit()),
394 [&visitor](mirror::Object* obj)
395 SHARED_REQUIRES(Locks::mutator_lock_) {
396 // If an object is not gray, it should only have references to things in the immune spaces.
397 if (obj->GetReadBarrierPointer() != ReadBarrier::GrayPtr()) {
398 obj->VisitReferences</*kVisitNativeRoots*/true,
399 kDefaultVerifyFlags,
400 kWithoutReadBarrier>(visitor, visitor);
401 }
402 });
403 }
404}
405
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800406// Switch threads that from from-space to to-space refs. Forward/mark the thread roots.
407void ConcurrentCopying::FlipThreadRoots() {
408 TimingLogger::ScopedTiming split("FlipThreadRoots", GetTimings());
409 if (kVerboseMode) {
410 LOG(INFO) << "time=" << region_space_->Time();
411 region_space_->DumpNonFreeRegions(LOG(INFO));
412 }
413 Thread* self = Thread::Current();
414 Locks::mutator_lock_->AssertNotHeld(self);
415 gc_barrier_->Init(self, 0);
416 ThreadFlipVisitor thread_flip_visitor(this, heap_->use_tlab_);
417 FlipCallback flip_callback(this);
Hiroshi Yamauchi76f55b02015-08-21 16:10:39 -0700418 heap_->ThreadFlipBegin(self); // Sync with JNI critical calls.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800419 size_t barrier_count = Runtime::Current()->FlipThreadRoots(
420 &thread_flip_visitor, &flip_callback, this);
Hiroshi Yamauchi76f55b02015-08-21 16:10:39 -0700421 heap_->ThreadFlipEnd(self);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800422 {
423 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
424 gc_barrier_->Increment(self, barrier_count);
425 }
426 is_asserting_to_space_invariant_ = true;
427 QuasiAtomic::ThreadFenceForConstructor();
428 if (kVerboseMode) {
429 LOG(INFO) << "time=" << region_space_->Time();
430 region_space_->DumpNonFreeRegions(LOG(INFO));
431 LOG(INFO) << "GC end of FlipThreadRoots";
432 }
433}
434
Mathieu Chartier21328a12016-07-22 10:47:45 -0700435class ConcurrentCopying::GrayImmuneObjectVisitor {
436 public:
437 explicit GrayImmuneObjectVisitor() {}
438
439 ALWAYS_INLINE void operator()(mirror::Object* obj) const SHARED_REQUIRES(Locks::mutator_lock_) {
440 if (kUseBakerReadBarrier) {
441 if (kIsDebugBuild) {
442 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
443 }
444 obj->SetReadBarrierPointer(ReadBarrier::GrayPtr());
445 }
446 }
447
448 static void Callback(mirror::Object* obj, void* arg) SHARED_REQUIRES(Locks::mutator_lock_) {
449 reinterpret_cast<GrayImmuneObjectVisitor*>(arg)->operator()(obj);
450 }
451};
452
453void ConcurrentCopying::GrayAllDirtyImmuneObjects() {
454 TimingLogger::ScopedTiming split(__FUNCTION__, GetTimings());
455 gc::Heap* const heap = Runtime::Current()->GetHeap();
456 accounting::CardTable* const card_table = heap->GetCardTable();
457 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
458 for (space::ContinuousSpace* space : immune_spaces_.GetSpaces()) {
459 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
460 GrayImmuneObjectVisitor visitor;
461 accounting::ModUnionTable* table = heap->FindModUnionTableFromSpace(space);
462 // Mark all the objects on dirty cards since these may point to objects in other space.
463 // Once these are marked, the GC will eventually clear them later.
464 // Table is non null for boot image and zygote spaces. It is only null for application image
465 // spaces.
466 if (table != nullptr) {
467 // TODO: Add preclean outside the pause.
468 table->ClearCards();
469 table->VisitObjects(GrayImmuneObjectVisitor::Callback, &visitor);
470 } else {
471 // TODO: Consider having a mark bitmap for app image spaces and avoid scanning during the
472 // pause because app image spaces are all dirty pages anyways.
473 card_table->Scan<false>(space->GetMarkBitmap(), space->Begin(), space->End(), visitor);
474 }
475 }
476 // Since all of the objects that may point to other spaces are marked, we can avoid all the read
477 // barriers in the immune spaces.
478 updated_all_immune_objects_.StoreRelaxed(true);
479}
480
Mathieu Chartiera4f6af92015-08-11 17:35:25 -0700481void ConcurrentCopying::SwapStacks() {
482 heap_->SwapStacks();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800483}
484
485void ConcurrentCopying::RecordLiveStackFreezeSize(Thread* self) {
486 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
487 live_stack_freeze_size_ = heap_->GetLiveStack()->Size();
488}
489
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800490class EmptyCheckpoint : public Closure {
491 public:
492 explicit EmptyCheckpoint(ConcurrentCopying* concurrent_copying)
493 : concurrent_copying_(concurrent_copying) {
494 }
495
496 virtual void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
497 // Note: self is not necessarily equal to thread since thread may be suspended.
498 Thread* self = Thread::Current();
499 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
500 << thread->GetState() << " thread " << thread << " self " << self;
Lei Lidd9943d2015-02-02 14:24:44 +0800501 // If thread is a running mutator, then act on behalf of the garbage collector.
502 // See the code in ThreadList::RunCheckpoint.
Mathieu Chartier10d25082015-10-28 18:36:09 -0700503 concurrent_copying_->GetBarrier().Pass(self);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800504 }
505
506 private:
507 ConcurrentCopying* const concurrent_copying_;
508};
509
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700510// Used to visit objects in the immune spaces.
511inline void ConcurrentCopying::ScanImmuneObject(mirror::Object* obj) {
512 DCHECK(obj != nullptr);
513 DCHECK(immune_spaces_.ContainsObject(obj));
514 // Update the fields without graying it or pushing it onto the mark stack.
515 Scan(obj);
516}
517
518class ConcurrentCopying::ImmuneSpaceScanObjVisitor {
519 public:
520 explicit ImmuneSpaceScanObjVisitor(ConcurrentCopying* cc)
521 : collector_(cc) {}
522
523 void operator()(mirror::Object* obj) const SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700524 if (kUseBakerReadBarrier && kGrayDirtyImmuneObjects) {
525 if (obj->GetReadBarrierPointer() == ReadBarrier::GrayPtr()) {
526 collector_->ScanImmuneObject(obj);
527 // Done scanning the object, go back to white.
528 bool success = obj->AtomicSetReadBarrierPointer(ReadBarrier::GrayPtr(),
529 ReadBarrier::WhitePtr());
530 CHECK(success);
531 }
532 } else {
533 collector_->ScanImmuneObject(obj);
534 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700535 }
536
537 private:
538 ConcurrentCopying* const collector_;
539};
540
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800541// Concurrently mark roots that are guarded by read barriers and process the mark stack.
542void ConcurrentCopying::MarkingPhase() {
543 TimingLogger::ScopedTiming split("MarkingPhase", GetTimings());
544 if (kVerboseMode) {
545 LOG(INFO) << "GC MarkingPhase";
546 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700547 CHECK(weak_ref_access_enabled_);
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700548
549 // Scan immune spaces.
550 // Update all the fields in the immune spaces first without graying the objects so that we
551 // minimize dirty pages in the immune spaces. Note mutators can concurrently access and gray some
552 // of the objects.
553 if (kUseBakerReadBarrier) {
554 gc_grays_immune_objects_ = false;
Hiroshi Yamauchi16292fc2016-06-20 20:23:34 -0700555 }
Mathieu Chartier21328a12016-07-22 10:47:45 -0700556 {
557 TimingLogger::ScopedTiming split2("ScanImmuneSpaces", GetTimings());
558 for (auto& space : immune_spaces_.GetSpaces()) {
559 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
560 accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
561 ImmuneSpaceScanObjVisitor visitor(this);
562 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()),
563 reinterpret_cast<uintptr_t>(space->Limit()),
564 visitor);
565 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700566 }
567 if (kUseBakerReadBarrier) {
568 // This release fence makes the field updates in the above loop visible before allowing mutator
569 // getting access to immune objects without graying it first.
570 updated_all_immune_objects_.StoreRelease(true);
571 // Now whiten immune objects concurrently accessed and grayed by mutators. We can't do this in
572 // the above loop because we would incorrectly disable the read barrier by whitening an object
573 // which may point to an unscanned, white object, breaking the to-space invariant.
574 //
575 // Make sure no mutators are in the middle of marking an immune object before whitening immune
576 // objects.
577 IssueEmptyCheckpoint();
578 MutexLock mu(Thread::Current(), immune_gray_stack_lock_);
579 if (kVerboseMode) {
580 LOG(INFO) << "immune gray stack size=" << immune_gray_stack_.size();
581 }
582 for (mirror::Object* obj : immune_gray_stack_) {
583 DCHECK(obj->GetReadBarrierPointer() == ReadBarrier::GrayPtr());
584 bool success = obj->AtomicSetReadBarrierPointer(ReadBarrier::GrayPtr(),
585 ReadBarrier::WhitePtr());
586 DCHECK(success);
587 }
588 immune_gray_stack_.clear();
589 }
590
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800591 {
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -0700592 TimingLogger::ScopedTiming split2("VisitConcurrentRoots", GetTimings());
593 Runtime::Current()->VisitConcurrentRoots(this, kVisitRootFlagAllRoots);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800594 }
595 {
596 // TODO: don't visit the transaction roots if it's not active.
597 TimingLogger::ScopedTiming split5("VisitNonThreadRoots", GetTimings());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700598 Runtime::Current()->VisitNonThreadRoots(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800599 }
600
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800601 Thread* self = Thread::Current();
602 {
Mathieu Chartiera6b1ead2015-10-06 10:32:38 -0700603 TimingLogger::ScopedTiming split7("ProcessMarkStack", GetTimings());
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700604 // We transition through three mark stack modes (thread-local, shared, GC-exclusive). The
605 // primary reasons are the fact that we need to use a checkpoint to process thread-local mark
606 // stacks, but after we disable weak refs accesses, we can't use a checkpoint due to a deadlock
607 // issue because running threads potentially blocking at WaitHoldingLocks, and that once we
608 // reach the point where we process weak references, we can avoid using a lock when accessing
609 // the GC mark stack, which makes mark stack processing more efficient.
610
611 // Process the mark stack once in the thread local stack mode. This marks most of the live
612 // objects, aside from weak ref accesses with read barriers (Reference::GetReferent() and system
613 // weaks) that may happen concurrently while we processing the mark stack and newly mark/gray
614 // objects and push refs on the mark stack.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800615 ProcessMarkStack();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700616 // Switch to the shared mark stack mode. That is, revoke and process thread-local mark stacks
617 // for the last time before transitioning to the shared mark stack mode, which would process new
618 // refs that may have been concurrently pushed onto the mark stack during the ProcessMarkStack()
619 // call above. At the same time, disable weak ref accesses using a per-thread flag. It's
620 // important to do these together in a single checkpoint so that we can ensure that mutators
621 // won't newly gray objects and push new refs onto the mark stack due to weak ref accesses and
622 // mutators safely transition to the shared mark stack mode (without leaving unprocessed refs on
623 // the thread-local mark stacks), without a race. This is why we use a thread-local weak ref
624 // access flag Thread::tls32_.weak_ref_access_enabled_ instead of the global ones.
625 SwitchToSharedMarkStackMode();
626 CHECK(!self->GetWeakRefAccessEnabled());
627 // Now that weak refs accesses are disabled, once we exhaust the shared mark stack again here
628 // (which may be non-empty if there were refs found on thread-local mark stacks during the above
629 // SwitchToSharedMarkStackMode() call), we won't have new refs to process, that is, mutators
630 // (via read barriers) have no way to produce any more refs to process. Marking converges once
631 // before we process weak refs below.
632 ProcessMarkStack();
633 CheckEmptyMarkStack();
634 // Switch to the GC exclusive mark stack mode so that we can process the mark stack without a
635 // lock from this point on.
636 SwitchToGcExclusiveMarkStackMode();
637 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800638 if (kVerboseMode) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800639 LOG(INFO) << "ProcessReferences";
640 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700641 // Process weak references. This may produce new refs to process and have them processed via
Mathieu Chartier97509952015-07-13 14:35:43 -0700642 // ProcessMarkStack (in the GC exclusive mark stack mode).
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700643 ProcessReferences(self);
644 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800645 if (kVerboseMode) {
646 LOG(INFO) << "SweepSystemWeaks";
647 }
648 SweepSystemWeaks(self);
649 if (kVerboseMode) {
650 LOG(INFO) << "SweepSystemWeaks done";
651 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700652 // Process the mark stack here one last time because the above SweepSystemWeaks() call may have
653 // marked some objects (strings alive) as hash_set::Erase() can call the hash function for
654 // arbitrary elements in the weak intern table in InternTable::Table::SweepWeaks().
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800655 ProcessMarkStack();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700656 CheckEmptyMarkStack();
657 // Re-enable weak ref accesses.
658 ReenableWeakRefAccess(self);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -0700659 // Free data for class loaders that we unloaded.
660 Runtime::Current()->GetClassLinker()->CleanupClassLoaders();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700661 // Marking is done. Disable marking.
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700662 DisableMarking();
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800663 if (kUseBakerReadBarrier) {
664 ProcessFalseGrayStack();
665 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700666 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800667 }
668
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700669 CHECK(weak_ref_access_enabled_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800670 if (kVerboseMode) {
671 LOG(INFO) << "GC end of MarkingPhase";
672 }
673}
674
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700675void ConcurrentCopying::ReenableWeakRefAccess(Thread* self) {
676 if (kVerboseMode) {
677 LOG(INFO) << "ReenableWeakRefAccess";
678 }
679 weak_ref_access_enabled_.StoreRelaxed(true); // This is for new threads.
680 QuasiAtomic::ThreadFenceForConstructor();
681 // Iterate all threads (don't need to or can't use a checkpoint) and re-enable weak ref access.
682 {
683 MutexLock mu(self, *Locks::thread_list_lock_);
684 std::list<Thread*> thread_list = Runtime::Current()->GetThreadList()->GetList();
685 for (Thread* thread : thread_list) {
686 thread->SetWeakRefAccessEnabled(true);
687 }
688 }
689 // Unblock blocking threads.
690 GetHeap()->GetReferenceProcessor()->BroadcastForSlowPath(self);
691 Runtime::Current()->BroadcastForNewSystemWeaks();
692}
693
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700694class ConcurrentCopying::DisableMarkingCheckpoint : public Closure {
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700695 public:
696 explicit DisableMarkingCheckpoint(ConcurrentCopying* concurrent_copying)
697 : concurrent_copying_(concurrent_copying) {
698 }
699
700 void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
701 // Note: self is not necessarily equal to thread since thread may be suspended.
702 Thread* self = Thread::Current();
703 DCHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
704 << thread->GetState() << " thread " << thread << " self " << self;
705 // Disable the thread-local is_gc_marking flag.
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -0700706 // Note a thread that has just started right before this checkpoint may have already this flag
707 // set to false, which is ok.
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700708 thread->SetIsGcMarking(false);
709 // If thread is a running mutator, then act on behalf of the garbage collector.
710 // See the code in ThreadList::RunCheckpoint.
Mathieu Chartier10d25082015-10-28 18:36:09 -0700711 concurrent_copying_->GetBarrier().Pass(self);
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700712 }
713
714 private:
715 ConcurrentCopying* const concurrent_copying_;
716};
717
718void ConcurrentCopying::IssueDisableMarkingCheckpoint() {
719 Thread* self = Thread::Current();
720 DisableMarkingCheckpoint check_point(this);
721 ThreadList* thread_list = Runtime::Current()->GetThreadList();
722 gc_barrier_->Init(self, 0);
723 size_t barrier_count = thread_list->RunCheckpoint(&check_point);
724 // If there are no threads to wait which implies that all the checkpoint functions are finished,
725 // then no need to release the mutator lock.
726 if (barrier_count == 0) {
727 return;
728 }
729 // Release locks then wait for all mutator threads to pass the barrier.
730 Locks::mutator_lock_->SharedUnlock(self);
731 {
732 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
733 gc_barrier_->Increment(self, barrier_count);
734 }
735 Locks::mutator_lock_->SharedLock(self);
736}
737
738void ConcurrentCopying::DisableMarking() {
739 // Change the global is_marking flag to false. Do a fence before doing a checkpoint to update the
740 // thread-local flags so that a new thread starting up will get the correct is_marking flag.
741 is_marking_ = false;
742 QuasiAtomic::ThreadFenceForConstructor();
743 // Use a checkpoint to turn off the thread-local is_gc_marking flags and to ensure no threads are
744 // still in the middle of a read barrier which may have a from-space ref cached in a local
745 // variable.
746 IssueDisableMarkingCheckpoint();
747 if (kUseTableLookupReadBarrier) {
748 heap_->rb_table_->ClearAll();
749 DCHECK(heap_->rb_table_->IsAllCleared());
750 }
751 is_mark_stack_push_disallowed_.StoreSequentiallyConsistent(1);
752 mark_stack_mode_.StoreSequentiallyConsistent(kMarkStackModeOff);
753}
754
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800755void ConcurrentCopying::PushOntoFalseGrayStack(mirror::Object* ref) {
756 CHECK(kUseBakerReadBarrier);
757 DCHECK(ref != nullptr);
758 MutexLock mu(Thread::Current(), mark_stack_lock_);
759 false_gray_stack_.push_back(ref);
760}
761
762void ConcurrentCopying::ProcessFalseGrayStack() {
763 CHECK(kUseBakerReadBarrier);
764 // Change the objects on the false gray stack from gray to white.
765 MutexLock mu(Thread::Current(), mark_stack_lock_);
766 for (mirror::Object* obj : false_gray_stack_) {
767 DCHECK(IsMarked(obj));
768 // The object could be white here if a thread got preempted after a success at the
769 // AtomicSetReadBarrierPointer in Mark(), GC started marking through it (but not finished so
770 // still gray), and the thread ran to register it onto the false gray stack.
771 if (obj->GetReadBarrierPointer() == ReadBarrier::GrayPtr()) {
772 bool success = obj->AtomicSetReadBarrierPointer(ReadBarrier::GrayPtr(),
773 ReadBarrier::WhitePtr());
774 DCHECK(success);
775 }
776 }
777 false_gray_stack_.clear();
778}
779
780
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800781void ConcurrentCopying::IssueEmptyCheckpoint() {
782 Thread* self = Thread::Current();
783 EmptyCheckpoint check_point(this);
784 ThreadList* thread_list = Runtime::Current()->GetThreadList();
785 gc_barrier_->Init(self, 0);
786 size_t barrier_count = thread_list->RunCheckpoint(&check_point);
Lei Lidd9943d2015-02-02 14:24:44 +0800787 // If there are no threads to wait which implys that all the checkpoint functions are finished,
788 // then no need to release the mutator lock.
789 if (barrier_count == 0) {
790 return;
791 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800792 // Release locks then wait for all mutator threads to pass the barrier.
793 Locks::mutator_lock_->SharedUnlock(self);
794 {
795 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
796 gc_barrier_->Increment(self, barrier_count);
797 }
798 Locks::mutator_lock_->SharedLock(self);
799}
800
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -0700801void ConcurrentCopying::ExpandGcMarkStack() {
802 DCHECK(gc_mark_stack_->IsFull());
803 const size_t new_size = gc_mark_stack_->Capacity() * 2;
804 std::vector<StackReference<mirror::Object>> temp(gc_mark_stack_->Begin(),
805 gc_mark_stack_->End());
806 gc_mark_stack_->Resize(new_size);
807 for (auto& ref : temp) {
808 gc_mark_stack_->PushBack(ref.AsMirrorPtr());
809 }
810 DCHECK(!gc_mark_stack_->IsFull());
811}
812
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800813void ConcurrentCopying::PushOntoMarkStack(mirror::Object* to_ref) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700814 CHECK_EQ(is_mark_stack_push_disallowed_.LoadRelaxed(), 0)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800815 << " " << to_ref << " " << PrettyTypeOf(to_ref);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700816 Thread* self = Thread::Current(); // TODO: pass self as an argument from call sites?
817 CHECK(thread_running_gc_ != nullptr);
818 MarkStackMode mark_stack_mode = mark_stack_mode_.LoadRelaxed();
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -0700819 if (LIKELY(mark_stack_mode == kMarkStackModeThreadLocal)) {
820 if (LIKELY(self == thread_running_gc_)) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700821 // If GC-running thread, use the GC mark stack instead of a thread-local mark stack.
822 CHECK(self->GetThreadLocalMarkStack() == nullptr);
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -0700823 if (UNLIKELY(gc_mark_stack_->IsFull())) {
824 ExpandGcMarkStack();
825 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700826 gc_mark_stack_->PushBack(to_ref);
827 } else {
828 // Otherwise, use a thread-local mark stack.
829 accounting::AtomicStack<mirror::Object>* tl_mark_stack = self->GetThreadLocalMarkStack();
830 if (UNLIKELY(tl_mark_stack == nullptr || tl_mark_stack->IsFull())) {
831 MutexLock mu(self, mark_stack_lock_);
832 // Get a new thread local mark stack.
833 accounting::AtomicStack<mirror::Object>* new_tl_mark_stack;
834 if (!pooled_mark_stacks_.empty()) {
835 // Use a pooled mark stack.
836 new_tl_mark_stack = pooled_mark_stacks_.back();
837 pooled_mark_stacks_.pop_back();
838 } else {
839 // None pooled. Create a new one.
840 new_tl_mark_stack =
841 accounting::AtomicStack<mirror::Object>::Create(
842 "thread local mark stack", 4 * KB, 4 * KB);
843 }
844 DCHECK(new_tl_mark_stack != nullptr);
845 DCHECK(new_tl_mark_stack->IsEmpty());
846 new_tl_mark_stack->PushBack(to_ref);
847 self->SetThreadLocalMarkStack(new_tl_mark_stack);
848 if (tl_mark_stack != nullptr) {
849 // Store the old full stack into a vector.
850 revoked_mark_stacks_.push_back(tl_mark_stack);
851 }
852 } else {
853 tl_mark_stack->PushBack(to_ref);
854 }
855 }
856 } else if (mark_stack_mode == kMarkStackModeShared) {
857 // Access the shared GC mark stack with a lock.
858 MutexLock mu(self, mark_stack_lock_);
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -0700859 if (UNLIKELY(gc_mark_stack_->IsFull())) {
860 ExpandGcMarkStack();
861 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700862 gc_mark_stack_->PushBack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800863 } else {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700864 CHECK_EQ(static_cast<uint32_t>(mark_stack_mode),
Hiroshi Yamauchifa755182015-09-30 20:12:11 -0700865 static_cast<uint32_t>(kMarkStackModeGcExclusive))
866 << "ref=" << to_ref
867 << " self->gc_marking=" << self->GetIsGcMarking()
868 << " cc->is_marking=" << is_marking_;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700869 CHECK(self == thread_running_gc_)
870 << "Only GC-running thread should access the mark stack "
871 << "in the GC exclusive mark stack mode";
872 // Access the GC mark stack without a lock.
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -0700873 if (UNLIKELY(gc_mark_stack_->IsFull())) {
874 ExpandGcMarkStack();
875 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700876 gc_mark_stack_->PushBack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800877 }
878}
879
880accounting::ObjectStack* ConcurrentCopying::GetAllocationStack() {
881 return heap_->allocation_stack_.get();
882}
883
884accounting::ObjectStack* ConcurrentCopying::GetLiveStack() {
885 return heap_->live_stack_.get();
886}
887
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800888// The following visitors are used to verify that there's no references to the from-space left after
889// marking.
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700890class ConcurrentCopying::VerifyNoFromSpaceRefsVisitor : public SingleRootVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800891 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700892 explicit VerifyNoFromSpaceRefsVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800893 : collector_(collector) {}
894
895 void operator()(mirror::Object* ref) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700896 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800897 if (ref == nullptr) {
898 // OK.
899 return;
900 }
901 collector_->AssertToSpaceInvariant(nullptr, MemberOffset(0), ref);
902 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800903 CHECK(ref->GetReadBarrierPointer() == ReadBarrier::WhitePtr())
904 << "Ref " << ref << " " << PrettyTypeOf(ref)
905 << " has non-white rb_ptr " << ref->GetReadBarrierPointer();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800906 }
907 }
908
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700909 void VisitRoot(mirror::Object* root, const RootInfo& info ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -0700910 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800911 DCHECK(root != nullptr);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700912 operator()(root);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800913 }
914
915 private:
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700916 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800917};
918
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700919class ConcurrentCopying::VerifyNoFromSpaceRefsFieldVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800920 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700921 explicit VerifyNoFromSpaceRefsFieldVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800922 : collector_(collector) {}
923
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700924 void operator()(mirror::Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700925 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800926 mirror::Object* ref =
927 obj->GetFieldObject<mirror::Object, kDefaultVerifyFlags, kWithoutReadBarrier>(offset);
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700928 VerifyNoFromSpaceRefsVisitor visitor(collector_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800929 visitor(ref);
930 }
931 void operator()(mirror::Class* klass, mirror::Reference* ref) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700932 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800933 CHECK(klass->IsTypeOfReferenceClass());
934 this->operator()(ref, mirror::Reference::ReferentOffset(), false);
935 }
936
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700937 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
938 SHARED_REQUIRES(Locks::mutator_lock_) {
939 if (!root->IsNull()) {
940 VisitRoot(root);
941 }
942 }
943
944 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
945 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700946 VerifyNoFromSpaceRefsVisitor visitor(collector_);
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700947 visitor(root->AsMirrorPtr());
948 }
949
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800950 private:
Mathieu Chartier97509952015-07-13 14:35:43 -0700951 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800952};
953
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700954class ConcurrentCopying::VerifyNoFromSpaceRefsObjectVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800955 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700956 explicit VerifyNoFromSpaceRefsObjectVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800957 : collector_(collector) {}
958 void operator()(mirror::Object* obj) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700959 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800960 ObjectCallback(obj, collector_);
961 }
962 static void ObjectCallback(mirror::Object* obj, void *arg)
Mathieu Chartier90443472015-07-16 20:32:27 -0700963 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800964 CHECK(obj != nullptr);
965 ConcurrentCopying* collector = reinterpret_cast<ConcurrentCopying*>(arg);
966 space::RegionSpace* region_space = collector->RegionSpace();
967 CHECK(!region_space->IsInFromSpace(obj)) << "Scanning object " << obj << " in from space";
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700968 VerifyNoFromSpaceRefsFieldVisitor visitor(collector);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -0700969 obj->VisitReferences(visitor, visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800970 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800971 CHECK(obj->GetReadBarrierPointer() == ReadBarrier::WhitePtr())
972 << "obj=" << obj << " non-white rb_ptr " << obj->GetReadBarrierPointer();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800973 }
974 }
975
976 private:
977 ConcurrentCopying* const collector_;
978};
979
980// Verify there's no from-space references left after the marking phase.
981void ConcurrentCopying::VerifyNoFromSpaceReferences() {
982 Thread* self = Thread::Current();
983 DCHECK(Locks::mutator_lock_->IsExclusiveHeld(self));
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700984 // Verify all threads have is_gc_marking to be false
985 {
986 MutexLock mu(self, *Locks::thread_list_lock_);
987 std::list<Thread*> thread_list = Runtime::Current()->GetThreadList()->GetList();
988 for (Thread* thread : thread_list) {
989 CHECK(!thread->GetIsGcMarking());
990 }
991 }
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700992 VerifyNoFromSpaceRefsObjectVisitor visitor(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800993 // Roots.
994 {
995 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700996 VerifyNoFromSpaceRefsVisitor ref_visitor(this);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700997 Runtime::Current()->VisitRoots(&ref_visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800998 }
999 // The to-space.
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001000 region_space_->WalkToSpace(VerifyNoFromSpaceRefsObjectVisitor::ObjectCallback, this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001001 // Non-moving spaces.
1002 {
1003 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1004 heap_->GetMarkBitmap()->Visit(visitor);
1005 }
1006 // The alloc stack.
1007 {
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001008 VerifyNoFromSpaceRefsVisitor ref_visitor(this);
Mathieu Chartiercb535da2015-01-23 13:50:03 -08001009 for (auto* it = heap_->allocation_stack_->Begin(), *end = heap_->allocation_stack_->End();
1010 it < end; ++it) {
1011 mirror::Object* const obj = it->AsMirrorPtr();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001012 if (obj != nullptr && obj->GetClass() != nullptr) {
1013 // TODO: need to call this only if obj is alive?
1014 ref_visitor(obj);
1015 visitor(obj);
1016 }
1017 }
1018 }
1019 // TODO: LOS. But only refs in LOS are classes.
1020}
1021
1022// The following visitors are used to assert the to-space invariant.
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001023class ConcurrentCopying::AssertToSpaceInvariantRefsVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001024 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001025 explicit AssertToSpaceInvariantRefsVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001026 : collector_(collector) {}
1027
1028 void operator()(mirror::Object* ref) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001029 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001030 if (ref == nullptr) {
1031 // OK.
1032 return;
1033 }
1034 collector_->AssertToSpaceInvariant(nullptr, MemberOffset(0), ref);
1035 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001036
1037 private:
Mathieu Chartier97509952015-07-13 14:35:43 -07001038 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001039};
1040
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001041class ConcurrentCopying::AssertToSpaceInvariantFieldVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001042 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001043 explicit AssertToSpaceInvariantFieldVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001044 : collector_(collector) {}
1045
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001046 void operator()(mirror::Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001047 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001048 mirror::Object* ref =
1049 obj->GetFieldObject<mirror::Object, kDefaultVerifyFlags, kWithoutReadBarrier>(offset);
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001050 AssertToSpaceInvariantRefsVisitor visitor(collector_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001051 visitor(ref);
1052 }
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001053 void operator()(mirror::Class* klass, mirror::Reference* ref ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001054 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001055 CHECK(klass->IsTypeOfReferenceClass());
1056 }
1057
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001058 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
1059 SHARED_REQUIRES(Locks::mutator_lock_) {
1060 if (!root->IsNull()) {
1061 VisitRoot(root);
1062 }
1063 }
1064
1065 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
1066 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001067 AssertToSpaceInvariantRefsVisitor visitor(collector_);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001068 visitor(root->AsMirrorPtr());
1069 }
1070
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001071 private:
Mathieu Chartier97509952015-07-13 14:35:43 -07001072 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001073};
1074
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001075class ConcurrentCopying::AssertToSpaceInvariantObjectVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001076 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001077 explicit AssertToSpaceInvariantObjectVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001078 : collector_(collector) {}
1079 void operator()(mirror::Object* obj) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001080 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001081 ObjectCallback(obj, collector_);
1082 }
1083 static void ObjectCallback(mirror::Object* obj, void *arg)
Mathieu Chartier90443472015-07-16 20:32:27 -07001084 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001085 CHECK(obj != nullptr);
1086 ConcurrentCopying* collector = reinterpret_cast<ConcurrentCopying*>(arg);
1087 space::RegionSpace* region_space = collector->RegionSpace();
1088 CHECK(!region_space->IsInFromSpace(obj)) << "Scanning object " << obj << " in from space";
1089 collector->AssertToSpaceInvariant(nullptr, MemberOffset(0), obj);
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001090 AssertToSpaceInvariantFieldVisitor visitor(collector);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07001091 obj->VisitReferences(visitor, visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001092 }
1093
1094 private:
Mathieu Chartier97509952015-07-13 14:35:43 -07001095 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001096};
1097
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001098class ConcurrentCopying::RevokeThreadLocalMarkStackCheckpoint : public Closure {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001099 public:
Roland Levillain3887c462015-08-12 18:15:42 +01001100 RevokeThreadLocalMarkStackCheckpoint(ConcurrentCopying* concurrent_copying,
1101 bool disable_weak_ref_access)
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001102 : concurrent_copying_(concurrent_copying),
1103 disable_weak_ref_access_(disable_weak_ref_access) {
1104 }
1105
1106 virtual void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
1107 // Note: self is not necessarily equal to thread since thread may be suspended.
1108 Thread* self = Thread::Current();
1109 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
1110 << thread->GetState() << " thread " << thread << " self " << self;
1111 // Revoke thread local mark stacks.
1112 accounting::AtomicStack<mirror::Object>* tl_mark_stack = thread->GetThreadLocalMarkStack();
1113 if (tl_mark_stack != nullptr) {
1114 MutexLock mu(self, concurrent_copying_->mark_stack_lock_);
1115 concurrent_copying_->revoked_mark_stacks_.push_back(tl_mark_stack);
1116 thread->SetThreadLocalMarkStack(nullptr);
1117 }
1118 // Disable weak ref access.
1119 if (disable_weak_ref_access_) {
1120 thread->SetWeakRefAccessEnabled(false);
1121 }
1122 // If thread is a running mutator, then act on behalf of the garbage collector.
1123 // See the code in ThreadList::RunCheckpoint.
Mathieu Chartier10d25082015-10-28 18:36:09 -07001124 concurrent_copying_->GetBarrier().Pass(self);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001125 }
1126
1127 private:
1128 ConcurrentCopying* const concurrent_copying_;
1129 const bool disable_weak_ref_access_;
1130};
1131
1132void ConcurrentCopying::RevokeThreadLocalMarkStacks(bool disable_weak_ref_access) {
1133 Thread* self = Thread::Current();
1134 RevokeThreadLocalMarkStackCheckpoint check_point(this, disable_weak_ref_access);
1135 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1136 gc_barrier_->Init(self, 0);
1137 size_t barrier_count = thread_list->RunCheckpoint(&check_point);
1138 // If there are no threads to wait which implys that all the checkpoint functions are finished,
1139 // then no need to release the mutator lock.
1140 if (barrier_count == 0) {
1141 return;
1142 }
1143 Locks::mutator_lock_->SharedUnlock(self);
1144 {
1145 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
1146 gc_barrier_->Increment(self, barrier_count);
1147 }
1148 Locks::mutator_lock_->SharedLock(self);
1149}
1150
1151void ConcurrentCopying::RevokeThreadLocalMarkStack(Thread* thread) {
1152 Thread* self = Thread::Current();
1153 CHECK_EQ(self, thread);
1154 accounting::AtomicStack<mirror::Object>* tl_mark_stack = thread->GetThreadLocalMarkStack();
1155 if (tl_mark_stack != nullptr) {
1156 CHECK(is_marking_);
1157 MutexLock mu(self, mark_stack_lock_);
1158 revoked_mark_stacks_.push_back(tl_mark_stack);
1159 thread->SetThreadLocalMarkStack(nullptr);
1160 }
1161}
1162
1163void ConcurrentCopying::ProcessMarkStack() {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001164 if (kVerboseMode) {
1165 LOG(INFO) << "ProcessMarkStack. ";
1166 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001167 bool empty_prev = false;
1168 while (true) {
1169 bool empty = ProcessMarkStackOnce();
1170 if (empty_prev && empty) {
1171 // Saw empty mark stack for a second time, done.
1172 break;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001173 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001174 empty_prev = empty;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001175 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001176}
1177
1178bool ConcurrentCopying::ProcessMarkStackOnce() {
1179 Thread* self = Thread::Current();
1180 CHECK(thread_running_gc_ != nullptr);
1181 CHECK(self == thread_running_gc_);
1182 CHECK(self->GetThreadLocalMarkStack() == nullptr);
1183 size_t count = 0;
1184 MarkStackMode mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1185 if (mark_stack_mode == kMarkStackModeThreadLocal) {
1186 // Process the thread-local mark stacks and the GC mark stack.
1187 count += ProcessThreadLocalMarkStacks(false);
1188 while (!gc_mark_stack_->IsEmpty()) {
1189 mirror::Object* to_ref = gc_mark_stack_->PopBack();
1190 ProcessMarkStackRef(to_ref);
1191 ++count;
1192 }
1193 gc_mark_stack_->Reset();
1194 } else if (mark_stack_mode == kMarkStackModeShared) {
1195 // Process the shared GC mark stack with a lock.
1196 {
1197 MutexLock mu(self, mark_stack_lock_);
1198 CHECK(revoked_mark_stacks_.empty());
1199 }
1200 while (true) {
1201 std::vector<mirror::Object*> refs;
1202 {
1203 // Copy refs with lock. Note the number of refs should be small.
1204 MutexLock mu(self, mark_stack_lock_);
1205 if (gc_mark_stack_->IsEmpty()) {
1206 break;
1207 }
1208 for (StackReference<mirror::Object>* p = gc_mark_stack_->Begin();
1209 p != gc_mark_stack_->End(); ++p) {
1210 refs.push_back(p->AsMirrorPtr());
1211 }
1212 gc_mark_stack_->Reset();
1213 }
1214 for (mirror::Object* ref : refs) {
1215 ProcessMarkStackRef(ref);
1216 ++count;
1217 }
1218 }
1219 } else {
1220 CHECK_EQ(static_cast<uint32_t>(mark_stack_mode),
1221 static_cast<uint32_t>(kMarkStackModeGcExclusive));
1222 {
1223 MutexLock mu(self, mark_stack_lock_);
1224 CHECK(revoked_mark_stacks_.empty());
1225 }
1226 // Process the GC mark stack in the exclusive mode. No need to take the lock.
1227 while (!gc_mark_stack_->IsEmpty()) {
1228 mirror::Object* to_ref = gc_mark_stack_->PopBack();
1229 ProcessMarkStackRef(to_ref);
1230 ++count;
1231 }
1232 gc_mark_stack_->Reset();
1233 }
1234
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001235 // Return true if the stack was empty.
1236 return count == 0;
1237}
1238
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001239size_t ConcurrentCopying::ProcessThreadLocalMarkStacks(bool disable_weak_ref_access) {
1240 // Run a checkpoint to collect all thread local mark stacks and iterate over them all.
1241 RevokeThreadLocalMarkStacks(disable_weak_ref_access);
1242 size_t count = 0;
1243 std::vector<accounting::AtomicStack<mirror::Object>*> mark_stacks;
1244 {
1245 MutexLock mu(Thread::Current(), mark_stack_lock_);
1246 // Make a copy of the mark stack vector.
1247 mark_stacks = revoked_mark_stacks_;
1248 revoked_mark_stacks_.clear();
1249 }
1250 for (accounting::AtomicStack<mirror::Object>* mark_stack : mark_stacks) {
1251 for (StackReference<mirror::Object>* p = mark_stack->Begin(); p != mark_stack->End(); ++p) {
1252 mirror::Object* to_ref = p->AsMirrorPtr();
1253 ProcessMarkStackRef(to_ref);
1254 ++count;
1255 }
1256 {
1257 MutexLock mu(Thread::Current(), mark_stack_lock_);
1258 if (pooled_mark_stacks_.size() >= kMarkStackPoolSize) {
1259 // The pool has enough. Delete it.
1260 delete mark_stack;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001261 } else {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001262 // Otherwise, put it into the pool for later reuse.
1263 mark_stack->Reset();
1264 pooled_mark_stacks_.push_back(mark_stack);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001265 }
1266 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001267 }
1268 return count;
1269}
1270
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001271inline void ConcurrentCopying::ProcessMarkStackRef(mirror::Object* to_ref) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001272 DCHECK(!region_space_->IsInFromSpace(to_ref));
1273 if (kUseBakerReadBarrier) {
1274 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr())
1275 << " " << to_ref << " " << to_ref->GetReadBarrierPointer()
1276 << " is_marked=" << IsMarked(to_ref);
1277 }
1278 // Scan ref fields.
1279 Scan(to_ref);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001280 if (kUseBakerReadBarrier) {
1281 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr())
1282 << " " << to_ref << " " << to_ref->GetReadBarrierPointer()
1283 << " is_marked=" << IsMarked(to_ref);
1284 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001285#ifdef USE_BAKER_OR_BROOKS_READ_BARRIER
1286 if (UNLIKELY((to_ref->GetClass<kVerifyNone, kWithoutReadBarrier>()->IsTypeOfReferenceClass() &&
1287 to_ref->AsReference()->GetReferent<kWithoutReadBarrier>() != nullptr &&
1288 !IsInToSpace(to_ref->AsReference()->GetReferent<kWithoutReadBarrier>())))) {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001289 // Leave this reference gray in the queue so that GetReferent() will trigger a read barrier. We
1290 // will change it to white later in ReferenceQueue::DequeuePendingReference().
Richard Uhlere3627402016-02-02 13:36:55 -08001291 DCHECK(to_ref->AsReference()->GetPendingNext() != nullptr) << "Left unenqueued ref gray " << to_ref;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001292 } else {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001293 // We may occasionally leave a reference white in the queue if its referent happens to be
1294 // concurrently marked after the Scan() call above has enqueued the Reference, in which case the
1295 // above IsInToSpace() evaluates to true and we change the color from gray to white here in this
1296 // else block.
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001297 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001298 bool success = to_ref->AtomicSetReadBarrierPointer</*kCasRelease*/true>(
1299 ReadBarrier::GrayPtr(),
1300 ReadBarrier::WhitePtr());
1301 DCHECK(success) << "Must succeed as we won the race.";
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001302 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001303 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001304#else
1305 DCHECK(!kUseBakerReadBarrier);
1306#endif
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001307
1308 if (region_space_->IsInUnevacFromSpace(to_ref)) {
1309 // Add to the live bytes per unevacuated from space. Note this code is always run by the
1310 // GC-running thread (no synchronization required).
1311 DCHECK(region_space_bitmap_->Test(to_ref));
1312 // Disable the read barrier in SizeOf for performance, which is safe.
1313 size_t obj_size = to_ref->SizeOf<kDefaultVerifyFlags, kWithoutReadBarrier>();
1314 size_t alloc_size = RoundUp(obj_size, space::RegionSpace::kAlignment);
1315 region_space_->AddLiveBytes(to_ref, alloc_size);
1316 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001317 if (ReadBarrier::kEnableToSpaceInvariantChecks || kIsDebugBuild) {
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001318 AssertToSpaceInvariantObjectVisitor visitor(this);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001319 visitor(to_ref);
1320 }
1321}
1322
1323void ConcurrentCopying::SwitchToSharedMarkStackMode() {
1324 Thread* self = Thread::Current();
1325 CHECK(thread_running_gc_ != nullptr);
1326 CHECK_EQ(self, thread_running_gc_);
1327 CHECK(self->GetThreadLocalMarkStack() == nullptr);
1328 MarkStackMode before_mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1329 CHECK_EQ(static_cast<uint32_t>(before_mark_stack_mode),
1330 static_cast<uint32_t>(kMarkStackModeThreadLocal));
1331 mark_stack_mode_.StoreRelaxed(kMarkStackModeShared);
1332 CHECK(weak_ref_access_enabled_.LoadRelaxed());
1333 weak_ref_access_enabled_.StoreRelaxed(false);
1334 QuasiAtomic::ThreadFenceForConstructor();
1335 // Process the thread local mark stacks one last time after switching to the shared mark stack
1336 // mode and disable weak ref accesses.
1337 ProcessThreadLocalMarkStacks(true);
1338 if (kVerboseMode) {
1339 LOG(INFO) << "Switched to shared mark stack mode and disabled weak ref access";
1340 }
1341}
1342
1343void ConcurrentCopying::SwitchToGcExclusiveMarkStackMode() {
1344 Thread* self = Thread::Current();
1345 CHECK(thread_running_gc_ != nullptr);
1346 CHECK_EQ(self, thread_running_gc_);
1347 CHECK(self->GetThreadLocalMarkStack() == nullptr);
1348 MarkStackMode before_mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1349 CHECK_EQ(static_cast<uint32_t>(before_mark_stack_mode),
1350 static_cast<uint32_t>(kMarkStackModeShared));
1351 mark_stack_mode_.StoreRelaxed(kMarkStackModeGcExclusive);
1352 QuasiAtomic::ThreadFenceForConstructor();
1353 if (kVerboseMode) {
1354 LOG(INFO) << "Switched to GC exclusive mark stack mode";
1355 }
1356}
1357
1358void ConcurrentCopying::CheckEmptyMarkStack() {
1359 Thread* self = Thread::Current();
1360 CHECK(thread_running_gc_ != nullptr);
1361 CHECK_EQ(self, thread_running_gc_);
1362 CHECK(self->GetThreadLocalMarkStack() == nullptr);
1363 MarkStackMode mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1364 if (mark_stack_mode == kMarkStackModeThreadLocal) {
1365 // Thread-local mark stack mode.
1366 RevokeThreadLocalMarkStacks(false);
1367 MutexLock mu(Thread::Current(), mark_stack_lock_);
1368 if (!revoked_mark_stacks_.empty()) {
1369 for (accounting::AtomicStack<mirror::Object>* mark_stack : revoked_mark_stacks_) {
1370 while (!mark_stack->IsEmpty()) {
1371 mirror::Object* obj = mark_stack->PopBack();
1372 if (kUseBakerReadBarrier) {
1373 mirror::Object* rb_ptr = obj->GetReadBarrierPointer();
1374 LOG(INFO) << "On mark queue : " << obj << " " << PrettyTypeOf(obj) << " rb_ptr=" << rb_ptr
1375 << " is_marked=" << IsMarked(obj);
1376 } else {
1377 LOG(INFO) << "On mark queue : " << obj << " " << PrettyTypeOf(obj)
1378 << " is_marked=" << IsMarked(obj);
1379 }
1380 }
1381 }
1382 LOG(FATAL) << "mark stack is not empty";
1383 }
1384 } else {
1385 // Shared, GC-exclusive, or off.
1386 MutexLock mu(Thread::Current(), mark_stack_lock_);
1387 CHECK(gc_mark_stack_->IsEmpty());
1388 CHECK(revoked_mark_stacks_.empty());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001389 }
1390}
1391
1392void ConcurrentCopying::SweepSystemWeaks(Thread* self) {
1393 TimingLogger::ScopedTiming split("SweepSystemWeaks", GetTimings());
1394 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier97509952015-07-13 14:35:43 -07001395 Runtime::Current()->SweepSystemWeaks(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001396}
1397
1398void ConcurrentCopying::Sweep(bool swap_bitmaps) {
1399 {
1400 TimingLogger::ScopedTiming t("MarkStackAsLive", GetTimings());
1401 accounting::ObjectStack* live_stack = heap_->GetLiveStack();
1402 if (kEnableFromSpaceAccountingCheck) {
1403 CHECK_GE(live_stack_freeze_size_, live_stack->Size());
1404 }
1405 heap_->MarkAllocStackAsLive(live_stack);
1406 live_stack->Reset();
1407 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001408 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001409 TimingLogger::ScopedTiming split("Sweep", GetTimings());
1410 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
1411 if (space->IsContinuousMemMapAllocSpace()) {
1412 space::ContinuousMemMapAllocSpace* alloc_space = space->AsContinuousMemMapAllocSpace();
Mathieu Chartier763a31e2015-11-16 16:05:55 -08001413 if (space == region_space_ || immune_spaces_.ContainsSpace(space)) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001414 continue;
1415 }
1416 TimingLogger::ScopedTiming split2(
1417 alloc_space->IsZygoteSpace() ? "SweepZygoteSpace" : "SweepAllocSpace", GetTimings());
1418 RecordFree(alloc_space->Sweep(swap_bitmaps));
1419 }
1420 }
1421 SweepLargeObjects(swap_bitmaps);
1422}
1423
1424void ConcurrentCopying::SweepLargeObjects(bool swap_bitmaps) {
1425 TimingLogger::ScopedTiming split("SweepLargeObjects", GetTimings());
1426 RecordFreeLOS(heap_->GetLargeObjectsSpace()->Sweep(swap_bitmaps));
1427}
1428
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001429void ConcurrentCopying::ReclaimPhase() {
1430 TimingLogger::ScopedTiming split("ReclaimPhase", GetTimings());
1431 if (kVerboseMode) {
1432 LOG(INFO) << "GC ReclaimPhase";
1433 }
1434 Thread* self = Thread::Current();
1435
1436 {
1437 // Double-check that the mark stack is empty.
1438 // Note: need to set this after VerifyNoFromSpaceRef().
1439 is_asserting_to_space_invariant_ = false;
1440 QuasiAtomic::ThreadFenceForConstructor();
1441 if (kVerboseMode) {
1442 LOG(INFO) << "Issue an empty check point. ";
1443 }
1444 IssueEmptyCheckpoint();
1445 // Disable the check.
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001446 is_mark_stack_push_disallowed_.StoreSequentiallyConsistent(0);
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001447 if (kUseBakerReadBarrier) {
1448 updated_all_immune_objects_.StoreSequentiallyConsistent(false);
1449 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001450 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001451 }
1452
1453 {
1454 // Record freed objects.
1455 TimingLogger::ScopedTiming split2("RecordFree", GetTimings());
1456 // Don't include thread-locals that are in the to-space.
1457 uint64_t from_bytes = region_space_->GetBytesAllocatedInFromSpace();
1458 uint64_t from_objects = region_space_->GetObjectsAllocatedInFromSpace();
1459 uint64_t unevac_from_bytes = region_space_->GetBytesAllocatedInUnevacFromSpace();
1460 uint64_t unevac_from_objects = region_space_->GetObjectsAllocatedInUnevacFromSpace();
1461 uint64_t to_bytes = bytes_moved_.LoadSequentiallyConsistent();
1462 uint64_t to_objects = objects_moved_.LoadSequentiallyConsistent();
1463 if (kEnableFromSpaceAccountingCheck) {
1464 CHECK_EQ(from_space_num_objects_at_first_pause_, from_objects + unevac_from_objects);
1465 CHECK_EQ(from_space_num_bytes_at_first_pause_, from_bytes + unevac_from_bytes);
1466 }
1467 CHECK_LE(to_objects, from_objects);
1468 CHECK_LE(to_bytes, from_bytes);
1469 int64_t freed_bytes = from_bytes - to_bytes;
1470 int64_t freed_objects = from_objects - to_objects;
1471 if (kVerboseMode) {
1472 LOG(INFO) << "RecordFree:"
1473 << " from_bytes=" << from_bytes << " from_objects=" << from_objects
1474 << " unevac_from_bytes=" << unevac_from_bytes << " unevac_from_objects=" << unevac_from_objects
1475 << " to_bytes=" << to_bytes << " to_objects=" << to_objects
1476 << " freed_bytes=" << freed_bytes << " freed_objects=" << freed_objects
1477 << " from_space size=" << region_space_->FromSpaceSize()
1478 << " unevac_from_space size=" << region_space_->UnevacFromSpaceSize()
1479 << " to_space size=" << region_space_->ToSpaceSize();
1480 LOG(INFO) << "(before) num_bytes_allocated=" << heap_->num_bytes_allocated_.LoadSequentiallyConsistent();
1481 }
1482 RecordFree(ObjectBytePair(freed_objects, freed_bytes));
1483 if (kVerboseMode) {
1484 LOG(INFO) << "(after) num_bytes_allocated=" << heap_->num_bytes_allocated_.LoadSequentiallyConsistent();
1485 }
1486 }
1487
1488 {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001489 TimingLogger::ScopedTiming split4("ClearFromSpace", GetTimings());
1490 region_space_->ClearFromSpace();
1491 }
1492
1493 {
1494 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001495 Sweep(false);
1496 SwapBitmaps();
1497 heap_->UnBindBitmaps();
1498
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001499 // Delete the region bitmap.
1500 DCHECK(region_space_bitmap_ != nullptr);
1501 delete region_space_bitmap_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001502 region_space_bitmap_ = nullptr;
1503 }
1504
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001505 CheckEmptyMarkStack();
1506
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001507 if (kVerboseMode) {
1508 LOG(INFO) << "GC end of ReclaimPhase";
1509 }
1510}
1511
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001512// Assert the to-space invariant.
1513void ConcurrentCopying::AssertToSpaceInvariant(mirror::Object* obj, MemberOffset offset,
1514 mirror::Object* ref) {
1515 CHECK(heap_->collector_type_ == kCollectorTypeCC) << static_cast<size_t>(heap_->collector_type_);
1516 if (is_asserting_to_space_invariant_) {
1517 if (region_space_->IsInToSpace(ref)) {
1518 // OK.
1519 return;
1520 } else if (region_space_->IsInUnevacFromSpace(ref)) {
1521 CHECK(region_space_bitmap_->Test(ref)) << ref;
1522 } else if (region_space_->IsInFromSpace(ref)) {
1523 // Not OK. Do extra logging.
1524 if (obj != nullptr) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001525 LogFromSpaceRefHolder(obj, offset);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001526 }
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001527 ref->GetLockWord(false).Dump(LOG(INTERNAL_FATAL));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001528 CHECK(false) << "Found from-space ref " << ref << " " << PrettyTypeOf(ref);
1529 } else {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001530 AssertToSpaceInvariantInNonMovingSpace(obj, ref);
1531 }
1532 }
1533}
1534
1535class RootPrinter {
1536 public:
1537 RootPrinter() { }
1538
1539 template <class MirrorType>
1540 ALWAYS_INLINE void VisitRootIfNonNull(mirror::CompressedReference<MirrorType>* root)
Mathieu Chartier90443472015-07-16 20:32:27 -07001541 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001542 if (!root->IsNull()) {
1543 VisitRoot(root);
1544 }
1545 }
1546
1547 template <class MirrorType>
1548 void VisitRoot(mirror::Object** root)
Mathieu Chartier90443472015-07-16 20:32:27 -07001549 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001550 LOG(INTERNAL_FATAL) << "root=" << root << " ref=" << *root;
1551 }
1552
1553 template <class MirrorType>
1554 void VisitRoot(mirror::CompressedReference<MirrorType>* root)
Mathieu Chartier90443472015-07-16 20:32:27 -07001555 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001556 LOG(INTERNAL_FATAL) << "root=" << root << " ref=" << root->AsMirrorPtr();
1557 }
1558};
1559
1560void ConcurrentCopying::AssertToSpaceInvariant(GcRootSource* gc_root_source,
1561 mirror::Object* ref) {
1562 CHECK(heap_->collector_type_ == kCollectorTypeCC) << static_cast<size_t>(heap_->collector_type_);
1563 if (is_asserting_to_space_invariant_) {
1564 if (region_space_->IsInToSpace(ref)) {
1565 // OK.
1566 return;
1567 } else if (region_space_->IsInUnevacFromSpace(ref)) {
1568 CHECK(region_space_bitmap_->Test(ref)) << ref;
1569 } else if (region_space_->IsInFromSpace(ref)) {
1570 // Not OK. Do extra logging.
1571 if (gc_root_source == nullptr) {
1572 // No info.
1573 } else if (gc_root_source->HasArtField()) {
1574 ArtField* field = gc_root_source->GetArtField();
1575 LOG(INTERNAL_FATAL) << "gc root in field " << field << " " << PrettyField(field);
1576 RootPrinter root_printer;
1577 field->VisitRoots(root_printer);
1578 } else if (gc_root_source->HasArtMethod()) {
1579 ArtMethod* method = gc_root_source->GetArtMethod();
1580 LOG(INTERNAL_FATAL) << "gc root in method " << method << " " << PrettyMethod(method);
1581 RootPrinter root_printer;
Mathieu Chartier1147b9b2015-09-14 18:50:08 -07001582 method->VisitRoots(root_printer, sizeof(void*));
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001583 }
1584 ref->GetLockWord(false).Dump(LOG(INTERNAL_FATAL));
1585 region_space_->DumpNonFreeRegions(LOG(INTERNAL_FATAL));
1586 PrintFileToLog("/proc/self/maps", LogSeverity::INTERNAL_FATAL);
1587 MemMap::DumpMaps(LOG(INTERNAL_FATAL), true);
1588 CHECK(false) << "Found from-space ref " << ref << " " << PrettyTypeOf(ref);
1589 } else {
1590 AssertToSpaceInvariantInNonMovingSpace(nullptr, ref);
1591 }
1592 }
1593}
1594
1595void ConcurrentCopying::LogFromSpaceRefHolder(mirror::Object* obj, MemberOffset offset) {
1596 if (kUseBakerReadBarrier) {
1597 LOG(INFO) << "holder=" << obj << " " << PrettyTypeOf(obj)
1598 << " holder rb_ptr=" << obj->GetReadBarrierPointer();
1599 } else {
1600 LOG(INFO) << "holder=" << obj << " " << PrettyTypeOf(obj);
1601 }
1602 if (region_space_->IsInFromSpace(obj)) {
1603 LOG(INFO) << "holder is in the from-space.";
1604 } else if (region_space_->IsInToSpace(obj)) {
1605 LOG(INFO) << "holder is in the to-space.";
1606 } else if (region_space_->IsInUnevacFromSpace(obj)) {
1607 LOG(INFO) << "holder is in the unevac from-space.";
1608 if (region_space_bitmap_->Test(obj)) {
1609 LOG(INFO) << "holder is marked in the region space bitmap.";
1610 } else {
1611 LOG(INFO) << "holder is not marked in the region space bitmap.";
1612 }
1613 } else {
1614 // In a non-moving space.
Mathieu Chartier763a31e2015-11-16 16:05:55 -08001615 if (immune_spaces_.ContainsObject(obj)) {
1616 LOG(INFO) << "holder is in an immune image or the zygote space.";
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001617 } else {
Mathieu Chartier763a31e2015-11-16 16:05:55 -08001618 LOG(INFO) << "holder is in a non-immune, non-moving (or main) space.";
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001619 accounting::ContinuousSpaceBitmap* mark_bitmap =
1620 heap_mark_bitmap_->GetContinuousSpaceBitmap(obj);
1621 accounting::LargeObjectBitmap* los_bitmap =
1622 heap_mark_bitmap_->GetLargeObjectBitmap(obj);
1623 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
1624 bool is_los = mark_bitmap == nullptr;
1625 if (!is_los && mark_bitmap->Test(obj)) {
1626 LOG(INFO) << "holder is marked in the mark bit map.";
1627 } else if (is_los && los_bitmap->Test(obj)) {
1628 LOG(INFO) << "holder is marked in the los bit map.";
1629 } else {
1630 // If ref is on the allocation stack, then it is considered
1631 // mark/alive (but not necessarily on the live stack.)
1632 if (IsOnAllocStack(obj)) {
1633 LOG(INFO) << "holder is on the alloc stack.";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001634 } else {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001635 LOG(INFO) << "holder is not marked or on the alloc stack.";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001636 }
1637 }
1638 }
1639 }
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001640 LOG(INFO) << "offset=" << offset.SizeValue();
1641}
1642
1643void ConcurrentCopying::AssertToSpaceInvariantInNonMovingSpace(mirror::Object* obj,
1644 mirror::Object* ref) {
1645 // In a non-moving spaces. Check that the ref is marked.
Mathieu Chartier763a31e2015-11-16 16:05:55 -08001646 if (immune_spaces_.ContainsObject(ref)) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001647 if (kUseBakerReadBarrier) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001648 // Immune object may not be gray if called from the GC.
1649 if (Thread::Current() == thread_running_gc_ && !gc_grays_immune_objects_) {
1650 return;
1651 }
1652 bool updated_all_immune_objects = updated_all_immune_objects_.LoadSequentiallyConsistent();
1653 CHECK(updated_all_immune_objects || ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr())
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001654 << "Unmarked immune space ref. obj=" << obj << " rb_ptr="
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001655 << (obj != nullptr ? obj->GetReadBarrierPointer() : nullptr)
1656 << " ref=" << ref << " ref rb_ptr=" << ref->GetReadBarrierPointer()
1657 << " updated_all_immune_objects=" << updated_all_immune_objects;
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001658 }
1659 } else {
1660 accounting::ContinuousSpaceBitmap* mark_bitmap =
1661 heap_mark_bitmap_->GetContinuousSpaceBitmap(ref);
1662 accounting::LargeObjectBitmap* los_bitmap =
1663 heap_mark_bitmap_->GetLargeObjectBitmap(ref);
1664 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
1665 bool is_los = mark_bitmap == nullptr;
1666 if ((!is_los && mark_bitmap->Test(ref)) ||
1667 (is_los && los_bitmap->Test(ref))) {
1668 // OK.
1669 } else {
1670 // If ref is on the allocation stack, then it may not be
1671 // marked live, but considered marked/alive (but not
1672 // necessarily on the live stack).
1673 CHECK(IsOnAllocStack(ref)) << "Unmarked ref that's not on the allocation stack. "
1674 << "obj=" << obj << " ref=" << ref;
1675 }
1676 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001677}
1678
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001679// Used to scan ref fields of an object.
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001680class ConcurrentCopying::RefFieldsVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001681 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001682 explicit RefFieldsVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001683 : collector_(collector) {}
1684
1685 void operator()(mirror::Object* obj, MemberOffset offset, bool /* is_static */)
Mathieu Chartier90443472015-07-16 20:32:27 -07001686 const ALWAYS_INLINE SHARED_REQUIRES(Locks::mutator_lock_)
1687 SHARED_REQUIRES(Locks::heap_bitmap_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001688 collector_->Process(obj, offset);
1689 }
1690
1691 void operator()(mirror::Class* klass, mirror::Reference* ref) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001692 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001693 CHECK(klass->IsTypeOfReferenceClass());
1694 collector_->DelayReferenceReferent(klass, ref);
1695 }
1696
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001697 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001698 ALWAYS_INLINE
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001699 SHARED_REQUIRES(Locks::mutator_lock_) {
1700 if (!root->IsNull()) {
1701 VisitRoot(root);
1702 }
1703 }
1704
1705 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001706 ALWAYS_INLINE
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001707 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001708 collector_->MarkRoot</*kGrayImmuneObject*/false>(root);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001709 }
1710
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001711 private:
1712 ConcurrentCopying* const collector_;
1713};
1714
1715// Scan ref fields of an object.
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001716inline void ConcurrentCopying::Scan(mirror::Object* to_ref) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001717 DCHECK(!region_space_->IsInFromSpace(to_ref));
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001718 DCHECK_EQ(Thread::Current(), thread_running_gc_);
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001719 RefFieldsVisitor visitor(this);
Hiroshi Yamauchi5496f692016-02-17 13:29:59 -08001720 // Disable the read barrier for a performance reason.
1721 to_ref->VisitReferences</*kVisitNativeRoots*/true, kDefaultVerifyFlags, kWithoutReadBarrier>(
1722 visitor, visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001723}
1724
1725// Process a field.
1726inline void ConcurrentCopying::Process(mirror::Object* obj, MemberOffset offset) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001727 DCHECK_EQ(Thread::Current(), thread_running_gc_);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001728 mirror::Object* ref = obj->GetFieldObject<
1729 mirror::Object, kVerifyNone, kWithoutReadBarrier, false>(offset);
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001730 mirror::Object* to_ref = Mark</*kGrayImmuneObject*/false>(ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001731 if (to_ref == ref) {
1732 return;
1733 }
1734 // This may fail if the mutator writes to the field at the same time. But it's ok.
1735 mirror::Object* expected_ref = ref;
1736 mirror::Object* new_ref = to_ref;
1737 do {
1738 if (expected_ref !=
1739 obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier, false>(offset)) {
1740 // It was updated by the mutator.
1741 break;
1742 }
Hiroshi Yamauchifed3e2f2015-10-20 11:11:56 -07001743 } while (!obj->CasFieldWeakRelaxedObjectWithoutWriteBarrier<
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001744 false, false, kVerifyNone>(offset, expected_ref, new_ref));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001745}
1746
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001747// Process some roots.
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001748inline void ConcurrentCopying::VisitRoots(
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001749 mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED) {
1750 for (size_t i = 0; i < count; ++i) {
1751 mirror::Object** root = roots[i];
1752 mirror::Object* ref = *root;
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001753 mirror::Object* to_ref = Mark(ref);
1754 if (to_ref == ref) {
Mathieu Chartier4809d0a2015-04-07 10:39:04 -07001755 continue;
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001756 }
1757 Atomic<mirror::Object*>* addr = reinterpret_cast<Atomic<mirror::Object*>*>(root);
1758 mirror::Object* expected_ref = ref;
1759 mirror::Object* new_ref = to_ref;
1760 do {
1761 if (expected_ref != addr->LoadRelaxed()) {
1762 // It was updated by the mutator.
1763 break;
1764 }
Hiroshi Yamauchifed3e2f2015-10-20 11:11:56 -07001765 } while (!addr->CompareExchangeWeakRelaxed(expected_ref, new_ref));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001766 }
1767}
1768
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001769template<bool kGrayImmuneObject>
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001770inline void ConcurrentCopying::MarkRoot(mirror::CompressedReference<mirror::Object>* root) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001771 DCHECK(!root->IsNull());
1772 mirror::Object* const ref = root->AsMirrorPtr();
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001773 mirror::Object* to_ref = Mark<kGrayImmuneObject>(ref);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001774 if (to_ref != ref) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001775 auto* addr = reinterpret_cast<Atomic<mirror::CompressedReference<mirror::Object>>*>(root);
1776 auto expected_ref = mirror::CompressedReference<mirror::Object>::FromMirrorPtr(ref);
1777 auto new_ref = mirror::CompressedReference<mirror::Object>::FromMirrorPtr(to_ref);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001778 // If the cas fails, then it was updated by the mutator.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001779 do {
1780 if (ref != addr->LoadRelaxed().AsMirrorPtr()) {
1781 // It was updated by the mutator.
1782 break;
1783 }
Hiroshi Yamauchifed3e2f2015-10-20 11:11:56 -07001784 } while (!addr->CompareExchangeWeakRelaxed(expected_ref, new_ref));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001785 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001786}
1787
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001788inline void ConcurrentCopying::VisitRoots(
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001789 mirror::CompressedReference<mirror::Object>** roots, size_t count,
1790 const RootInfo& info ATTRIBUTE_UNUSED) {
1791 for (size_t i = 0; i < count; ++i) {
1792 mirror::CompressedReference<mirror::Object>* const root = roots[i];
1793 if (!root->IsNull()) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001794 // kGrayImmuneObject is true because this is used for the thread flip.
1795 MarkRoot</*kGrayImmuneObject*/true>(root);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001796 }
1797 }
1798}
1799
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001800// Temporary set gc_grays_immune_objects_ to true in a scope if the current thread is GC.
1801class ConcurrentCopying::ScopedGcGraysImmuneObjects {
1802 public:
1803 explicit ScopedGcGraysImmuneObjects(ConcurrentCopying* collector)
1804 : collector_(collector), enabled_(false) {
1805 if (kUseBakerReadBarrier &&
1806 collector_->thread_running_gc_ == Thread::Current() &&
1807 !collector_->gc_grays_immune_objects_) {
1808 collector_->gc_grays_immune_objects_ = true;
1809 enabled_ = true;
1810 }
1811 }
1812
1813 ~ScopedGcGraysImmuneObjects() {
1814 if (kUseBakerReadBarrier &&
1815 collector_->thread_running_gc_ == Thread::Current() &&
1816 enabled_) {
1817 DCHECK(collector_->gc_grays_immune_objects_);
1818 collector_->gc_grays_immune_objects_ = false;
1819 }
1820 }
1821
1822 private:
1823 ConcurrentCopying* const collector_;
1824 bool enabled_;
1825};
1826
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001827// Fill the given memory block with a dummy object. Used to fill in a
1828// copy of objects that was lost in race.
1829void ConcurrentCopying::FillWithDummyObject(mirror::Object* dummy_obj, size_t byte_size) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001830 // GC doesn't gray immune objects while scanning immune objects. But we need to trigger the read
1831 // barriers here because we need the updated reference to the int array class, etc. Temporary set
1832 // gc_grays_immune_objects_ to true so that we won't cause a DCHECK failure in MarkImmuneSpace().
1833 ScopedGcGraysImmuneObjects scoped_gc_gray_immune_objects(this);
Roland Levillain14d90572015-07-16 10:52:26 +01001834 CHECK_ALIGNED(byte_size, kObjectAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001835 memset(dummy_obj, 0, byte_size);
1836 mirror::Class* int_array_class = mirror::IntArray::GetArrayClass();
1837 CHECK(int_array_class != nullptr);
1838 AssertToSpaceInvariant(nullptr, MemberOffset(0), int_array_class);
1839 size_t component_size = int_array_class->GetComponentSize();
1840 CHECK_EQ(component_size, sizeof(int32_t));
1841 size_t data_offset = mirror::Array::DataOffset(component_size).SizeValue();
1842 if (data_offset > byte_size) {
1843 // An int array is too big. Use java.lang.Object.
1844 mirror::Class* java_lang_Object = WellKnownClasses::ToClass(WellKnownClasses::java_lang_Object);
1845 AssertToSpaceInvariant(nullptr, MemberOffset(0), java_lang_Object);
1846 CHECK_EQ(byte_size, java_lang_Object->GetObjectSize());
1847 dummy_obj->SetClass(java_lang_Object);
1848 CHECK_EQ(byte_size, dummy_obj->SizeOf());
1849 } else {
1850 // Use an int array.
1851 dummy_obj->SetClass(int_array_class);
1852 CHECK(dummy_obj->IsArrayInstance());
1853 int32_t length = (byte_size - data_offset) / component_size;
1854 dummy_obj->AsArray()->SetLength(length);
1855 CHECK_EQ(dummy_obj->AsArray()->GetLength(), length)
1856 << "byte_size=" << byte_size << " length=" << length
1857 << " component_size=" << component_size << " data_offset=" << data_offset;
1858 CHECK_EQ(byte_size, dummy_obj->SizeOf())
1859 << "byte_size=" << byte_size << " length=" << length
1860 << " component_size=" << component_size << " data_offset=" << data_offset;
1861 }
1862}
1863
1864// Reuse the memory blocks that were copy of objects that were lost in race.
1865mirror::Object* ConcurrentCopying::AllocateInSkippedBlock(size_t alloc_size) {
1866 // Try to reuse the blocks that were unused due to CAS failures.
Roland Levillain14d90572015-07-16 10:52:26 +01001867 CHECK_ALIGNED(alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001868 Thread* self = Thread::Current();
1869 size_t min_object_size = RoundUp(sizeof(mirror::Object), space::RegionSpace::kAlignment);
1870 MutexLock mu(self, skipped_blocks_lock_);
1871 auto it = skipped_blocks_map_.lower_bound(alloc_size);
1872 if (it == skipped_blocks_map_.end()) {
1873 // Not found.
1874 return nullptr;
1875 }
1876 {
1877 size_t byte_size = it->first;
1878 CHECK_GE(byte_size, alloc_size);
1879 if (byte_size > alloc_size && byte_size - alloc_size < min_object_size) {
1880 // If remainder would be too small for a dummy object, retry with a larger request size.
1881 it = skipped_blocks_map_.lower_bound(alloc_size + min_object_size);
1882 if (it == skipped_blocks_map_.end()) {
1883 // Not found.
1884 return nullptr;
1885 }
Roland Levillain14d90572015-07-16 10:52:26 +01001886 CHECK_ALIGNED(it->first - alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001887 CHECK_GE(it->first - alloc_size, min_object_size)
1888 << "byte_size=" << byte_size << " it->first=" << it->first << " alloc_size=" << alloc_size;
1889 }
1890 }
1891 // Found a block.
1892 CHECK(it != skipped_blocks_map_.end());
1893 size_t byte_size = it->first;
1894 uint8_t* addr = it->second;
1895 CHECK_GE(byte_size, alloc_size);
1896 CHECK(region_space_->IsInToSpace(reinterpret_cast<mirror::Object*>(addr)));
Roland Levillain14d90572015-07-16 10:52:26 +01001897 CHECK_ALIGNED(byte_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001898 if (kVerboseMode) {
1899 LOG(INFO) << "Reusing skipped bytes : " << reinterpret_cast<void*>(addr) << ", " << byte_size;
1900 }
1901 skipped_blocks_map_.erase(it);
1902 memset(addr, 0, byte_size);
1903 if (byte_size > alloc_size) {
1904 // Return the remainder to the map.
Roland Levillain14d90572015-07-16 10:52:26 +01001905 CHECK_ALIGNED(byte_size - alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001906 CHECK_GE(byte_size - alloc_size, min_object_size);
1907 FillWithDummyObject(reinterpret_cast<mirror::Object*>(addr + alloc_size),
1908 byte_size - alloc_size);
1909 CHECK(region_space_->IsInToSpace(reinterpret_cast<mirror::Object*>(addr + alloc_size)));
1910 skipped_blocks_map_.insert(std::make_pair(byte_size - alloc_size, addr + alloc_size));
1911 }
1912 return reinterpret_cast<mirror::Object*>(addr);
1913}
1914
1915mirror::Object* ConcurrentCopying::Copy(mirror::Object* from_ref) {
1916 DCHECK(region_space_->IsInFromSpace(from_ref));
1917 // No read barrier to avoid nested RB that might violate the to-space
1918 // invariant. Note that from_ref is a from space ref so the SizeOf()
1919 // call will access the from-space meta objects, but it's ok and necessary.
1920 size_t obj_size = from_ref->SizeOf<kDefaultVerifyFlags, kWithoutReadBarrier>();
1921 size_t region_space_alloc_size = RoundUp(obj_size, space::RegionSpace::kAlignment);
1922 size_t region_space_bytes_allocated = 0U;
1923 size_t non_moving_space_bytes_allocated = 0U;
1924 size_t bytes_allocated = 0U;
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001925 size_t dummy;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001926 mirror::Object* to_ref = region_space_->AllocNonvirtual<true>(
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001927 region_space_alloc_size, &region_space_bytes_allocated, nullptr, &dummy);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001928 bytes_allocated = region_space_bytes_allocated;
1929 if (to_ref != nullptr) {
1930 DCHECK_EQ(region_space_alloc_size, region_space_bytes_allocated);
1931 }
1932 bool fall_back_to_non_moving = false;
1933 if (UNLIKELY(to_ref == nullptr)) {
1934 // Failed to allocate in the region space. Try the skipped blocks.
1935 to_ref = AllocateInSkippedBlock(region_space_alloc_size);
1936 if (to_ref != nullptr) {
1937 // Succeeded to allocate in a skipped block.
1938 if (heap_->use_tlab_) {
1939 // This is necessary for the tlab case as it's not accounted in the space.
1940 region_space_->RecordAlloc(to_ref);
1941 }
1942 bytes_allocated = region_space_alloc_size;
1943 } else {
1944 // Fall back to the non-moving space.
1945 fall_back_to_non_moving = true;
1946 if (kVerboseMode) {
1947 LOG(INFO) << "Out of memory in the to-space. Fall back to non-moving. skipped_bytes="
1948 << to_space_bytes_skipped_.LoadSequentiallyConsistent()
1949 << " skipped_objects=" << to_space_objects_skipped_.LoadSequentiallyConsistent();
1950 }
1951 fall_back_to_non_moving = true;
1952 to_ref = heap_->non_moving_space_->Alloc(Thread::Current(), obj_size,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001953 &non_moving_space_bytes_allocated, nullptr, &dummy);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001954 CHECK(to_ref != nullptr) << "Fall-back non-moving space allocation failed";
1955 bytes_allocated = non_moving_space_bytes_allocated;
1956 // Mark it in the mark bitmap.
1957 accounting::ContinuousSpaceBitmap* mark_bitmap =
1958 heap_mark_bitmap_->GetContinuousSpaceBitmap(to_ref);
1959 CHECK(mark_bitmap != nullptr);
1960 CHECK(!mark_bitmap->AtomicTestAndSet(to_ref));
1961 }
1962 }
1963 DCHECK(to_ref != nullptr);
1964
1965 // Attempt to install the forward pointer. This is in a loop as the
1966 // lock word atomic write can fail.
1967 while (true) {
1968 // Copy the object. TODO: copy only the lockword in the second iteration and on?
1969 memcpy(to_ref, from_ref, obj_size);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001970
1971 LockWord old_lock_word = to_ref->GetLockWord(false);
1972
1973 if (old_lock_word.GetState() == LockWord::kForwardingAddress) {
1974 // Lost the race. Another thread (either GC or mutator) stored
1975 // the forwarding pointer first. Make the lost copy (to_ref)
1976 // look like a valid but dead (dummy) object and keep it for
1977 // future reuse.
1978 FillWithDummyObject(to_ref, bytes_allocated);
1979 if (!fall_back_to_non_moving) {
1980 DCHECK(region_space_->IsInToSpace(to_ref));
1981 if (bytes_allocated > space::RegionSpace::kRegionSize) {
1982 // Free the large alloc.
1983 region_space_->FreeLarge(to_ref, bytes_allocated);
1984 } else {
1985 // Record the lost copy for later reuse.
1986 heap_->num_bytes_allocated_.FetchAndAddSequentiallyConsistent(bytes_allocated);
1987 to_space_bytes_skipped_.FetchAndAddSequentiallyConsistent(bytes_allocated);
1988 to_space_objects_skipped_.FetchAndAddSequentiallyConsistent(1);
1989 MutexLock mu(Thread::Current(), skipped_blocks_lock_);
1990 skipped_blocks_map_.insert(std::make_pair(bytes_allocated,
1991 reinterpret_cast<uint8_t*>(to_ref)));
1992 }
1993 } else {
1994 DCHECK(heap_->non_moving_space_->HasAddress(to_ref));
1995 DCHECK_EQ(bytes_allocated, non_moving_space_bytes_allocated);
1996 // Free the non-moving-space chunk.
1997 accounting::ContinuousSpaceBitmap* mark_bitmap =
1998 heap_mark_bitmap_->GetContinuousSpaceBitmap(to_ref);
1999 CHECK(mark_bitmap != nullptr);
2000 CHECK(mark_bitmap->Clear(to_ref));
2001 heap_->non_moving_space_->Free(Thread::Current(), to_ref);
2002 }
2003
2004 // Get the winner's forward ptr.
2005 mirror::Object* lost_fwd_ptr = to_ref;
2006 to_ref = reinterpret_cast<mirror::Object*>(old_lock_word.ForwardingAddress());
2007 CHECK(to_ref != nullptr);
2008 CHECK_NE(to_ref, lost_fwd_ptr);
2009 CHECK(region_space_->IsInToSpace(to_ref) || heap_->non_moving_space_->HasAddress(to_ref));
2010 CHECK_NE(to_ref->GetLockWord(false).GetState(), LockWord::kForwardingAddress);
2011 return to_ref;
2012 }
2013
Hiroshi Yamauchi60f63f52015-04-23 16:12:40 -07002014 // Set the gray ptr.
2015 if (kUseBakerReadBarrier) {
2016 to_ref->SetReadBarrierPointer(ReadBarrier::GrayPtr());
2017 }
2018
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002019 LockWord new_lock_word = LockWord::FromForwardingAddress(reinterpret_cast<size_t>(to_ref));
2020
2021 // Try to atomically write the fwd ptr.
2022 bool success = from_ref->CasLockWordWeakSequentiallyConsistent(old_lock_word, new_lock_word);
2023 if (LIKELY(success)) {
2024 // The CAS succeeded.
2025 objects_moved_.FetchAndAddSequentiallyConsistent(1);
2026 bytes_moved_.FetchAndAddSequentiallyConsistent(region_space_alloc_size);
2027 if (LIKELY(!fall_back_to_non_moving)) {
2028 DCHECK(region_space_->IsInToSpace(to_ref));
2029 } else {
2030 DCHECK(heap_->non_moving_space_->HasAddress(to_ref));
2031 DCHECK_EQ(bytes_allocated, non_moving_space_bytes_allocated);
2032 }
2033 if (kUseBakerReadBarrier) {
2034 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr());
2035 }
2036 DCHECK(GetFwdPtr(from_ref) == to_ref);
2037 CHECK_NE(to_ref->GetLockWord(false).GetState(), LockWord::kForwardingAddress);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002038 PushOntoMarkStack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002039 return to_ref;
2040 } else {
2041 // The CAS failed. It may have lost the race or may have failed
2042 // due to monitor/hashcode ops. Either way, retry.
2043 }
2044 }
2045}
2046
2047mirror::Object* ConcurrentCopying::IsMarked(mirror::Object* from_ref) {
2048 DCHECK(from_ref != nullptr);
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08002049 space::RegionSpace::RegionType rtype = region_space_->GetRegionType(from_ref);
2050 if (rtype == space::RegionSpace::RegionType::kRegionTypeToSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002051 // It's already marked.
2052 return from_ref;
2053 }
2054 mirror::Object* to_ref;
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08002055 if (rtype == space::RegionSpace::RegionType::kRegionTypeFromSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002056 to_ref = GetFwdPtr(from_ref);
2057 DCHECK(to_ref == nullptr || region_space_->IsInToSpace(to_ref) ||
2058 heap_->non_moving_space_->HasAddress(to_ref))
2059 << "from_ref=" << from_ref << " to_ref=" << to_ref;
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08002060 } else if (rtype == space::RegionSpace::RegionType::kRegionTypeUnevacFromSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002061 if (region_space_bitmap_->Test(from_ref)) {
2062 to_ref = from_ref;
2063 } else {
2064 to_ref = nullptr;
2065 }
2066 } else {
2067 // from_ref is in a non-moving space.
Mathieu Chartier763a31e2015-11-16 16:05:55 -08002068 if (immune_spaces_.ContainsObject(from_ref)) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002069 // An immune object is alive.
2070 to_ref = from_ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002071 } else {
2072 // Non-immune non-moving space. Use the mark bitmap.
2073 accounting::ContinuousSpaceBitmap* mark_bitmap =
2074 heap_mark_bitmap_->GetContinuousSpaceBitmap(from_ref);
2075 accounting::LargeObjectBitmap* los_bitmap =
2076 heap_mark_bitmap_->GetLargeObjectBitmap(from_ref);
2077 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
2078 bool is_los = mark_bitmap == nullptr;
2079 if (!is_los && mark_bitmap->Test(from_ref)) {
2080 // Already marked.
2081 to_ref = from_ref;
2082 } else if (is_los && los_bitmap->Test(from_ref)) {
2083 // Already marked in LOS.
2084 to_ref = from_ref;
2085 } else {
2086 // Not marked.
2087 if (IsOnAllocStack(from_ref)) {
2088 // If on the allocation stack, it's considered marked.
2089 to_ref = from_ref;
2090 } else {
2091 // Not marked.
2092 to_ref = nullptr;
2093 }
2094 }
2095 }
2096 }
2097 return to_ref;
2098}
2099
2100bool ConcurrentCopying::IsOnAllocStack(mirror::Object* ref) {
2101 QuasiAtomic::ThreadFenceAcquire();
2102 accounting::ObjectStack* alloc_stack = GetAllocationStack();
Mathieu Chartiercb535da2015-01-23 13:50:03 -08002103 return alloc_stack->Contains(ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002104}
2105
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002106mirror::Object* ConcurrentCopying::MarkNonMoving(mirror::Object* ref) {
2107 // ref is in a non-moving space (from_ref == to_ref).
2108 DCHECK(!region_space_->HasAddress(ref)) << ref;
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002109 DCHECK(!immune_spaces_.ContainsObject(ref));
2110 // Use the mark bitmap.
2111 accounting::ContinuousSpaceBitmap* mark_bitmap =
2112 heap_mark_bitmap_->GetContinuousSpaceBitmap(ref);
2113 accounting::LargeObjectBitmap* los_bitmap =
2114 heap_mark_bitmap_->GetLargeObjectBitmap(ref);
2115 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
2116 bool is_los = mark_bitmap == nullptr;
2117 if (!is_los && mark_bitmap->Test(ref)) {
2118 // Already marked.
2119 if (kUseBakerReadBarrier) {
2120 DCHECK(ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr() ||
2121 ref->GetReadBarrierPointer() == ReadBarrier::WhitePtr());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002122 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002123 } else if (is_los && los_bitmap->Test(ref)) {
2124 // Already marked in LOS.
2125 if (kUseBakerReadBarrier) {
2126 DCHECK(ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr() ||
2127 ref->GetReadBarrierPointer() == ReadBarrier::WhitePtr());
2128 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002129 } else {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002130 // Not marked.
2131 if (IsOnAllocStack(ref)) {
2132 // If it's on the allocation stack, it's considered marked. Keep it white.
2133 // Objects on the allocation stack need not be marked.
2134 if (!is_los) {
2135 DCHECK(!mark_bitmap->Test(ref));
2136 } else {
2137 DCHECK(!los_bitmap->Test(ref));
Nicolas Geoffrayddeb1722016-06-28 08:25:59 +00002138 }
Nicolas Geoffrayddeb1722016-06-28 08:25:59 +00002139 if (kUseBakerReadBarrier) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002140 DCHECK_EQ(ref->GetReadBarrierPointer(), ReadBarrier::WhitePtr());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002141 }
2142 } else {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002143 // For the baker-style RB, we need to handle 'false-gray' cases. See the
2144 // kRegionTypeUnevacFromSpace-case comment in Mark().
2145 if (kUseBakerReadBarrier) {
2146 // Test the bitmap first to reduce the chance of false gray cases.
2147 if ((!is_los && mark_bitmap->Test(ref)) ||
2148 (is_los && los_bitmap->Test(ref))) {
2149 return ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002150 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002151 }
2152 // Not marked or on the allocation stack. Try to mark it.
2153 // This may or may not succeed, which is ok.
2154 bool cas_success = false;
2155 if (kUseBakerReadBarrier) {
2156 cas_success = ref->AtomicSetReadBarrierPointer(ReadBarrier::WhitePtr(),
2157 ReadBarrier::GrayPtr());
2158 }
2159 if (!is_los && mark_bitmap->AtomicTestAndSet(ref)) {
2160 // Already marked.
2161 if (kUseBakerReadBarrier && cas_success &&
2162 ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr()) {
2163 PushOntoFalseGrayStack(ref);
2164 }
2165 } else if (is_los && los_bitmap->AtomicTestAndSet(ref)) {
2166 // Already marked in LOS.
2167 if (kUseBakerReadBarrier && cas_success &&
2168 ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr()) {
2169 PushOntoFalseGrayStack(ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002170 }
2171 } else {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002172 // Newly marked.
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08002173 if (kUseBakerReadBarrier) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002174 DCHECK_EQ(ref->GetReadBarrierPointer(), ReadBarrier::GrayPtr());
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08002175 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002176 PushOntoMarkStack(ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002177 }
2178 }
2179 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002180 return ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002181}
2182
2183void ConcurrentCopying::FinishPhase() {
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -08002184 Thread* const self = Thread::Current();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002185 {
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -08002186 MutexLock mu(self, mark_stack_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002187 CHECK_EQ(pooled_mark_stacks_.size(), kMarkStackPoolSize);
2188 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002189 region_space_ = nullptr;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002190 {
2191 MutexLock mu(Thread::Current(), skipped_blocks_lock_);
2192 skipped_blocks_map_.clear();
2193 }
Mathieu Chartier56fe2582016-07-14 13:30:03 -07002194 {
2195 ReaderMutexLock mu(self, *Locks::mutator_lock_);
Mathieu Chartier21328a12016-07-22 10:47:45 -07002196 {
2197 WriterMutexLock mu2(self, *Locks::heap_bitmap_lock_);
2198 heap_->ClearMarkedObjects();
2199 }
2200 if (kUseBakerReadBarrier && kFilterModUnionCards) {
2201 TimingLogger::ScopedTiming split("FilterModUnionCards", GetTimings());
2202 ReaderMutexLock mu2(self, *Locks::heap_bitmap_lock_);
2203 gc::Heap* const heap = Runtime::Current()->GetHeap();
2204 for (space::ContinuousSpace* space : immune_spaces_.GetSpaces()) {
2205 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
2206 accounting::ModUnionTable* table = heap->FindModUnionTableFromSpace(space);
2207 // Filter out cards that don't need to be set.
2208 if (table != nullptr) {
2209 table->FilterCards();
2210 }
2211 }
2212 }
Mathieu Chartier56fe2582016-07-14 13:30:03 -07002213 }
2214 if (measure_read_barrier_slow_path_) {
2215 MutexLock mu(self, rb_slow_path_histogram_lock_);
2216 rb_slow_path_time_histogram_.AdjustAndAddValue(rb_slow_path_ns_.LoadRelaxed());
2217 rb_slow_path_count_total_ += rb_slow_path_count_.LoadRelaxed();
2218 rb_slow_path_count_gc_total_ += rb_slow_path_count_gc_.LoadRelaxed();
2219 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002220}
2221
Mathieu Chartier97509952015-07-13 14:35:43 -07002222bool ConcurrentCopying::IsMarkedHeapReference(mirror::HeapReference<mirror::Object>* field) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002223 mirror::Object* from_ref = field->AsMirrorPtr();
Mathieu Chartier97509952015-07-13 14:35:43 -07002224 mirror::Object* to_ref = IsMarked(from_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002225 if (to_ref == nullptr) {
2226 return false;
2227 }
2228 if (from_ref != to_ref) {
2229 QuasiAtomic::ThreadFenceRelease();
2230 field->Assign(to_ref);
2231 QuasiAtomic::ThreadFenceSequentiallyConsistent();
2232 }
2233 return true;
2234}
2235
Mathieu Chartier97509952015-07-13 14:35:43 -07002236mirror::Object* ConcurrentCopying::MarkObject(mirror::Object* from_ref) {
2237 return Mark(from_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002238}
2239
2240void ConcurrentCopying::DelayReferenceReferent(mirror::Class* klass, mirror::Reference* reference) {
Mathieu Chartier97509952015-07-13 14:35:43 -07002241 heap_->GetReferenceProcessor()->DelayReferenceReferent(klass, reference, this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002242}
2243
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002244void ConcurrentCopying::ProcessReferences(Thread* self) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002245 TimingLogger::ScopedTiming split("ProcessReferences", GetTimings());
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002246 // We don't really need to lock the heap bitmap lock as we use CAS to mark in bitmaps.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002247 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
2248 GetHeap()->GetReferenceProcessor()->ProcessReferences(
Mathieu Chartier97509952015-07-13 14:35:43 -07002249 true /*concurrent*/, GetTimings(), GetCurrentIteration()->GetClearSoftReferences(), this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002250}
2251
2252void ConcurrentCopying::RevokeAllThreadLocalBuffers() {
2253 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
2254 region_space_->RevokeAllThreadLocalBuffers();
2255}
2256
Mathieu Chartier56fe2582016-07-14 13:30:03 -07002257mirror::Object* ConcurrentCopying::MarkFromReadBarrierWithMeasurements(mirror::Object* from_ref) {
2258 if (Thread::Current() != thread_running_gc_) {
2259 rb_slow_path_count_.FetchAndAddRelaxed(1u);
2260 } else {
2261 rb_slow_path_count_gc_.FetchAndAddRelaxed(1u);
2262 }
2263 ScopedTrace tr(__FUNCTION__);
2264 const uint64_t start_time = measure_read_barrier_slow_path_ ? NanoTime() : 0u;
2265 mirror::Object* ret = Mark(from_ref);
2266 if (measure_read_barrier_slow_path_) {
2267 rb_slow_path_ns_.FetchAndAddRelaxed(NanoTime() - start_time);
2268 }
2269 return ret;
2270}
2271
2272void ConcurrentCopying::DumpPerformanceInfo(std::ostream& os) {
2273 GarbageCollector::DumpPerformanceInfo(os);
2274 MutexLock mu(Thread::Current(), rb_slow_path_histogram_lock_);
2275 if (rb_slow_path_time_histogram_.SampleSize() > 0) {
2276 Histogram<uint64_t>::CumulativeData cumulative_data;
2277 rb_slow_path_time_histogram_.CreateHistogram(&cumulative_data);
2278 rb_slow_path_time_histogram_.PrintConfidenceIntervals(os, 0.99, cumulative_data);
2279 }
2280 if (rb_slow_path_count_total_ > 0) {
2281 os << "Slow path count " << rb_slow_path_count_total_ << "\n";
2282 }
2283 if (rb_slow_path_count_gc_total_ > 0) {
2284 os << "GC slow path count " << rb_slow_path_count_gc_total_ << "\n";
2285 }
2286}
2287
Hiroshi Yamauchid5307ec2014-03-27 21:07:51 -07002288} // namespace collector
2289} // namespace gc
2290} // namespace art