blob: 071537db91a413a42e3b9ee363cf77dd1de14b21 [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"
Andreas Gampe542451c2016-07-26 09:02:02 -070020#include "base/enums.h"
Mathieu Chartier56fe2582016-07-14 13:30:03 -070021#include "base/histogram-inl.h"
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070022#include "base/stl_util.h"
Mathieu Chartier56fe2582016-07-14 13:30:03 -070023#include "base/systrace.h"
Mathieu Chartiera6b1ead2015-10-06 10:32:38 -070024#include "debugger.h"
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080025#include "gc/accounting/heap_bitmap-inl.h"
Mathieu Chartier21328a12016-07-22 10:47:45 -070026#include "gc/accounting/mod_union_table-inl.h"
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080027#include "gc/accounting/space_bitmap-inl.h"
Mathieu Chartier3cf22532015-07-09 15:15:09 -070028#include "gc/reference_processor.h"
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080029#include "gc/space/image_space.h"
Mathieu Chartier073b16c2015-11-10 14:13:23 -080030#include "gc/space/space-inl.h"
Mathieu Chartier4a26f172016-01-26 14:26:18 -080031#include "image-inl.h"
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080032#include "intern_table.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070033#include "mirror/class-inl.h"
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080034#include "mirror/object-inl.h"
35#include "scoped_thread_state_change.h"
36#include "thread-inl.h"
37#include "thread_list.h"
38#include "well_known_classes.h"
39
Hiroshi Yamauchid5307ec2014-03-27 21:07:51 -070040namespace art {
41namespace gc {
42namespace collector {
43
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -070044static constexpr size_t kDefaultGcMarkStackSize = 2 * MB;
Mathieu Chartier21328a12016-07-22 10:47:45 -070045// If kFilterModUnionCards then we attempt to filter cards that don't need to be dirty in the mod
46// union table. Disabled since it does not seem to help the pause much.
47static constexpr bool kFilterModUnionCards = kIsDebugBuild;
Mathieu Chartierd6636d32016-07-28 11:02:38 -070048// If kDisallowReadBarrierDuringScan is true then the GC aborts if there are any that occur during
49// ConcurrentCopying::Scan. May be used to diagnose possibly unnecessary read barriers.
50// Only enabled for kIsDebugBuild to avoid performance hit.
51static constexpr bool kDisallowReadBarrierDuringScan = kIsDebugBuild;
Mathieu Chartier36a270a2016-07-28 18:08:51 -070052// Slow path mark stack size, increase this if the stack is getting full and it is causing
53// performance problems.
54static constexpr size_t kReadBarrierMarkStackSize = 512 * KB;
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -070055
Mathieu Chartier56fe2582016-07-14 13:30:03 -070056ConcurrentCopying::ConcurrentCopying(Heap* heap,
57 const std::string& name_prefix,
58 bool measure_read_barrier_slow_path)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080059 : GarbageCollector(heap,
60 name_prefix + (name_prefix.empty() ? "" : " ") +
61 "concurrent copying + mark sweep"),
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070062 region_space_(nullptr), gc_barrier_(new Barrier(0)),
63 gc_mark_stack_(accounting::ObjectStack::Create("concurrent copying gc mark stack",
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -070064 kDefaultGcMarkStackSize,
65 kDefaultGcMarkStackSize)),
Mathieu Chartier36a270a2016-07-28 18:08:51 -070066 rb_mark_bit_stack_(accounting::ObjectStack::Create("rb copying gc mark stack",
67 kReadBarrierMarkStackSize,
68 kReadBarrierMarkStackSize)),
69 rb_mark_bit_stack_full_(false),
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070070 mark_stack_lock_("concurrent copying mark stack lock", kMarkSweepMarkStackLock),
71 thread_running_gc_(nullptr),
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080072 is_marking_(false), is_active_(false), is_asserting_to_space_invariant_(false),
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -070073 region_space_bitmap_(nullptr),
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070074 heap_mark_bitmap_(nullptr), live_stack_freeze_size_(0), mark_stack_mode_(kMarkStackModeOff),
75 weak_ref_access_enabled_(true),
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080076 skipped_blocks_lock_("concurrent copying bytes blocks lock", kMarkSweepMarkStackLock),
Mathieu Chartier56fe2582016-07-14 13:30:03 -070077 measure_read_barrier_slow_path_(measure_read_barrier_slow_path),
78 rb_slow_path_ns_(0),
79 rb_slow_path_count_(0),
80 rb_slow_path_count_gc_(0),
81 rb_slow_path_histogram_lock_("Read barrier histogram lock"),
82 rb_slow_path_time_histogram_("Mutator time in read barrier slow path", 500, 32),
83 rb_slow_path_count_total_(0),
84 rb_slow_path_count_gc_total_(0),
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080085 rb_table_(heap_->GetReadBarrierTable()),
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -070086 force_evacuate_all_(false),
87 immune_gray_stack_lock_("concurrent copying immune gray stack lock",
88 kMarkSweepMarkStackLock) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080089 static_assert(space::RegionSpace::kRegionSize == accounting::ReadBarrierTable::kRegionSize,
90 "The region space size and the read barrier table region size must match");
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070091 Thread* self = Thread::Current();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080092 {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080093 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
94 // Cache this so that we won't have to lock heap_bitmap_lock_ in
95 // Mark() which could cause a nested lock on heap_bitmap_lock_
96 // when GC causes a RB while doing GC or a lock order violation
97 // (class_linker_lock_ and heap_bitmap_lock_).
98 heap_mark_bitmap_ = heap->GetMarkBitmap();
99 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700100 {
101 MutexLock mu(self, mark_stack_lock_);
102 for (size_t i = 0; i < kMarkStackPoolSize; ++i) {
103 accounting::AtomicStack<mirror::Object>* mark_stack =
104 accounting::AtomicStack<mirror::Object>::Create(
105 "thread local mark stack", kMarkStackSize, kMarkStackSize);
106 pooled_mark_stacks_.push_back(mark_stack);
107 }
108 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800109}
110
Mathieu Chartierb19ccb12015-07-15 10:24:16 -0700111void ConcurrentCopying::MarkHeapReference(mirror::HeapReference<mirror::Object>* from_ref) {
112 // Used for preserving soft references, should be OK to not have a CAS here since there should be
113 // no other threads which can trigger read barriers on the same referent during reference
114 // processing.
115 from_ref->Assign(Mark(from_ref->AsMirrorPtr()));
Mathieu Chartier81187812015-07-15 14:24:07 -0700116 DCHECK(!from_ref->IsNull());
Mathieu Chartier97509952015-07-13 14:35:43 -0700117}
118
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800119ConcurrentCopying::~ConcurrentCopying() {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700120 STLDeleteElements(&pooled_mark_stacks_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800121}
122
123void ConcurrentCopying::RunPhases() {
124 CHECK(kUseBakerReadBarrier || kUseTableLookupReadBarrier);
125 CHECK(!is_active_);
126 is_active_ = true;
127 Thread* self = Thread::Current();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700128 thread_running_gc_ = self;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800129 Locks::mutator_lock_->AssertNotHeld(self);
130 {
131 ReaderMutexLock mu(self, *Locks::mutator_lock_);
132 InitializePhase();
133 }
134 FlipThreadRoots();
135 {
136 ReaderMutexLock mu(self, *Locks::mutator_lock_);
137 MarkingPhase();
138 }
139 // Verify no from space refs. This causes a pause.
140 if (kEnableNoFromSpaceRefsVerification || kIsDebugBuild) {
141 TimingLogger::ScopedTiming split("(Paused)VerifyNoFromSpaceReferences", GetTimings());
142 ScopedPause pause(this);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700143 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800144 if (kVerboseMode) {
145 LOG(INFO) << "Verifying no from-space refs";
146 }
147 VerifyNoFromSpaceReferences();
Mathieu Chartier720e71a2015-04-06 17:10:58 -0700148 if (kVerboseMode) {
149 LOG(INFO) << "Done verifying no from-space refs";
150 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700151 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800152 }
153 {
154 ReaderMutexLock mu(self, *Locks::mutator_lock_);
155 ReclaimPhase();
156 }
157 FinishPhase();
158 CHECK(is_active_);
159 is_active_ = false;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700160 thread_running_gc_ = nullptr;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800161}
162
163void ConcurrentCopying::BindBitmaps() {
164 Thread* self = Thread::Current();
165 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
166 // Mark all of the spaces we never collect as immune.
167 for (const auto& space : heap_->GetContinuousSpaces()) {
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800168 if (space->GetGcRetentionPolicy() == space::kGcRetentionPolicyNeverCollect ||
169 space->GetGcRetentionPolicy() == space::kGcRetentionPolicyFullCollect) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800170 CHECK(space->IsZygoteSpace() || space->IsImageSpace());
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800171 immune_spaces_.AddSpace(space);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800172 } else if (space == region_space_) {
173 accounting::ContinuousSpaceBitmap* bitmap =
174 accounting::ContinuousSpaceBitmap::Create("cc region space bitmap",
175 space->Begin(), space->Capacity());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800176 region_space_bitmap_ = bitmap;
177 }
178 }
179}
180
181void ConcurrentCopying::InitializePhase() {
182 TimingLogger::ScopedTiming split("InitializePhase", GetTimings());
183 if (kVerboseMode) {
184 LOG(INFO) << "GC InitializePhase";
185 LOG(INFO) << "Region-space : " << reinterpret_cast<void*>(region_space_->Begin()) << "-"
186 << reinterpret_cast<void*>(region_space_->Limit());
187 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700188 CheckEmptyMarkStack();
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800189 if (kIsDebugBuild) {
190 MutexLock mu(Thread::Current(), mark_stack_lock_);
191 CHECK(false_gray_stack_.empty());
192 }
Mathieu Chartier56fe2582016-07-14 13:30:03 -0700193
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700194 rb_mark_bit_stack_full_ = false;
Mathieu Chartier56fe2582016-07-14 13:30:03 -0700195 mark_from_read_barrier_measurements_ = measure_read_barrier_slow_path_;
196 if (measure_read_barrier_slow_path_) {
197 rb_slow_path_ns_.StoreRelaxed(0);
198 rb_slow_path_count_.StoreRelaxed(0);
199 rb_slow_path_count_gc_.StoreRelaxed(0);
200 }
201
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800202 immune_spaces_.Reset();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800203 bytes_moved_.StoreRelaxed(0);
204 objects_moved_.StoreRelaxed(0);
205 if (GetCurrentIteration()->GetGcCause() == kGcCauseExplicit ||
206 GetCurrentIteration()->GetGcCause() == kGcCauseForNativeAlloc ||
207 GetCurrentIteration()->GetClearSoftReferences()) {
208 force_evacuate_all_ = true;
209 } else {
210 force_evacuate_all_ = false;
211 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700212 if (kUseBakerReadBarrier) {
213 updated_all_immune_objects_.StoreRelaxed(false);
214 // GC may gray immune objects in the thread flip.
215 gc_grays_immune_objects_ = true;
216 if (kIsDebugBuild) {
217 MutexLock mu(Thread::Current(), immune_gray_stack_lock_);
218 DCHECK(immune_gray_stack_.empty());
219 }
220 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800221 BindBitmaps();
222 if (kVerboseMode) {
223 LOG(INFO) << "force_evacuate_all=" << force_evacuate_all_;
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800224 LOG(INFO) << "Largest immune region: " << immune_spaces_.GetLargestImmuneRegion().Begin()
225 << "-" << immune_spaces_.GetLargestImmuneRegion().End();
226 for (space::ContinuousSpace* space : immune_spaces_.GetSpaces()) {
227 LOG(INFO) << "Immune space: " << *space;
228 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800229 LOG(INFO) << "GC end of InitializePhase";
230 }
231}
232
233// Used to switch the thread roots of a thread from from-space refs to to-space refs.
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700234class ConcurrentCopying::ThreadFlipVisitor : public Closure, public RootVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800235 public:
Roland Levillain3887c462015-08-12 18:15:42 +0100236 ThreadFlipVisitor(ConcurrentCopying* concurrent_copying, bool use_tlab)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800237 : concurrent_copying_(concurrent_copying), use_tlab_(use_tlab) {
238 }
239
Mathieu Chartier90443472015-07-16 20:32:27 -0700240 virtual void Run(Thread* thread) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800241 // Note: self is not necessarily equal to thread since thread may be suspended.
242 Thread* self = Thread::Current();
243 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
244 << thread->GetState() << " thread " << thread << " self " << self;
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700245 thread->SetIsGcMarking(true);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800246 if (use_tlab_ && thread->HasTlab()) {
247 if (ConcurrentCopying::kEnableFromSpaceAccountingCheck) {
248 // This must come before the revoke.
249 size_t thread_local_objects = thread->GetThreadLocalObjectsAllocated();
250 concurrent_copying_->region_space_->RevokeThreadLocalBuffers(thread);
251 reinterpret_cast<Atomic<size_t>*>(&concurrent_copying_->from_space_num_objects_at_first_pause_)->
252 FetchAndAddSequentiallyConsistent(thread_local_objects);
253 } else {
254 concurrent_copying_->region_space_->RevokeThreadLocalBuffers(thread);
255 }
256 }
257 if (kUseThreadLocalAllocationStack) {
258 thread->RevokeThreadLocalAllocationStack();
259 }
260 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700261 // We can use the non-CAS VisitRoots functions below because we update thread-local GC roots
262 // only.
263 thread->VisitRoots(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800264 concurrent_copying_->GetBarrier().Pass(self);
265 }
266
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700267 void VisitRoots(mirror::Object*** roots,
268 size_t count,
269 const RootInfo& info ATTRIBUTE_UNUSED)
270 SHARED_REQUIRES(Locks::mutator_lock_) {
271 for (size_t i = 0; i < count; ++i) {
272 mirror::Object** root = roots[i];
273 mirror::Object* ref = *root;
274 if (ref != nullptr) {
275 mirror::Object* to_ref = concurrent_copying_->Mark(ref);
276 if (to_ref != ref) {
277 *root = to_ref;
278 }
279 }
280 }
281 }
282
283 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots,
284 size_t count,
285 const RootInfo& info ATTRIBUTE_UNUSED)
286 SHARED_REQUIRES(Locks::mutator_lock_) {
287 for (size_t i = 0; i < count; ++i) {
288 mirror::CompressedReference<mirror::Object>* const root = roots[i];
289 if (!root->IsNull()) {
290 mirror::Object* ref = root->AsMirrorPtr();
291 mirror::Object* to_ref = concurrent_copying_->Mark(ref);
292 if (to_ref != ref) {
293 root->Assign(to_ref);
294 }
295 }
296 }
297 }
298
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800299 private:
300 ConcurrentCopying* const concurrent_copying_;
301 const bool use_tlab_;
302};
303
304// Called back from Runtime::FlipThreadRoots() during a pause.
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700305class ConcurrentCopying::FlipCallback : public Closure {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800306 public:
307 explicit FlipCallback(ConcurrentCopying* concurrent_copying)
308 : concurrent_copying_(concurrent_copying) {
309 }
310
Mathieu Chartier90443472015-07-16 20:32:27 -0700311 virtual void Run(Thread* thread) OVERRIDE REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800312 ConcurrentCopying* cc = concurrent_copying_;
313 TimingLogger::ScopedTiming split("(Paused)FlipCallback", cc->GetTimings());
314 // Note: self is not necessarily equal to thread since thread may be suspended.
315 Thread* self = Thread::Current();
316 CHECK(thread == self);
317 Locks::mutator_lock_->AssertExclusiveHeld(self);
318 cc->region_space_->SetFromSpace(cc->rb_table_, cc->force_evacuate_all_);
Mathieu Chartiera4f6af92015-08-11 17:35:25 -0700319 cc->SwapStacks();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800320 if (ConcurrentCopying::kEnableFromSpaceAccountingCheck) {
321 cc->RecordLiveStackFreezeSize(self);
322 cc->from_space_num_objects_at_first_pause_ = cc->region_space_->GetObjectsAllocated();
323 cc->from_space_num_bytes_at_first_pause_ = cc->region_space_->GetBytesAllocated();
324 }
325 cc->is_marking_ = true;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700326 cc->mark_stack_mode_.StoreRelaxed(ConcurrentCopying::kMarkStackModeThreadLocal);
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800327 if (kIsDebugBuild) {
328 cc->region_space_->AssertAllRegionLiveBytesZeroOrCleared();
329 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800330 if (UNLIKELY(Runtime::Current()->IsActiveTransaction())) {
Mathieu Chartier184c9dc2015-03-05 13:20:54 -0800331 CHECK(Runtime::Current()->IsAotCompiler());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800332 TimingLogger::ScopedTiming split2("(Paused)VisitTransactionRoots", cc->GetTimings());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700333 Runtime::Current()->VisitTransactionRoots(cc);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800334 }
Mathieu Chartier21328a12016-07-22 10:47:45 -0700335 if (kUseBakerReadBarrier && kGrayDirtyImmuneObjects) {
336 cc->GrayAllDirtyImmuneObjects();
337 if (kIsDebugBuild) {
338 // Check that all non-gray immune objects only refernce immune objects.
339 cc->VerifyGrayImmuneObjects();
340 }
341 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800342 }
343
344 private:
345 ConcurrentCopying* const concurrent_copying_;
346};
347
Mathieu Chartier21328a12016-07-22 10:47:45 -0700348class ConcurrentCopying::VerifyGrayImmuneObjectsVisitor {
349 public:
350 explicit VerifyGrayImmuneObjectsVisitor(ConcurrentCopying* collector)
351 : collector_(collector) {}
352
353 void operator()(mirror::Object* obj, MemberOffset offset, bool /* is_static */)
354 const ALWAYS_INLINE SHARED_REQUIRES(Locks::mutator_lock_)
355 SHARED_REQUIRES(Locks::heap_bitmap_lock_) {
356 CheckReference(obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(offset),
357 obj, offset);
358 }
359
360 void operator()(mirror::Class* klass, mirror::Reference* ref) const
361 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
362 CHECK(klass->IsTypeOfReferenceClass());
363 CheckReference(ref->GetReferent<kWithoutReadBarrier>(),
364 ref,
365 mirror::Reference::ReferentOffset());
366 }
367
368 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
369 ALWAYS_INLINE
370 SHARED_REQUIRES(Locks::mutator_lock_) {
371 if (!root->IsNull()) {
372 VisitRoot(root);
373 }
374 }
375
376 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
377 ALWAYS_INLINE
378 SHARED_REQUIRES(Locks::mutator_lock_) {
379 CheckReference(root->AsMirrorPtr(), nullptr, MemberOffset(0));
380 }
381
382 private:
383 ConcurrentCopying* const collector_;
384
385 void CheckReference(mirror::Object* ref, mirror::Object* holder, MemberOffset offset) const
386 SHARED_REQUIRES(Locks::mutator_lock_) {
387 if (ref != nullptr) {
388 CHECK(collector_->immune_spaces_.ContainsObject(ref))
389 << "Non gray object references non immune object "<< ref << " " << PrettyTypeOf(ref)
390 << " in holder " << holder << " " << PrettyTypeOf(holder) << " offset="
391 << offset.Uint32Value();
392 }
393 }
394};
395
396void ConcurrentCopying::VerifyGrayImmuneObjects() {
397 TimingLogger::ScopedTiming split(__FUNCTION__, GetTimings());
398 for (auto& space : immune_spaces_.GetSpaces()) {
399 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
400 accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
401 VerifyGrayImmuneObjectsVisitor visitor(this);
402 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()),
403 reinterpret_cast<uintptr_t>(space->Limit()),
404 [&visitor](mirror::Object* obj)
405 SHARED_REQUIRES(Locks::mutator_lock_) {
406 // If an object is not gray, it should only have references to things in the immune spaces.
407 if (obj->GetReadBarrierPointer() != ReadBarrier::GrayPtr()) {
408 obj->VisitReferences</*kVisitNativeRoots*/true,
409 kDefaultVerifyFlags,
410 kWithoutReadBarrier>(visitor, visitor);
411 }
412 });
413 }
414}
415
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800416// Switch threads that from from-space to to-space refs. Forward/mark the thread roots.
417void ConcurrentCopying::FlipThreadRoots() {
418 TimingLogger::ScopedTiming split("FlipThreadRoots", GetTimings());
419 if (kVerboseMode) {
420 LOG(INFO) << "time=" << region_space_->Time();
421 region_space_->DumpNonFreeRegions(LOG(INFO));
422 }
423 Thread* self = Thread::Current();
424 Locks::mutator_lock_->AssertNotHeld(self);
425 gc_barrier_->Init(self, 0);
426 ThreadFlipVisitor thread_flip_visitor(this, heap_->use_tlab_);
427 FlipCallback flip_callback(this);
Hiroshi Yamauchi76f55b02015-08-21 16:10:39 -0700428 heap_->ThreadFlipBegin(self); // Sync with JNI critical calls.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800429 size_t barrier_count = Runtime::Current()->FlipThreadRoots(
430 &thread_flip_visitor, &flip_callback, this);
Hiroshi Yamauchi76f55b02015-08-21 16:10:39 -0700431 heap_->ThreadFlipEnd(self);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800432 {
433 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
434 gc_barrier_->Increment(self, barrier_count);
435 }
436 is_asserting_to_space_invariant_ = true;
437 QuasiAtomic::ThreadFenceForConstructor();
438 if (kVerboseMode) {
439 LOG(INFO) << "time=" << region_space_->Time();
440 region_space_->DumpNonFreeRegions(LOG(INFO));
441 LOG(INFO) << "GC end of FlipThreadRoots";
442 }
443}
444
Mathieu Chartier21328a12016-07-22 10:47:45 -0700445class ConcurrentCopying::GrayImmuneObjectVisitor {
446 public:
447 explicit GrayImmuneObjectVisitor() {}
448
449 ALWAYS_INLINE void operator()(mirror::Object* obj) const SHARED_REQUIRES(Locks::mutator_lock_) {
450 if (kUseBakerReadBarrier) {
451 if (kIsDebugBuild) {
452 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
453 }
454 obj->SetReadBarrierPointer(ReadBarrier::GrayPtr());
455 }
456 }
457
458 static void Callback(mirror::Object* obj, void* arg) SHARED_REQUIRES(Locks::mutator_lock_) {
459 reinterpret_cast<GrayImmuneObjectVisitor*>(arg)->operator()(obj);
460 }
461};
462
463void ConcurrentCopying::GrayAllDirtyImmuneObjects() {
464 TimingLogger::ScopedTiming split(__FUNCTION__, GetTimings());
465 gc::Heap* const heap = Runtime::Current()->GetHeap();
466 accounting::CardTable* const card_table = heap->GetCardTable();
467 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
468 for (space::ContinuousSpace* space : immune_spaces_.GetSpaces()) {
469 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
470 GrayImmuneObjectVisitor visitor;
471 accounting::ModUnionTable* table = heap->FindModUnionTableFromSpace(space);
472 // Mark all the objects on dirty cards since these may point to objects in other space.
473 // Once these are marked, the GC will eventually clear them later.
474 // Table is non null for boot image and zygote spaces. It is only null for application image
475 // spaces.
476 if (table != nullptr) {
477 // TODO: Add preclean outside the pause.
478 table->ClearCards();
479 table->VisitObjects(GrayImmuneObjectVisitor::Callback, &visitor);
480 } else {
481 // TODO: Consider having a mark bitmap for app image spaces and avoid scanning during the
482 // pause because app image spaces are all dirty pages anyways.
483 card_table->Scan<false>(space->GetMarkBitmap(), space->Begin(), space->End(), visitor);
484 }
485 }
486 // Since all of the objects that may point to other spaces are marked, we can avoid all the read
487 // barriers in the immune spaces.
488 updated_all_immune_objects_.StoreRelaxed(true);
489}
490
Mathieu Chartiera4f6af92015-08-11 17:35:25 -0700491void ConcurrentCopying::SwapStacks() {
492 heap_->SwapStacks();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800493}
494
495void ConcurrentCopying::RecordLiveStackFreezeSize(Thread* self) {
496 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
497 live_stack_freeze_size_ = heap_->GetLiveStack()->Size();
498}
499
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800500class EmptyCheckpoint : public Closure {
501 public:
502 explicit EmptyCheckpoint(ConcurrentCopying* concurrent_copying)
503 : concurrent_copying_(concurrent_copying) {
504 }
505
506 virtual void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
507 // Note: self is not necessarily equal to thread since thread may be suspended.
508 Thread* self = Thread::Current();
509 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
510 << thread->GetState() << " thread " << thread << " self " << self;
Lei Lidd9943d2015-02-02 14:24:44 +0800511 // If thread is a running mutator, then act on behalf of the garbage collector.
512 // See the code in ThreadList::RunCheckpoint.
Mathieu Chartier10d25082015-10-28 18:36:09 -0700513 concurrent_copying_->GetBarrier().Pass(self);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800514 }
515
516 private:
517 ConcurrentCopying* const concurrent_copying_;
518};
519
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700520// Used to visit objects in the immune spaces.
521inline void ConcurrentCopying::ScanImmuneObject(mirror::Object* obj) {
522 DCHECK(obj != nullptr);
523 DCHECK(immune_spaces_.ContainsObject(obj));
524 // Update the fields without graying it or pushing it onto the mark stack.
525 Scan(obj);
526}
527
528class ConcurrentCopying::ImmuneSpaceScanObjVisitor {
529 public:
530 explicit ImmuneSpaceScanObjVisitor(ConcurrentCopying* cc)
531 : collector_(cc) {}
532
Hiroshi Yamauchi5408f232016-07-29 15:07:05 -0700533 ALWAYS_INLINE void operator()(mirror::Object* obj) const SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700534 if (kUseBakerReadBarrier && kGrayDirtyImmuneObjects) {
535 if (obj->GetReadBarrierPointer() == ReadBarrier::GrayPtr()) {
536 collector_->ScanImmuneObject(obj);
537 // Done scanning the object, go back to white.
538 bool success = obj->AtomicSetReadBarrierPointer(ReadBarrier::GrayPtr(),
539 ReadBarrier::WhitePtr());
540 CHECK(success);
541 }
542 } else {
543 collector_->ScanImmuneObject(obj);
544 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700545 }
546
Hiroshi Yamauchi5408f232016-07-29 15:07:05 -0700547 static void Callback(mirror::Object* obj, void* arg) SHARED_REQUIRES(Locks::mutator_lock_) {
548 reinterpret_cast<ImmuneSpaceScanObjVisitor*>(arg)->operator()(obj);
549 }
550
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700551 private:
552 ConcurrentCopying* const collector_;
553};
554
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800555// Concurrently mark roots that are guarded by read barriers and process the mark stack.
556void ConcurrentCopying::MarkingPhase() {
557 TimingLogger::ScopedTiming split("MarkingPhase", GetTimings());
558 if (kVerboseMode) {
559 LOG(INFO) << "GC MarkingPhase";
560 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700561 CHECK(weak_ref_access_enabled_);
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700562
563 // Scan immune spaces.
564 // Update all the fields in the immune spaces first without graying the objects so that we
565 // minimize dirty pages in the immune spaces. Note mutators can concurrently access and gray some
566 // of the objects.
567 if (kUseBakerReadBarrier) {
568 gc_grays_immune_objects_ = false;
Hiroshi Yamauchi16292fc2016-06-20 20:23:34 -0700569 }
Mathieu Chartier21328a12016-07-22 10:47:45 -0700570 {
571 TimingLogger::ScopedTiming split2("ScanImmuneSpaces", GetTimings());
572 for (auto& space : immune_spaces_.GetSpaces()) {
573 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
574 accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
Hiroshi Yamauchi5408f232016-07-29 15:07:05 -0700575 accounting::ModUnionTable* table = heap_->FindModUnionTableFromSpace(space);
Mathieu Chartier21328a12016-07-22 10:47:45 -0700576 ImmuneSpaceScanObjVisitor visitor(this);
Hiroshi Yamauchi5408f232016-07-29 15:07:05 -0700577 if (kUseBakerReadBarrier && kGrayDirtyImmuneObjects && table != nullptr) {
578 table->VisitObjects(ImmuneSpaceScanObjVisitor::Callback, &visitor);
579 } else {
580 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()),
581 reinterpret_cast<uintptr_t>(space->Limit()),
582 visitor);
583 }
Mathieu Chartier21328a12016-07-22 10:47:45 -0700584 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700585 }
586 if (kUseBakerReadBarrier) {
587 // This release fence makes the field updates in the above loop visible before allowing mutator
588 // getting access to immune objects without graying it first.
589 updated_all_immune_objects_.StoreRelease(true);
590 // Now whiten immune objects concurrently accessed and grayed by mutators. We can't do this in
591 // the above loop because we would incorrectly disable the read barrier by whitening an object
592 // which may point to an unscanned, white object, breaking the to-space invariant.
593 //
594 // Make sure no mutators are in the middle of marking an immune object before whitening immune
595 // objects.
596 IssueEmptyCheckpoint();
597 MutexLock mu(Thread::Current(), immune_gray_stack_lock_);
598 if (kVerboseMode) {
599 LOG(INFO) << "immune gray stack size=" << immune_gray_stack_.size();
600 }
601 for (mirror::Object* obj : immune_gray_stack_) {
602 DCHECK(obj->GetReadBarrierPointer() == ReadBarrier::GrayPtr());
603 bool success = obj->AtomicSetReadBarrierPointer(ReadBarrier::GrayPtr(),
604 ReadBarrier::WhitePtr());
605 DCHECK(success);
606 }
607 immune_gray_stack_.clear();
608 }
609
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800610 {
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -0700611 TimingLogger::ScopedTiming split2("VisitConcurrentRoots", GetTimings());
612 Runtime::Current()->VisitConcurrentRoots(this, kVisitRootFlagAllRoots);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800613 }
614 {
615 // TODO: don't visit the transaction roots if it's not active.
616 TimingLogger::ScopedTiming split5("VisitNonThreadRoots", GetTimings());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700617 Runtime::Current()->VisitNonThreadRoots(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800618 }
619
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800620 Thread* self = Thread::Current();
621 {
Mathieu Chartiera6b1ead2015-10-06 10:32:38 -0700622 TimingLogger::ScopedTiming split7("ProcessMarkStack", GetTimings());
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700623 // We transition through three mark stack modes (thread-local, shared, GC-exclusive). The
624 // primary reasons are the fact that we need to use a checkpoint to process thread-local mark
625 // stacks, but after we disable weak refs accesses, we can't use a checkpoint due to a deadlock
626 // issue because running threads potentially blocking at WaitHoldingLocks, and that once we
627 // reach the point where we process weak references, we can avoid using a lock when accessing
628 // the GC mark stack, which makes mark stack processing more efficient.
629
630 // Process the mark stack once in the thread local stack mode. This marks most of the live
631 // objects, aside from weak ref accesses with read barriers (Reference::GetReferent() and system
632 // weaks) that may happen concurrently while we processing the mark stack and newly mark/gray
633 // objects and push refs on the mark stack.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800634 ProcessMarkStack();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700635 // Switch to the shared mark stack mode. That is, revoke and process thread-local mark stacks
636 // for the last time before transitioning to the shared mark stack mode, which would process new
637 // refs that may have been concurrently pushed onto the mark stack during the ProcessMarkStack()
638 // call above. At the same time, disable weak ref accesses using a per-thread flag. It's
639 // important to do these together in a single checkpoint so that we can ensure that mutators
640 // won't newly gray objects and push new refs onto the mark stack due to weak ref accesses and
641 // mutators safely transition to the shared mark stack mode (without leaving unprocessed refs on
642 // the thread-local mark stacks), without a race. This is why we use a thread-local weak ref
643 // access flag Thread::tls32_.weak_ref_access_enabled_ instead of the global ones.
644 SwitchToSharedMarkStackMode();
645 CHECK(!self->GetWeakRefAccessEnabled());
646 // Now that weak refs accesses are disabled, once we exhaust the shared mark stack again here
647 // (which may be non-empty if there were refs found on thread-local mark stacks during the above
648 // SwitchToSharedMarkStackMode() call), we won't have new refs to process, that is, mutators
649 // (via read barriers) have no way to produce any more refs to process. Marking converges once
650 // before we process weak refs below.
651 ProcessMarkStack();
652 CheckEmptyMarkStack();
653 // Switch to the GC exclusive mark stack mode so that we can process the mark stack without a
654 // lock from this point on.
655 SwitchToGcExclusiveMarkStackMode();
656 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800657 if (kVerboseMode) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800658 LOG(INFO) << "ProcessReferences";
659 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700660 // Process weak references. This may produce new refs to process and have them processed via
Mathieu Chartier97509952015-07-13 14:35:43 -0700661 // ProcessMarkStack (in the GC exclusive mark stack mode).
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700662 ProcessReferences(self);
663 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800664 if (kVerboseMode) {
665 LOG(INFO) << "SweepSystemWeaks";
666 }
667 SweepSystemWeaks(self);
668 if (kVerboseMode) {
669 LOG(INFO) << "SweepSystemWeaks done";
670 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700671 // Process the mark stack here one last time because the above SweepSystemWeaks() call may have
672 // marked some objects (strings alive) as hash_set::Erase() can call the hash function for
673 // arbitrary elements in the weak intern table in InternTable::Table::SweepWeaks().
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800674 ProcessMarkStack();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700675 CheckEmptyMarkStack();
676 // Re-enable weak ref accesses.
677 ReenableWeakRefAccess(self);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -0700678 // Free data for class loaders that we unloaded.
679 Runtime::Current()->GetClassLinker()->CleanupClassLoaders();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700680 // Marking is done. Disable marking.
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700681 DisableMarking();
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800682 if (kUseBakerReadBarrier) {
683 ProcessFalseGrayStack();
684 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700685 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800686 }
687
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700688 CHECK(weak_ref_access_enabled_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800689 if (kVerboseMode) {
690 LOG(INFO) << "GC end of MarkingPhase";
691 }
692}
693
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700694void ConcurrentCopying::ReenableWeakRefAccess(Thread* self) {
695 if (kVerboseMode) {
696 LOG(INFO) << "ReenableWeakRefAccess";
697 }
698 weak_ref_access_enabled_.StoreRelaxed(true); // This is for new threads.
699 QuasiAtomic::ThreadFenceForConstructor();
700 // Iterate all threads (don't need to or can't use a checkpoint) and re-enable weak ref access.
701 {
702 MutexLock mu(self, *Locks::thread_list_lock_);
703 std::list<Thread*> thread_list = Runtime::Current()->GetThreadList()->GetList();
704 for (Thread* thread : thread_list) {
705 thread->SetWeakRefAccessEnabled(true);
706 }
707 }
708 // Unblock blocking threads.
709 GetHeap()->GetReferenceProcessor()->BroadcastForSlowPath(self);
710 Runtime::Current()->BroadcastForNewSystemWeaks();
711}
712
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700713class ConcurrentCopying::DisableMarkingCheckpoint : public Closure {
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700714 public:
715 explicit DisableMarkingCheckpoint(ConcurrentCopying* concurrent_copying)
716 : concurrent_copying_(concurrent_copying) {
717 }
718
719 void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
720 // Note: self is not necessarily equal to thread since thread may be suspended.
721 Thread* self = Thread::Current();
722 DCHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
723 << thread->GetState() << " thread " << thread << " self " << self;
724 // Disable the thread-local is_gc_marking flag.
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -0700725 // Note a thread that has just started right before this checkpoint may have already this flag
726 // set to false, which is ok.
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700727 thread->SetIsGcMarking(false);
728 // If thread is a running mutator, then act on behalf of the garbage collector.
729 // See the code in ThreadList::RunCheckpoint.
Mathieu Chartier10d25082015-10-28 18:36:09 -0700730 concurrent_copying_->GetBarrier().Pass(self);
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700731 }
732
733 private:
734 ConcurrentCopying* const concurrent_copying_;
735};
736
737void ConcurrentCopying::IssueDisableMarkingCheckpoint() {
738 Thread* self = Thread::Current();
739 DisableMarkingCheckpoint check_point(this);
740 ThreadList* thread_list = Runtime::Current()->GetThreadList();
741 gc_barrier_->Init(self, 0);
742 size_t barrier_count = thread_list->RunCheckpoint(&check_point);
743 // If there are no threads to wait which implies that all the checkpoint functions are finished,
744 // then no need to release the mutator lock.
745 if (barrier_count == 0) {
746 return;
747 }
748 // Release locks then wait for all mutator threads to pass the barrier.
749 Locks::mutator_lock_->SharedUnlock(self);
750 {
751 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
752 gc_barrier_->Increment(self, barrier_count);
753 }
754 Locks::mutator_lock_->SharedLock(self);
755}
756
757void ConcurrentCopying::DisableMarking() {
758 // Change the global is_marking flag to false. Do a fence before doing a checkpoint to update the
759 // thread-local flags so that a new thread starting up will get the correct is_marking flag.
760 is_marking_ = false;
761 QuasiAtomic::ThreadFenceForConstructor();
762 // Use a checkpoint to turn off the thread-local is_gc_marking flags and to ensure no threads are
763 // still in the middle of a read barrier which may have a from-space ref cached in a local
764 // variable.
765 IssueDisableMarkingCheckpoint();
766 if (kUseTableLookupReadBarrier) {
767 heap_->rb_table_->ClearAll();
768 DCHECK(heap_->rb_table_->IsAllCleared());
769 }
770 is_mark_stack_push_disallowed_.StoreSequentiallyConsistent(1);
771 mark_stack_mode_.StoreSequentiallyConsistent(kMarkStackModeOff);
772}
773
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800774void ConcurrentCopying::PushOntoFalseGrayStack(mirror::Object* ref) {
775 CHECK(kUseBakerReadBarrier);
776 DCHECK(ref != nullptr);
777 MutexLock mu(Thread::Current(), mark_stack_lock_);
778 false_gray_stack_.push_back(ref);
779}
780
781void ConcurrentCopying::ProcessFalseGrayStack() {
782 CHECK(kUseBakerReadBarrier);
783 // Change the objects on the false gray stack from gray to white.
784 MutexLock mu(Thread::Current(), mark_stack_lock_);
785 for (mirror::Object* obj : false_gray_stack_) {
786 DCHECK(IsMarked(obj));
787 // The object could be white here if a thread got preempted after a success at the
788 // AtomicSetReadBarrierPointer in Mark(), GC started marking through it (but not finished so
789 // still gray), and the thread ran to register it onto the false gray stack.
790 if (obj->GetReadBarrierPointer() == ReadBarrier::GrayPtr()) {
791 bool success = obj->AtomicSetReadBarrierPointer(ReadBarrier::GrayPtr(),
792 ReadBarrier::WhitePtr());
793 DCHECK(success);
794 }
795 }
796 false_gray_stack_.clear();
797}
798
799
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800800void ConcurrentCopying::IssueEmptyCheckpoint() {
801 Thread* self = Thread::Current();
802 EmptyCheckpoint check_point(this);
803 ThreadList* thread_list = Runtime::Current()->GetThreadList();
804 gc_barrier_->Init(self, 0);
805 size_t barrier_count = thread_list->RunCheckpoint(&check_point);
Lei Lidd9943d2015-02-02 14:24:44 +0800806 // If there are no threads to wait which implys that all the checkpoint functions are finished,
807 // then no need to release the mutator lock.
808 if (barrier_count == 0) {
809 return;
810 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800811 // Release locks then wait for all mutator threads to pass the barrier.
812 Locks::mutator_lock_->SharedUnlock(self);
813 {
814 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
815 gc_barrier_->Increment(self, barrier_count);
816 }
817 Locks::mutator_lock_->SharedLock(self);
818}
819
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -0700820void ConcurrentCopying::ExpandGcMarkStack() {
821 DCHECK(gc_mark_stack_->IsFull());
822 const size_t new_size = gc_mark_stack_->Capacity() * 2;
823 std::vector<StackReference<mirror::Object>> temp(gc_mark_stack_->Begin(),
824 gc_mark_stack_->End());
825 gc_mark_stack_->Resize(new_size);
826 for (auto& ref : temp) {
827 gc_mark_stack_->PushBack(ref.AsMirrorPtr());
828 }
829 DCHECK(!gc_mark_stack_->IsFull());
830}
831
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800832void ConcurrentCopying::PushOntoMarkStack(mirror::Object* to_ref) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700833 CHECK_EQ(is_mark_stack_push_disallowed_.LoadRelaxed(), 0)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800834 << " " << to_ref << " " << PrettyTypeOf(to_ref);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700835 Thread* self = Thread::Current(); // TODO: pass self as an argument from call sites?
836 CHECK(thread_running_gc_ != nullptr);
837 MarkStackMode mark_stack_mode = mark_stack_mode_.LoadRelaxed();
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -0700838 if (LIKELY(mark_stack_mode == kMarkStackModeThreadLocal)) {
839 if (LIKELY(self == thread_running_gc_)) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700840 // If GC-running thread, use the GC mark stack instead of a thread-local mark stack.
841 CHECK(self->GetThreadLocalMarkStack() == nullptr);
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -0700842 if (UNLIKELY(gc_mark_stack_->IsFull())) {
843 ExpandGcMarkStack();
844 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700845 gc_mark_stack_->PushBack(to_ref);
846 } else {
847 // Otherwise, use a thread-local mark stack.
848 accounting::AtomicStack<mirror::Object>* tl_mark_stack = self->GetThreadLocalMarkStack();
849 if (UNLIKELY(tl_mark_stack == nullptr || tl_mark_stack->IsFull())) {
850 MutexLock mu(self, mark_stack_lock_);
851 // Get a new thread local mark stack.
852 accounting::AtomicStack<mirror::Object>* new_tl_mark_stack;
853 if (!pooled_mark_stacks_.empty()) {
854 // Use a pooled mark stack.
855 new_tl_mark_stack = pooled_mark_stacks_.back();
856 pooled_mark_stacks_.pop_back();
857 } else {
858 // None pooled. Create a new one.
859 new_tl_mark_stack =
860 accounting::AtomicStack<mirror::Object>::Create(
861 "thread local mark stack", 4 * KB, 4 * KB);
862 }
863 DCHECK(new_tl_mark_stack != nullptr);
864 DCHECK(new_tl_mark_stack->IsEmpty());
865 new_tl_mark_stack->PushBack(to_ref);
866 self->SetThreadLocalMarkStack(new_tl_mark_stack);
867 if (tl_mark_stack != nullptr) {
868 // Store the old full stack into a vector.
869 revoked_mark_stacks_.push_back(tl_mark_stack);
870 }
871 } else {
872 tl_mark_stack->PushBack(to_ref);
873 }
874 }
875 } else if (mark_stack_mode == kMarkStackModeShared) {
876 // Access the shared GC mark stack with a lock.
877 MutexLock mu(self, mark_stack_lock_);
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -0700878 if (UNLIKELY(gc_mark_stack_->IsFull())) {
879 ExpandGcMarkStack();
880 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700881 gc_mark_stack_->PushBack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800882 } else {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700883 CHECK_EQ(static_cast<uint32_t>(mark_stack_mode),
Hiroshi Yamauchifa755182015-09-30 20:12:11 -0700884 static_cast<uint32_t>(kMarkStackModeGcExclusive))
885 << "ref=" << to_ref
886 << " self->gc_marking=" << self->GetIsGcMarking()
887 << " cc->is_marking=" << is_marking_;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700888 CHECK(self == thread_running_gc_)
889 << "Only GC-running thread should access the mark stack "
890 << "in the GC exclusive mark stack mode";
891 // Access the GC mark stack without a lock.
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -0700892 if (UNLIKELY(gc_mark_stack_->IsFull())) {
893 ExpandGcMarkStack();
894 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700895 gc_mark_stack_->PushBack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800896 }
897}
898
899accounting::ObjectStack* ConcurrentCopying::GetAllocationStack() {
900 return heap_->allocation_stack_.get();
901}
902
903accounting::ObjectStack* ConcurrentCopying::GetLiveStack() {
904 return heap_->live_stack_.get();
905}
906
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800907// The following visitors are used to verify that there's no references to the from-space left after
908// marking.
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700909class ConcurrentCopying::VerifyNoFromSpaceRefsVisitor : public SingleRootVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800910 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700911 explicit VerifyNoFromSpaceRefsVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800912 : collector_(collector) {}
913
914 void operator()(mirror::Object* ref) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700915 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800916 if (ref == nullptr) {
917 // OK.
918 return;
919 }
920 collector_->AssertToSpaceInvariant(nullptr, MemberOffset(0), ref);
921 if (kUseBakerReadBarrier) {
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700922 CHECK_EQ(ref->GetReadBarrierPointer(), ReadBarrier::WhitePtr())
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800923 << "Ref " << ref << " " << PrettyTypeOf(ref)
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700924 << " has non-white rb_ptr ";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800925 }
926 }
927
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700928 void VisitRoot(mirror::Object* root, const RootInfo& info ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -0700929 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800930 DCHECK(root != nullptr);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700931 operator()(root);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800932 }
933
934 private:
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700935 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800936};
937
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700938class ConcurrentCopying::VerifyNoFromSpaceRefsFieldVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800939 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700940 explicit VerifyNoFromSpaceRefsFieldVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800941 : collector_(collector) {}
942
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700943 void operator()(mirror::Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700944 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800945 mirror::Object* ref =
946 obj->GetFieldObject<mirror::Object, kDefaultVerifyFlags, kWithoutReadBarrier>(offset);
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700947 VerifyNoFromSpaceRefsVisitor visitor(collector_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800948 visitor(ref);
949 }
950 void operator()(mirror::Class* klass, mirror::Reference* ref) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700951 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800952 CHECK(klass->IsTypeOfReferenceClass());
953 this->operator()(ref, mirror::Reference::ReferentOffset(), false);
954 }
955
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700956 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
957 SHARED_REQUIRES(Locks::mutator_lock_) {
958 if (!root->IsNull()) {
959 VisitRoot(root);
960 }
961 }
962
963 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
964 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700965 VerifyNoFromSpaceRefsVisitor visitor(collector_);
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700966 visitor(root->AsMirrorPtr());
967 }
968
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800969 private:
Mathieu Chartier97509952015-07-13 14:35:43 -0700970 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800971};
972
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700973class ConcurrentCopying::VerifyNoFromSpaceRefsObjectVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800974 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700975 explicit VerifyNoFromSpaceRefsObjectVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800976 : collector_(collector) {}
977 void operator()(mirror::Object* obj) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700978 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800979 ObjectCallback(obj, collector_);
980 }
981 static void ObjectCallback(mirror::Object* obj, void *arg)
Mathieu Chartier90443472015-07-16 20:32:27 -0700982 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800983 CHECK(obj != nullptr);
984 ConcurrentCopying* collector = reinterpret_cast<ConcurrentCopying*>(arg);
985 space::RegionSpace* region_space = collector->RegionSpace();
986 CHECK(!region_space->IsInFromSpace(obj)) << "Scanning object " << obj << " in from space";
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700987 VerifyNoFromSpaceRefsFieldVisitor visitor(collector);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -0700988 obj->VisitReferences(visitor, visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800989 if (kUseBakerReadBarrier) {
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700990 CHECK_EQ(obj->GetReadBarrierPointer(), ReadBarrier::WhitePtr())
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800991 << "obj=" << obj << " non-white rb_ptr " << obj->GetReadBarrierPointer();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800992 }
993 }
994
995 private:
996 ConcurrentCopying* const collector_;
997};
998
999// Verify there's no from-space references left after the marking phase.
1000void ConcurrentCopying::VerifyNoFromSpaceReferences() {
1001 Thread* self = Thread::Current();
1002 DCHECK(Locks::mutator_lock_->IsExclusiveHeld(self));
Hiroshi Yamauchi00370822015-08-18 14:47:25 -07001003 // Verify all threads have is_gc_marking to be false
1004 {
1005 MutexLock mu(self, *Locks::thread_list_lock_);
1006 std::list<Thread*> thread_list = Runtime::Current()->GetThreadList()->GetList();
1007 for (Thread* thread : thread_list) {
1008 CHECK(!thread->GetIsGcMarking());
1009 }
1010 }
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001011 VerifyNoFromSpaceRefsObjectVisitor visitor(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001012 // Roots.
1013 {
1014 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001015 VerifyNoFromSpaceRefsVisitor ref_visitor(this);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001016 Runtime::Current()->VisitRoots(&ref_visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001017 }
1018 // The to-space.
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001019 region_space_->WalkToSpace(VerifyNoFromSpaceRefsObjectVisitor::ObjectCallback, this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001020 // Non-moving spaces.
1021 {
1022 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1023 heap_->GetMarkBitmap()->Visit(visitor);
1024 }
1025 // The alloc stack.
1026 {
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001027 VerifyNoFromSpaceRefsVisitor ref_visitor(this);
Mathieu Chartiercb535da2015-01-23 13:50:03 -08001028 for (auto* it = heap_->allocation_stack_->Begin(), *end = heap_->allocation_stack_->End();
1029 it < end; ++it) {
1030 mirror::Object* const obj = it->AsMirrorPtr();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001031 if (obj != nullptr && obj->GetClass() != nullptr) {
1032 // TODO: need to call this only if obj is alive?
1033 ref_visitor(obj);
1034 visitor(obj);
1035 }
1036 }
1037 }
1038 // TODO: LOS. But only refs in LOS are classes.
1039}
1040
1041// The following visitors are used to assert the to-space invariant.
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001042class ConcurrentCopying::AssertToSpaceInvariantRefsVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001043 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001044 explicit AssertToSpaceInvariantRefsVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001045 : collector_(collector) {}
1046
1047 void operator()(mirror::Object* ref) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001048 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001049 if (ref == nullptr) {
1050 // OK.
1051 return;
1052 }
1053 collector_->AssertToSpaceInvariant(nullptr, MemberOffset(0), ref);
1054 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001055
1056 private:
Mathieu Chartier97509952015-07-13 14:35:43 -07001057 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001058};
1059
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001060class ConcurrentCopying::AssertToSpaceInvariantFieldVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001061 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001062 explicit AssertToSpaceInvariantFieldVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001063 : collector_(collector) {}
1064
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001065 void operator()(mirror::Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001066 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001067 mirror::Object* ref =
1068 obj->GetFieldObject<mirror::Object, kDefaultVerifyFlags, kWithoutReadBarrier>(offset);
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001069 AssertToSpaceInvariantRefsVisitor visitor(collector_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001070 visitor(ref);
1071 }
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001072 void operator()(mirror::Class* klass, mirror::Reference* ref ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001073 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001074 CHECK(klass->IsTypeOfReferenceClass());
1075 }
1076
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001077 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
1078 SHARED_REQUIRES(Locks::mutator_lock_) {
1079 if (!root->IsNull()) {
1080 VisitRoot(root);
1081 }
1082 }
1083
1084 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
1085 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001086 AssertToSpaceInvariantRefsVisitor visitor(collector_);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001087 visitor(root->AsMirrorPtr());
1088 }
1089
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001090 private:
Mathieu Chartier97509952015-07-13 14:35:43 -07001091 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001092};
1093
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001094class ConcurrentCopying::AssertToSpaceInvariantObjectVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001095 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001096 explicit AssertToSpaceInvariantObjectVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001097 : collector_(collector) {}
1098 void operator()(mirror::Object* obj) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001099 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001100 ObjectCallback(obj, collector_);
1101 }
1102 static void ObjectCallback(mirror::Object* obj, void *arg)
Mathieu Chartier90443472015-07-16 20:32:27 -07001103 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001104 CHECK(obj != nullptr);
1105 ConcurrentCopying* collector = reinterpret_cast<ConcurrentCopying*>(arg);
1106 space::RegionSpace* region_space = collector->RegionSpace();
1107 CHECK(!region_space->IsInFromSpace(obj)) << "Scanning object " << obj << " in from space";
1108 collector->AssertToSpaceInvariant(nullptr, MemberOffset(0), obj);
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001109 AssertToSpaceInvariantFieldVisitor visitor(collector);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07001110 obj->VisitReferences(visitor, visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001111 }
1112
1113 private:
Mathieu Chartier97509952015-07-13 14:35:43 -07001114 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001115};
1116
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001117class ConcurrentCopying::RevokeThreadLocalMarkStackCheckpoint : public Closure {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001118 public:
Roland Levillain3887c462015-08-12 18:15:42 +01001119 RevokeThreadLocalMarkStackCheckpoint(ConcurrentCopying* concurrent_copying,
1120 bool disable_weak_ref_access)
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001121 : concurrent_copying_(concurrent_copying),
1122 disable_weak_ref_access_(disable_weak_ref_access) {
1123 }
1124
1125 virtual void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
1126 // Note: self is not necessarily equal to thread since thread may be suspended.
1127 Thread* self = Thread::Current();
1128 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
1129 << thread->GetState() << " thread " << thread << " self " << self;
1130 // Revoke thread local mark stacks.
1131 accounting::AtomicStack<mirror::Object>* tl_mark_stack = thread->GetThreadLocalMarkStack();
1132 if (tl_mark_stack != nullptr) {
1133 MutexLock mu(self, concurrent_copying_->mark_stack_lock_);
1134 concurrent_copying_->revoked_mark_stacks_.push_back(tl_mark_stack);
1135 thread->SetThreadLocalMarkStack(nullptr);
1136 }
1137 // Disable weak ref access.
1138 if (disable_weak_ref_access_) {
1139 thread->SetWeakRefAccessEnabled(false);
1140 }
1141 // If thread is a running mutator, then act on behalf of the garbage collector.
1142 // See the code in ThreadList::RunCheckpoint.
Mathieu Chartier10d25082015-10-28 18:36:09 -07001143 concurrent_copying_->GetBarrier().Pass(self);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001144 }
1145
1146 private:
1147 ConcurrentCopying* const concurrent_copying_;
1148 const bool disable_weak_ref_access_;
1149};
1150
1151void ConcurrentCopying::RevokeThreadLocalMarkStacks(bool disable_weak_ref_access) {
1152 Thread* self = Thread::Current();
1153 RevokeThreadLocalMarkStackCheckpoint check_point(this, disable_weak_ref_access);
1154 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1155 gc_barrier_->Init(self, 0);
1156 size_t barrier_count = thread_list->RunCheckpoint(&check_point);
1157 // If there are no threads to wait which implys that all the checkpoint functions are finished,
1158 // then no need to release the mutator lock.
1159 if (barrier_count == 0) {
1160 return;
1161 }
1162 Locks::mutator_lock_->SharedUnlock(self);
1163 {
1164 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
1165 gc_barrier_->Increment(self, barrier_count);
1166 }
1167 Locks::mutator_lock_->SharedLock(self);
1168}
1169
1170void ConcurrentCopying::RevokeThreadLocalMarkStack(Thread* thread) {
1171 Thread* self = Thread::Current();
1172 CHECK_EQ(self, thread);
1173 accounting::AtomicStack<mirror::Object>* tl_mark_stack = thread->GetThreadLocalMarkStack();
1174 if (tl_mark_stack != nullptr) {
1175 CHECK(is_marking_);
1176 MutexLock mu(self, mark_stack_lock_);
1177 revoked_mark_stacks_.push_back(tl_mark_stack);
1178 thread->SetThreadLocalMarkStack(nullptr);
1179 }
1180}
1181
1182void ConcurrentCopying::ProcessMarkStack() {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001183 if (kVerboseMode) {
1184 LOG(INFO) << "ProcessMarkStack. ";
1185 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001186 bool empty_prev = false;
1187 while (true) {
1188 bool empty = ProcessMarkStackOnce();
1189 if (empty_prev && empty) {
1190 // Saw empty mark stack for a second time, done.
1191 break;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001192 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001193 empty_prev = empty;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001194 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001195}
1196
1197bool ConcurrentCopying::ProcessMarkStackOnce() {
1198 Thread* self = Thread::Current();
1199 CHECK(thread_running_gc_ != nullptr);
1200 CHECK(self == thread_running_gc_);
1201 CHECK(self->GetThreadLocalMarkStack() == nullptr);
1202 size_t count = 0;
1203 MarkStackMode mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1204 if (mark_stack_mode == kMarkStackModeThreadLocal) {
1205 // Process the thread-local mark stacks and the GC mark stack.
1206 count += ProcessThreadLocalMarkStacks(false);
1207 while (!gc_mark_stack_->IsEmpty()) {
1208 mirror::Object* to_ref = gc_mark_stack_->PopBack();
1209 ProcessMarkStackRef(to_ref);
1210 ++count;
1211 }
1212 gc_mark_stack_->Reset();
1213 } else if (mark_stack_mode == kMarkStackModeShared) {
1214 // Process the shared GC mark stack with a lock.
1215 {
1216 MutexLock mu(self, mark_stack_lock_);
1217 CHECK(revoked_mark_stacks_.empty());
1218 }
1219 while (true) {
1220 std::vector<mirror::Object*> refs;
1221 {
1222 // Copy refs with lock. Note the number of refs should be small.
1223 MutexLock mu(self, mark_stack_lock_);
1224 if (gc_mark_stack_->IsEmpty()) {
1225 break;
1226 }
1227 for (StackReference<mirror::Object>* p = gc_mark_stack_->Begin();
1228 p != gc_mark_stack_->End(); ++p) {
1229 refs.push_back(p->AsMirrorPtr());
1230 }
1231 gc_mark_stack_->Reset();
1232 }
1233 for (mirror::Object* ref : refs) {
1234 ProcessMarkStackRef(ref);
1235 ++count;
1236 }
1237 }
1238 } else {
1239 CHECK_EQ(static_cast<uint32_t>(mark_stack_mode),
1240 static_cast<uint32_t>(kMarkStackModeGcExclusive));
1241 {
1242 MutexLock mu(self, mark_stack_lock_);
1243 CHECK(revoked_mark_stacks_.empty());
1244 }
1245 // Process the GC mark stack in the exclusive mode. No need to take the lock.
1246 while (!gc_mark_stack_->IsEmpty()) {
1247 mirror::Object* to_ref = gc_mark_stack_->PopBack();
1248 ProcessMarkStackRef(to_ref);
1249 ++count;
1250 }
1251 gc_mark_stack_->Reset();
1252 }
1253
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001254 // Return true if the stack was empty.
1255 return count == 0;
1256}
1257
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001258size_t ConcurrentCopying::ProcessThreadLocalMarkStacks(bool disable_weak_ref_access) {
1259 // Run a checkpoint to collect all thread local mark stacks and iterate over them all.
1260 RevokeThreadLocalMarkStacks(disable_weak_ref_access);
1261 size_t count = 0;
1262 std::vector<accounting::AtomicStack<mirror::Object>*> mark_stacks;
1263 {
1264 MutexLock mu(Thread::Current(), mark_stack_lock_);
1265 // Make a copy of the mark stack vector.
1266 mark_stacks = revoked_mark_stacks_;
1267 revoked_mark_stacks_.clear();
1268 }
1269 for (accounting::AtomicStack<mirror::Object>* mark_stack : mark_stacks) {
1270 for (StackReference<mirror::Object>* p = mark_stack->Begin(); p != mark_stack->End(); ++p) {
1271 mirror::Object* to_ref = p->AsMirrorPtr();
1272 ProcessMarkStackRef(to_ref);
1273 ++count;
1274 }
1275 {
1276 MutexLock mu(Thread::Current(), mark_stack_lock_);
1277 if (pooled_mark_stacks_.size() >= kMarkStackPoolSize) {
1278 // The pool has enough. Delete it.
1279 delete mark_stack;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001280 } else {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001281 // Otherwise, put it into the pool for later reuse.
1282 mark_stack->Reset();
1283 pooled_mark_stacks_.push_back(mark_stack);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001284 }
1285 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001286 }
1287 return count;
1288}
1289
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001290inline void ConcurrentCopying::ProcessMarkStackRef(mirror::Object* to_ref) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001291 DCHECK(!region_space_->IsInFromSpace(to_ref));
1292 if (kUseBakerReadBarrier) {
1293 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr())
1294 << " " << to_ref << " " << to_ref->GetReadBarrierPointer()
1295 << " is_marked=" << IsMarked(to_ref);
1296 }
1297 // Scan ref fields.
1298 Scan(to_ref);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001299 if (kUseBakerReadBarrier) {
1300 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr())
1301 << " " << to_ref << " " << to_ref->GetReadBarrierPointer()
1302 << " is_marked=" << IsMarked(to_ref);
1303 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001304#ifdef USE_BAKER_OR_BROOKS_READ_BARRIER
1305 if (UNLIKELY((to_ref->GetClass<kVerifyNone, kWithoutReadBarrier>()->IsTypeOfReferenceClass() &&
1306 to_ref->AsReference()->GetReferent<kWithoutReadBarrier>() != nullptr &&
1307 !IsInToSpace(to_ref->AsReference()->GetReferent<kWithoutReadBarrier>())))) {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001308 // Leave this reference gray in the queue so that GetReferent() will trigger a read barrier. We
1309 // will change it to white later in ReferenceQueue::DequeuePendingReference().
Richard Uhlere3627402016-02-02 13:36:55 -08001310 DCHECK(to_ref->AsReference()->GetPendingNext() != nullptr) << "Left unenqueued ref gray " << to_ref;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001311 } else {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001312 // We may occasionally leave a reference white in the queue if its referent happens to be
1313 // concurrently marked after the Scan() call above has enqueued the Reference, in which case the
1314 // above IsInToSpace() evaluates to true and we change the color from gray to white here in this
1315 // else block.
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001316 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001317 bool success = to_ref->AtomicSetReadBarrierPointer</*kCasRelease*/true>(
1318 ReadBarrier::GrayPtr(),
1319 ReadBarrier::WhitePtr());
1320 DCHECK(success) << "Must succeed as we won the race.";
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001321 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001322 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001323#else
1324 DCHECK(!kUseBakerReadBarrier);
1325#endif
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001326
1327 if (region_space_->IsInUnevacFromSpace(to_ref)) {
1328 // Add to the live bytes per unevacuated from space. Note this code is always run by the
1329 // GC-running thread (no synchronization required).
1330 DCHECK(region_space_bitmap_->Test(to_ref));
1331 // Disable the read barrier in SizeOf for performance, which is safe.
1332 size_t obj_size = to_ref->SizeOf<kDefaultVerifyFlags, kWithoutReadBarrier>();
1333 size_t alloc_size = RoundUp(obj_size, space::RegionSpace::kAlignment);
1334 region_space_->AddLiveBytes(to_ref, alloc_size);
1335 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001336 if (ReadBarrier::kEnableToSpaceInvariantChecks || kIsDebugBuild) {
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001337 AssertToSpaceInvariantObjectVisitor visitor(this);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001338 visitor(to_ref);
1339 }
1340}
1341
1342void ConcurrentCopying::SwitchToSharedMarkStackMode() {
1343 Thread* self = Thread::Current();
1344 CHECK(thread_running_gc_ != nullptr);
1345 CHECK_EQ(self, thread_running_gc_);
1346 CHECK(self->GetThreadLocalMarkStack() == nullptr);
1347 MarkStackMode before_mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1348 CHECK_EQ(static_cast<uint32_t>(before_mark_stack_mode),
1349 static_cast<uint32_t>(kMarkStackModeThreadLocal));
1350 mark_stack_mode_.StoreRelaxed(kMarkStackModeShared);
1351 CHECK(weak_ref_access_enabled_.LoadRelaxed());
1352 weak_ref_access_enabled_.StoreRelaxed(false);
1353 QuasiAtomic::ThreadFenceForConstructor();
1354 // Process the thread local mark stacks one last time after switching to the shared mark stack
1355 // mode and disable weak ref accesses.
1356 ProcessThreadLocalMarkStacks(true);
1357 if (kVerboseMode) {
1358 LOG(INFO) << "Switched to shared mark stack mode and disabled weak ref access";
1359 }
1360}
1361
1362void ConcurrentCopying::SwitchToGcExclusiveMarkStackMode() {
1363 Thread* self = Thread::Current();
1364 CHECK(thread_running_gc_ != nullptr);
1365 CHECK_EQ(self, thread_running_gc_);
1366 CHECK(self->GetThreadLocalMarkStack() == nullptr);
1367 MarkStackMode before_mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1368 CHECK_EQ(static_cast<uint32_t>(before_mark_stack_mode),
1369 static_cast<uint32_t>(kMarkStackModeShared));
1370 mark_stack_mode_.StoreRelaxed(kMarkStackModeGcExclusive);
1371 QuasiAtomic::ThreadFenceForConstructor();
1372 if (kVerboseMode) {
1373 LOG(INFO) << "Switched to GC exclusive mark stack mode";
1374 }
1375}
1376
1377void ConcurrentCopying::CheckEmptyMarkStack() {
1378 Thread* self = Thread::Current();
1379 CHECK(thread_running_gc_ != nullptr);
1380 CHECK_EQ(self, thread_running_gc_);
1381 CHECK(self->GetThreadLocalMarkStack() == nullptr);
1382 MarkStackMode mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1383 if (mark_stack_mode == kMarkStackModeThreadLocal) {
1384 // Thread-local mark stack mode.
1385 RevokeThreadLocalMarkStacks(false);
1386 MutexLock mu(Thread::Current(), mark_stack_lock_);
1387 if (!revoked_mark_stacks_.empty()) {
1388 for (accounting::AtomicStack<mirror::Object>* mark_stack : revoked_mark_stacks_) {
1389 while (!mark_stack->IsEmpty()) {
1390 mirror::Object* obj = mark_stack->PopBack();
1391 if (kUseBakerReadBarrier) {
1392 mirror::Object* rb_ptr = obj->GetReadBarrierPointer();
1393 LOG(INFO) << "On mark queue : " << obj << " " << PrettyTypeOf(obj) << " rb_ptr=" << rb_ptr
1394 << " is_marked=" << IsMarked(obj);
1395 } else {
1396 LOG(INFO) << "On mark queue : " << obj << " " << PrettyTypeOf(obj)
1397 << " is_marked=" << IsMarked(obj);
1398 }
1399 }
1400 }
1401 LOG(FATAL) << "mark stack is not empty";
1402 }
1403 } else {
1404 // Shared, GC-exclusive, or off.
1405 MutexLock mu(Thread::Current(), mark_stack_lock_);
1406 CHECK(gc_mark_stack_->IsEmpty());
1407 CHECK(revoked_mark_stacks_.empty());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001408 }
1409}
1410
1411void ConcurrentCopying::SweepSystemWeaks(Thread* self) {
1412 TimingLogger::ScopedTiming split("SweepSystemWeaks", GetTimings());
1413 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier97509952015-07-13 14:35:43 -07001414 Runtime::Current()->SweepSystemWeaks(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001415}
1416
1417void ConcurrentCopying::Sweep(bool swap_bitmaps) {
1418 {
1419 TimingLogger::ScopedTiming t("MarkStackAsLive", GetTimings());
1420 accounting::ObjectStack* live_stack = heap_->GetLiveStack();
1421 if (kEnableFromSpaceAccountingCheck) {
1422 CHECK_GE(live_stack_freeze_size_, live_stack->Size());
1423 }
1424 heap_->MarkAllocStackAsLive(live_stack);
1425 live_stack->Reset();
1426 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001427 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001428 TimingLogger::ScopedTiming split("Sweep", GetTimings());
1429 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
1430 if (space->IsContinuousMemMapAllocSpace()) {
1431 space::ContinuousMemMapAllocSpace* alloc_space = space->AsContinuousMemMapAllocSpace();
Mathieu Chartier763a31e2015-11-16 16:05:55 -08001432 if (space == region_space_ || immune_spaces_.ContainsSpace(space)) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001433 continue;
1434 }
1435 TimingLogger::ScopedTiming split2(
1436 alloc_space->IsZygoteSpace() ? "SweepZygoteSpace" : "SweepAllocSpace", GetTimings());
1437 RecordFree(alloc_space->Sweep(swap_bitmaps));
1438 }
1439 }
1440 SweepLargeObjects(swap_bitmaps);
1441}
1442
1443void ConcurrentCopying::SweepLargeObjects(bool swap_bitmaps) {
1444 TimingLogger::ScopedTiming split("SweepLargeObjects", GetTimings());
1445 RecordFreeLOS(heap_->GetLargeObjectsSpace()->Sweep(swap_bitmaps));
1446}
1447
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001448void ConcurrentCopying::ReclaimPhase() {
1449 TimingLogger::ScopedTiming split("ReclaimPhase", GetTimings());
1450 if (kVerboseMode) {
1451 LOG(INFO) << "GC ReclaimPhase";
1452 }
1453 Thread* self = Thread::Current();
1454
1455 {
1456 // Double-check that the mark stack is empty.
1457 // Note: need to set this after VerifyNoFromSpaceRef().
1458 is_asserting_to_space_invariant_ = false;
1459 QuasiAtomic::ThreadFenceForConstructor();
1460 if (kVerboseMode) {
1461 LOG(INFO) << "Issue an empty check point. ";
1462 }
1463 IssueEmptyCheckpoint();
1464 // Disable the check.
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001465 is_mark_stack_push_disallowed_.StoreSequentiallyConsistent(0);
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001466 if (kUseBakerReadBarrier) {
1467 updated_all_immune_objects_.StoreSequentiallyConsistent(false);
1468 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001469 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001470 }
1471
1472 {
1473 // Record freed objects.
1474 TimingLogger::ScopedTiming split2("RecordFree", GetTimings());
1475 // Don't include thread-locals that are in the to-space.
1476 uint64_t from_bytes = region_space_->GetBytesAllocatedInFromSpace();
1477 uint64_t from_objects = region_space_->GetObjectsAllocatedInFromSpace();
1478 uint64_t unevac_from_bytes = region_space_->GetBytesAllocatedInUnevacFromSpace();
1479 uint64_t unevac_from_objects = region_space_->GetObjectsAllocatedInUnevacFromSpace();
1480 uint64_t to_bytes = bytes_moved_.LoadSequentiallyConsistent();
1481 uint64_t to_objects = objects_moved_.LoadSequentiallyConsistent();
1482 if (kEnableFromSpaceAccountingCheck) {
1483 CHECK_EQ(from_space_num_objects_at_first_pause_, from_objects + unevac_from_objects);
1484 CHECK_EQ(from_space_num_bytes_at_first_pause_, from_bytes + unevac_from_bytes);
1485 }
1486 CHECK_LE(to_objects, from_objects);
1487 CHECK_LE(to_bytes, from_bytes);
1488 int64_t freed_bytes = from_bytes - to_bytes;
1489 int64_t freed_objects = from_objects - to_objects;
1490 if (kVerboseMode) {
1491 LOG(INFO) << "RecordFree:"
1492 << " from_bytes=" << from_bytes << " from_objects=" << from_objects
1493 << " unevac_from_bytes=" << unevac_from_bytes << " unevac_from_objects=" << unevac_from_objects
1494 << " to_bytes=" << to_bytes << " to_objects=" << to_objects
1495 << " freed_bytes=" << freed_bytes << " freed_objects=" << freed_objects
1496 << " from_space size=" << region_space_->FromSpaceSize()
1497 << " unevac_from_space size=" << region_space_->UnevacFromSpaceSize()
1498 << " to_space size=" << region_space_->ToSpaceSize();
1499 LOG(INFO) << "(before) num_bytes_allocated=" << heap_->num_bytes_allocated_.LoadSequentiallyConsistent();
1500 }
1501 RecordFree(ObjectBytePair(freed_objects, freed_bytes));
1502 if (kVerboseMode) {
1503 LOG(INFO) << "(after) num_bytes_allocated=" << heap_->num_bytes_allocated_.LoadSequentiallyConsistent();
1504 }
1505 }
1506
1507 {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001508 TimingLogger::ScopedTiming split4("ClearFromSpace", GetTimings());
1509 region_space_->ClearFromSpace();
1510 }
1511
1512 {
1513 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001514 Sweep(false);
1515 SwapBitmaps();
1516 heap_->UnBindBitmaps();
1517
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001518 // Delete the region bitmap.
1519 DCHECK(region_space_bitmap_ != nullptr);
1520 delete region_space_bitmap_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001521 region_space_bitmap_ = nullptr;
1522 }
1523
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001524 CheckEmptyMarkStack();
1525
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001526 if (kVerboseMode) {
1527 LOG(INFO) << "GC end of ReclaimPhase";
1528 }
1529}
1530
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001531// Assert the to-space invariant.
1532void ConcurrentCopying::AssertToSpaceInvariant(mirror::Object* obj, MemberOffset offset,
1533 mirror::Object* ref) {
1534 CHECK(heap_->collector_type_ == kCollectorTypeCC) << static_cast<size_t>(heap_->collector_type_);
1535 if (is_asserting_to_space_invariant_) {
1536 if (region_space_->IsInToSpace(ref)) {
1537 // OK.
1538 return;
1539 } else if (region_space_->IsInUnevacFromSpace(ref)) {
1540 CHECK(region_space_bitmap_->Test(ref)) << ref;
1541 } else if (region_space_->IsInFromSpace(ref)) {
1542 // Not OK. Do extra logging.
1543 if (obj != nullptr) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001544 LogFromSpaceRefHolder(obj, offset);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001545 }
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001546 ref->GetLockWord(false).Dump(LOG(INTERNAL_FATAL));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001547 CHECK(false) << "Found from-space ref " << ref << " " << PrettyTypeOf(ref);
1548 } else {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001549 AssertToSpaceInvariantInNonMovingSpace(obj, ref);
1550 }
1551 }
1552}
1553
1554class RootPrinter {
1555 public:
1556 RootPrinter() { }
1557
1558 template <class MirrorType>
1559 ALWAYS_INLINE void VisitRootIfNonNull(mirror::CompressedReference<MirrorType>* root)
Mathieu Chartier90443472015-07-16 20:32:27 -07001560 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001561 if (!root->IsNull()) {
1562 VisitRoot(root);
1563 }
1564 }
1565
1566 template <class MirrorType>
1567 void VisitRoot(mirror::Object** root)
Mathieu Chartier90443472015-07-16 20:32:27 -07001568 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001569 LOG(INTERNAL_FATAL) << "root=" << root << " ref=" << *root;
1570 }
1571
1572 template <class MirrorType>
1573 void VisitRoot(mirror::CompressedReference<MirrorType>* root)
Mathieu Chartier90443472015-07-16 20:32:27 -07001574 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001575 LOG(INTERNAL_FATAL) << "root=" << root << " ref=" << root->AsMirrorPtr();
1576 }
1577};
1578
1579void ConcurrentCopying::AssertToSpaceInvariant(GcRootSource* gc_root_source,
1580 mirror::Object* ref) {
1581 CHECK(heap_->collector_type_ == kCollectorTypeCC) << static_cast<size_t>(heap_->collector_type_);
1582 if (is_asserting_to_space_invariant_) {
1583 if (region_space_->IsInToSpace(ref)) {
1584 // OK.
1585 return;
1586 } else if (region_space_->IsInUnevacFromSpace(ref)) {
1587 CHECK(region_space_bitmap_->Test(ref)) << ref;
1588 } else if (region_space_->IsInFromSpace(ref)) {
1589 // Not OK. Do extra logging.
1590 if (gc_root_source == nullptr) {
1591 // No info.
1592 } else if (gc_root_source->HasArtField()) {
1593 ArtField* field = gc_root_source->GetArtField();
1594 LOG(INTERNAL_FATAL) << "gc root in field " << field << " " << PrettyField(field);
1595 RootPrinter root_printer;
1596 field->VisitRoots(root_printer);
1597 } else if (gc_root_source->HasArtMethod()) {
1598 ArtMethod* method = gc_root_source->GetArtMethod();
1599 LOG(INTERNAL_FATAL) << "gc root in method " << method << " " << PrettyMethod(method);
1600 RootPrinter root_printer;
Andreas Gampe542451c2016-07-26 09:02:02 -07001601 method->VisitRoots(root_printer, kRuntimePointerSize);
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001602 }
1603 ref->GetLockWord(false).Dump(LOG(INTERNAL_FATAL));
1604 region_space_->DumpNonFreeRegions(LOG(INTERNAL_FATAL));
1605 PrintFileToLog("/proc/self/maps", LogSeverity::INTERNAL_FATAL);
1606 MemMap::DumpMaps(LOG(INTERNAL_FATAL), true);
1607 CHECK(false) << "Found from-space ref " << ref << " " << PrettyTypeOf(ref);
1608 } else {
1609 AssertToSpaceInvariantInNonMovingSpace(nullptr, ref);
1610 }
1611 }
1612}
1613
1614void ConcurrentCopying::LogFromSpaceRefHolder(mirror::Object* obj, MemberOffset offset) {
1615 if (kUseBakerReadBarrier) {
1616 LOG(INFO) << "holder=" << obj << " " << PrettyTypeOf(obj)
1617 << " holder rb_ptr=" << obj->GetReadBarrierPointer();
1618 } else {
1619 LOG(INFO) << "holder=" << obj << " " << PrettyTypeOf(obj);
1620 }
1621 if (region_space_->IsInFromSpace(obj)) {
1622 LOG(INFO) << "holder is in the from-space.";
1623 } else if (region_space_->IsInToSpace(obj)) {
1624 LOG(INFO) << "holder is in the to-space.";
1625 } else if (region_space_->IsInUnevacFromSpace(obj)) {
1626 LOG(INFO) << "holder is in the unevac from-space.";
1627 if (region_space_bitmap_->Test(obj)) {
1628 LOG(INFO) << "holder is marked in the region space bitmap.";
1629 } else {
1630 LOG(INFO) << "holder is not marked in the region space bitmap.";
1631 }
1632 } else {
1633 // In a non-moving space.
Mathieu Chartier763a31e2015-11-16 16:05:55 -08001634 if (immune_spaces_.ContainsObject(obj)) {
1635 LOG(INFO) << "holder is in an immune image or the zygote space.";
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001636 } else {
Mathieu Chartier763a31e2015-11-16 16:05:55 -08001637 LOG(INFO) << "holder is in a non-immune, non-moving (or main) space.";
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001638 accounting::ContinuousSpaceBitmap* mark_bitmap =
1639 heap_mark_bitmap_->GetContinuousSpaceBitmap(obj);
1640 accounting::LargeObjectBitmap* los_bitmap =
1641 heap_mark_bitmap_->GetLargeObjectBitmap(obj);
1642 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
1643 bool is_los = mark_bitmap == nullptr;
1644 if (!is_los && mark_bitmap->Test(obj)) {
1645 LOG(INFO) << "holder is marked in the mark bit map.";
1646 } else if (is_los && los_bitmap->Test(obj)) {
1647 LOG(INFO) << "holder is marked in the los bit map.";
1648 } else {
1649 // If ref is on the allocation stack, then it is considered
1650 // mark/alive (but not necessarily on the live stack.)
1651 if (IsOnAllocStack(obj)) {
1652 LOG(INFO) << "holder is on the alloc stack.";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001653 } else {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001654 LOG(INFO) << "holder is not marked or on the alloc stack.";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001655 }
1656 }
1657 }
1658 }
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001659 LOG(INFO) << "offset=" << offset.SizeValue();
1660}
1661
1662void ConcurrentCopying::AssertToSpaceInvariantInNonMovingSpace(mirror::Object* obj,
1663 mirror::Object* ref) {
1664 // In a non-moving spaces. Check that the ref is marked.
Mathieu Chartier763a31e2015-11-16 16:05:55 -08001665 if (immune_spaces_.ContainsObject(ref)) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001666 if (kUseBakerReadBarrier) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001667 // Immune object may not be gray if called from the GC.
1668 if (Thread::Current() == thread_running_gc_ && !gc_grays_immune_objects_) {
1669 return;
1670 }
1671 bool updated_all_immune_objects = updated_all_immune_objects_.LoadSequentiallyConsistent();
1672 CHECK(updated_all_immune_objects || ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr())
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001673 << "Unmarked immune space ref. obj=" << obj << " rb_ptr="
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001674 << (obj != nullptr ? obj->GetReadBarrierPointer() : nullptr)
1675 << " ref=" << ref << " ref rb_ptr=" << ref->GetReadBarrierPointer()
1676 << " updated_all_immune_objects=" << updated_all_immune_objects;
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001677 }
1678 } else {
1679 accounting::ContinuousSpaceBitmap* mark_bitmap =
1680 heap_mark_bitmap_->GetContinuousSpaceBitmap(ref);
1681 accounting::LargeObjectBitmap* los_bitmap =
1682 heap_mark_bitmap_->GetLargeObjectBitmap(ref);
1683 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
1684 bool is_los = mark_bitmap == nullptr;
1685 if ((!is_los && mark_bitmap->Test(ref)) ||
1686 (is_los && los_bitmap->Test(ref))) {
1687 // OK.
1688 } else {
1689 // If ref is on the allocation stack, then it may not be
1690 // marked live, but considered marked/alive (but not
1691 // necessarily on the live stack).
1692 CHECK(IsOnAllocStack(ref)) << "Unmarked ref that's not on the allocation stack. "
1693 << "obj=" << obj << " ref=" << ref;
1694 }
1695 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001696}
1697
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001698// Used to scan ref fields of an object.
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001699class ConcurrentCopying::RefFieldsVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001700 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001701 explicit RefFieldsVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001702 : collector_(collector) {}
1703
1704 void operator()(mirror::Object* obj, MemberOffset offset, bool /* is_static */)
Mathieu Chartier90443472015-07-16 20:32:27 -07001705 const ALWAYS_INLINE SHARED_REQUIRES(Locks::mutator_lock_)
1706 SHARED_REQUIRES(Locks::heap_bitmap_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001707 collector_->Process(obj, offset);
1708 }
1709
1710 void operator()(mirror::Class* klass, mirror::Reference* ref) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001711 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001712 CHECK(klass->IsTypeOfReferenceClass());
1713 collector_->DelayReferenceReferent(klass, ref);
1714 }
1715
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001716 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001717 ALWAYS_INLINE
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001718 SHARED_REQUIRES(Locks::mutator_lock_) {
1719 if (!root->IsNull()) {
1720 VisitRoot(root);
1721 }
1722 }
1723
1724 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001725 ALWAYS_INLINE
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001726 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001727 collector_->MarkRoot</*kGrayImmuneObject*/false>(root);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001728 }
1729
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001730 private:
1731 ConcurrentCopying* const collector_;
1732};
1733
1734// Scan ref fields of an object.
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001735inline void ConcurrentCopying::Scan(mirror::Object* to_ref) {
Mathieu Chartierd6636d32016-07-28 11:02:38 -07001736 if (kDisallowReadBarrierDuringScan) {
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07001737 // Avoid all read barriers during visit references to help performance.
1738 Thread::Current()->ModifyDebugDisallowReadBarrier(1);
1739 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001740 DCHECK(!region_space_->IsInFromSpace(to_ref));
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001741 DCHECK_EQ(Thread::Current(), thread_running_gc_);
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001742 RefFieldsVisitor visitor(this);
Hiroshi Yamauchi5496f692016-02-17 13:29:59 -08001743 // Disable the read barrier for a performance reason.
1744 to_ref->VisitReferences</*kVisitNativeRoots*/true, kDefaultVerifyFlags, kWithoutReadBarrier>(
1745 visitor, visitor);
Mathieu Chartierd6636d32016-07-28 11:02:38 -07001746 if (kDisallowReadBarrierDuringScan) {
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07001747 Thread::Current()->ModifyDebugDisallowReadBarrier(-1);
1748 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001749}
1750
1751// Process a field.
1752inline void ConcurrentCopying::Process(mirror::Object* obj, MemberOffset offset) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001753 DCHECK_EQ(Thread::Current(), thread_running_gc_);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001754 mirror::Object* ref = obj->GetFieldObject<
1755 mirror::Object, kVerifyNone, kWithoutReadBarrier, false>(offset);
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001756 mirror::Object* to_ref = Mark</*kGrayImmuneObject*/false>(ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001757 if (to_ref == ref) {
1758 return;
1759 }
1760 // This may fail if the mutator writes to the field at the same time. But it's ok.
1761 mirror::Object* expected_ref = ref;
1762 mirror::Object* new_ref = to_ref;
1763 do {
1764 if (expected_ref !=
1765 obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier, false>(offset)) {
1766 // It was updated by the mutator.
1767 break;
1768 }
Hiroshi Yamauchifed3e2f2015-10-20 11:11:56 -07001769 } while (!obj->CasFieldWeakRelaxedObjectWithoutWriteBarrier<
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001770 false, false, kVerifyNone>(offset, expected_ref, new_ref));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001771}
1772
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001773// Process some roots.
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001774inline void ConcurrentCopying::VisitRoots(
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001775 mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED) {
1776 for (size_t i = 0; i < count; ++i) {
1777 mirror::Object** root = roots[i];
1778 mirror::Object* ref = *root;
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001779 mirror::Object* to_ref = Mark(ref);
1780 if (to_ref == ref) {
Mathieu Chartier4809d0a2015-04-07 10:39:04 -07001781 continue;
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001782 }
1783 Atomic<mirror::Object*>* addr = reinterpret_cast<Atomic<mirror::Object*>*>(root);
1784 mirror::Object* expected_ref = ref;
1785 mirror::Object* new_ref = to_ref;
1786 do {
1787 if (expected_ref != addr->LoadRelaxed()) {
1788 // It was updated by the mutator.
1789 break;
1790 }
Hiroshi Yamauchifed3e2f2015-10-20 11:11:56 -07001791 } while (!addr->CompareExchangeWeakRelaxed(expected_ref, new_ref));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001792 }
1793}
1794
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001795template<bool kGrayImmuneObject>
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001796inline void ConcurrentCopying::MarkRoot(mirror::CompressedReference<mirror::Object>* root) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001797 DCHECK(!root->IsNull());
1798 mirror::Object* const ref = root->AsMirrorPtr();
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001799 mirror::Object* to_ref = Mark<kGrayImmuneObject>(ref);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001800 if (to_ref != ref) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001801 auto* addr = reinterpret_cast<Atomic<mirror::CompressedReference<mirror::Object>>*>(root);
1802 auto expected_ref = mirror::CompressedReference<mirror::Object>::FromMirrorPtr(ref);
1803 auto new_ref = mirror::CompressedReference<mirror::Object>::FromMirrorPtr(to_ref);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001804 // If the cas fails, then it was updated by the mutator.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001805 do {
1806 if (ref != addr->LoadRelaxed().AsMirrorPtr()) {
1807 // It was updated by the mutator.
1808 break;
1809 }
Hiroshi Yamauchifed3e2f2015-10-20 11:11:56 -07001810 } while (!addr->CompareExchangeWeakRelaxed(expected_ref, new_ref));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001811 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001812}
1813
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001814inline void ConcurrentCopying::VisitRoots(
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001815 mirror::CompressedReference<mirror::Object>** roots, size_t count,
1816 const RootInfo& info ATTRIBUTE_UNUSED) {
1817 for (size_t i = 0; i < count; ++i) {
1818 mirror::CompressedReference<mirror::Object>* const root = roots[i];
1819 if (!root->IsNull()) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001820 // kGrayImmuneObject is true because this is used for the thread flip.
1821 MarkRoot</*kGrayImmuneObject*/true>(root);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001822 }
1823 }
1824}
1825
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001826// Temporary set gc_grays_immune_objects_ to true in a scope if the current thread is GC.
1827class ConcurrentCopying::ScopedGcGraysImmuneObjects {
1828 public:
1829 explicit ScopedGcGraysImmuneObjects(ConcurrentCopying* collector)
1830 : collector_(collector), enabled_(false) {
1831 if (kUseBakerReadBarrier &&
1832 collector_->thread_running_gc_ == Thread::Current() &&
1833 !collector_->gc_grays_immune_objects_) {
1834 collector_->gc_grays_immune_objects_ = true;
1835 enabled_ = true;
1836 }
1837 }
1838
1839 ~ScopedGcGraysImmuneObjects() {
1840 if (kUseBakerReadBarrier &&
1841 collector_->thread_running_gc_ == Thread::Current() &&
1842 enabled_) {
1843 DCHECK(collector_->gc_grays_immune_objects_);
1844 collector_->gc_grays_immune_objects_ = false;
1845 }
1846 }
1847
1848 private:
1849 ConcurrentCopying* const collector_;
1850 bool enabled_;
1851};
1852
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001853// Fill the given memory block with a dummy object. Used to fill in a
1854// copy of objects that was lost in race.
1855void ConcurrentCopying::FillWithDummyObject(mirror::Object* dummy_obj, size_t byte_size) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001856 // GC doesn't gray immune objects while scanning immune objects. But we need to trigger the read
1857 // barriers here because we need the updated reference to the int array class, etc. Temporary set
1858 // gc_grays_immune_objects_ to true so that we won't cause a DCHECK failure in MarkImmuneSpace().
1859 ScopedGcGraysImmuneObjects scoped_gc_gray_immune_objects(this);
Roland Levillain14d90572015-07-16 10:52:26 +01001860 CHECK_ALIGNED(byte_size, kObjectAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001861 memset(dummy_obj, 0, byte_size);
Mathieu Chartierd6636d32016-07-28 11:02:38 -07001862 // Avoid going through read barrier for since kDisallowReadBarrierDuringScan may be enabled.
1863 // Explicitly mark to make sure to get an object in the to-space.
1864 mirror::Class* int_array_class = down_cast<mirror::Class*>(
1865 Mark(mirror::IntArray::GetArrayClass<kWithoutReadBarrier>()));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001866 CHECK(int_array_class != nullptr);
1867 AssertToSpaceInvariant(nullptr, MemberOffset(0), int_array_class);
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07001868 size_t component_size = int_array_class->GetComponentSize<kWithoutReadBarrier>();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001869 CHECK_EQ(component_size, sizeof(int32_t));
1870 size_t data_offset = mirror::Array::DataOffset(component_size).SizeValue();
1871 if (data_offset > byte_size) {
1872 // An int array is too big. Use java.lang.Object.
1873 mirror::Class* java_lang_Object = WellKnownClasses::ToClass(WellKnownClasses::java_lang_Object);
1874 AssertToSpaceInvariant(nullptr, MemberOffset(0), java_lang_Object);
Mathieu Chartierd6636d32016-07-28 11:02:38 -07001875 CHECK_EQ(byte_size, (java_lang_Object->GetObjectSize<kVerifyNone, kWithoutReadBarrier>()));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001876 dummy_obj->SetClass(java_lang_Object);
Mathieu Chartierd6636d32016-07-28 11:02:38 -07001877 CHECK_EQ(byte_size, (dummy_obj->SizeOf<kVerifyNone, kWithoutReadBarrier>()));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001878 } else {
1879 // Use an int array.
1880 dummy_obj->SetClass(int_array_class);
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07001881 CHECK((dummy_obj->IsArrayInstance<kVerifyNone, kWithoutReadBarrier>()));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001882 int32_t length = (byte_size - data_offset) / component_size;
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07001883 mirror::Array* dummy_arr = dummy_obj->AsArray<kVerifyNone, kWithoutReadBarrier>();
1884 dummy_arr->SetLength(length);
1885 CHECK_EQ(dummy_arr->GetLength(), length)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001886 << "byte_size=" << byte_size << " length=" << length
1887 << " component_size=" << component_size << " data_offset=" << data_offset;
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07001888 CHECK_EQ(byte_size, (dummy_obj->SizeOf<kVerifyNone, kWithoutReadBarrier>()))
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001889 << "byte_size=" << byte_size << " length=" << length
1890 << " component_size=" << component_size << " data_offset=" << data_offset;
1891 }
1892}
1893
1894// Reuse the memory blocks that were copy of objects that were lost in race.
1895mirror::Object* ConcurrentCopying::AllocateInSkippedBlock(size_t alloc_size) {
1896 // Try to reuse the blocks that were unused due to CAS failures.
Roland Levillain14d90572015-07-16 10:52:26 +01001897 CHECK_ALIGNED(alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001898 Thread* self = Thread::Current();
1899 size_t min_object_size = RoundUp(sizeof(mirror::Object), space::RegionSpace::kAlignment);
Mathieu Chartierd6636d32016-07-28 11:02:38 -07001900 size_t byte_size;
1901 uint8_t* addr;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001902 {
Mathieu Chartierd6636d32016-07-28 11:02:38 -07001903 MutexLock mu(self, skipped_blocks_lock_);
1904 auto it = skipped_blocks_map_.lower_bound(alloc_size);
1905 if (it == skipped_blocks_map_.end()) {
1906 // Not found.
1907 return nullptr;
1908 }
1909 byte_size = it->first;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001910 CHECK_GE(byte_size, alloc_size);
1911 if (byte_size > alloc_size && byte_size - alloc_size < min_object_size) {
1912 // If remainder would be too small for a dummy object, retry with a larger request size.
1913 it = skipped_blocks_map_.lower_bound(alloc_size + min_object_size);
1914 if (it == skipped_blocks_map_.end()) {
1915 // Not found.
1916 return nullptr;
1917 }
Roland Levillain14d90572015-07-16 10:52:26 +01001918 CHECK_ALIGNED(it->first - alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001919 CHECK_GE(it->first - alloc_size, min_object_size)
1920 << "byte_size=" << byte_size << " it->first=" << it->first << " alloc_size=" << alloc_size;
1921 }
Mathieu Chartierd6636d32016-07-28 11:02:38 -07001922 // Found a block.
1923 CHECK(it != skipped_blocks_map_.end());
1924 byte_size = it->first;
1925 addr = it->second;
1926 CHECK_GE(byte_size, alloc_size);
1927 CHECK(region_space_->IsInToSpace(reinterpret_cast<mirror::Object*>(addr)));
1928 CHECK_ALIGNED(byte_size, space::RegionSpace::kAlignment);
1929 if (kVerboseMode) {
1930 LOG(INFO) << "Reusing skipped bytes : " << reinterpret_cast<void*>(addr) << ", " << byte_size;
1931 }
1932 skipped_blocks_map_.erase(it);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001933 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001934 memset(addr, 0, byte_size);
1935 if (byte_size > alloc_size) {
1936 // Return the remainder to the map.
Roland Levillain14d90572015-07-16 10:52:26 +01001937 CHECK_ALIGNED(byte_size - alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001938 CHECK_GE(byte_size - alloc_size, min_object_size);
Mathieu Chartierd6636d32016-07-28 11:02:38 -07001939 // FillWithDummyObject may mark an object, avoid holding skipped_blocks_lock_ to prevent lock
1940 // violation and possible deadlock. The deadlock case is a recursive case:
1941 // FillWithDummyObject -> IntArray::GetArrayClass -> Mark -> Copy -> AllocateInSkippedBlock.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001942 FillWithDummyObject(reinterpret_cast<mirror::Object*>(addr + alloc_size),
1943 byte_size - alloc_size);
1944 CHECK(region_space_->IsInToSpace(reinterpret_cast<mirror::Object*>(addr + alloc_size)));
Mathieu Chartierd6636d32016-07-28 11:02:38 -07001945 {
1946 MutexLock mu(self, skipped_blocks_lock_);
1947 skipped_blocks_map_.insert(std::make_pair(byte_size - alloc_size, addr + alloc_size));
1948 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001949 }
1950 return reinterpret_cast<mirror::Object*>(addr);
1951}
1952
1953mirror::Object* ConcurrentCopying::Copy(mirror::Object* from_ref) {
1954 DCHECK(region_space_->IsInFromSpace(from_ref));
1955 // No read barrier to avoid nested RB that might violate the to-space
1956 // invariant. Note that from_ref is a from space ref so the SizeOf()
1957 // call will access the from-space meta objects, but it's ok and necessary.
1958 size_t obj_size = from_ref->SizeOf<kDefaultVerifyFlags, kWithoutReadBarrier>();
1959 size_t region_space_alloc_size = RoundUp(obj_size, space::RegionSpace::kAlignment);
1960 size_t region_space_bytes_allocated = 0U;
1961 size_t non_moving_space_bytes_allocated = 0U;
1962 size_t bytes_allocated = 0U;
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001963 size_t dummy;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001964 mirror::Object* to_ref = region_space_->AllocNonvirtual<true>(
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001965 region_space_alloc_size, &region_space_bytes_allocated, nullptr, &dummy);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001966 bytes_allocated = region_space_bytes_allocated;
1967 if (to_ref != nullptr) {
1968 DCHECK_EQ(region_space_alloc_size, region_space_bytes_allocated);
1969 }
1970 bool fall_back_to_non_moving = false;
1971 if (UNLIKELY(to_ref == nullptr)) {
1972 // Failed to allocate in the region space. Try the skipped blocks.
1973 to_ref = AllocateInSkippedBlock(region_space_alloc_size);
1974 if (to_ref != nullptr) {
1975 // Succeeded to allocate in a skipped block.
1976 if (heap_->use_tlab_) {
1977 // This is necessary for the tlab case as it's not accounted in the space.
1978 region_space_->RecordAlloc(to_ref);
1979 }
1980 bytes_allocated = region_space_alloc_size;
1981 } else {
1982 // Fall back to the non-moving space.
1983 fall_back_to_non_moving = true;
1984 if (kVerboseMode) {
1985 LOG(INFO) << "Out of memory in the to-space. Fall back to non-moving. skipped_bytes="
1986 << to_space_bytes_skipped_.LoadSequentiallyConsistent()
1987 << " skipped_objects=" << to_space_objects_skipped_.LoadSequentiallyConsistent();
1988 }
1989 fall_back_to_non_moving = true;
1990 to_ref = heap_->non_moving_space_->Alloc(Thread::Current(), obj_size,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001991 &non_moving_space_bytes_allocated, nullptr, &dummy);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001992 CHECK(to_ref != nullptr) << "Fall-back non-moving space allocation failed";
1993 bytes_allocated = non_moving_space_bytes_allocated;
1994 // Mark it in the mark bitmap.
1995 accounting::ContinuousSpaceBitmap* mark_bitmap =
1996 heap_mark_bitmap_->GetContinuousSpaceBitmap(to_ref);
1997 CHECK(mark_bitmap != nullptr);
1998 CHECK(!mark_bitmap->AtomicTestAndSet(to_ref));
1999 }
2000 }
2001 DCHECK(to_ref != nullptr);
2002
2003 // Attempt to install the forward pointer. This is in a loop as the
2004 // lock word atomic write can fail.
2005 while (true) {
2006 // Copy the object. TODO: copy only the lockword in the second iteration and on?
2007 memcpy(to_ref, from_ref, obj_size);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002008
2009 LockWord old_lock_word = to_ref->GetLockWord(false);
2010
2011 if (old_lock_word.GetState() == LockWord::kForwardingAddress) {
2012 // Lost the race. Another thread (either GC or mutator) stored
2013 // the forwarding pointer first. Make the lost copy (to_ref)
2014 // look like a valid but dead (dummy) object and keep it for
2015 // future reuse.
2016 FillWithDummyObject(to_ref, bytes_allocated);
2017 if (!fall_back_to_non_moving) {
2018 DCHECK(region_space_->IsInToSpace(to_ref));
2019 if (bytes_allocated > space::RegionSpace::kRegionSize) {
2020 // Free the large alloc.
2021 region_space_->FreeLarge(to_ref, bytes_allocated);
2022 } else {
2023 // Record the lost copy for later reuse.
2024 heap_->num_bytes_allocated_.FetchAndAddSequentiallyConsistent(bytes_allocated);
2025 to_space_bytes_skipped_.FetchAndAddSequentiallyConsistent(bytes_allocated);
2026 to_space_objects_skipped_.FetchAndAddSequentiallyConsistent(1);
2027 MutexLock mu(Thread::Current(), skipped_blocks_lock_);
2028 skipped_blocks_map_.insert(std::make_pair(bytes_allocated,
2029 reinterpret_cast<uint8_t*>(to_ref)));
2030 }
2031 } else {
2032 DCHECK(heap_->non_moving_space_->HasAddress(to_ref));
2033 DCHECK_EQ(bytes_allocated, non_moving_space_bytes_allocated);
2034 // Free the non-moving-space chunk.
2035 accounting::ContinuousSpaceBitmap* mark_bitmap =
2036 heap_mark_bitmap_->GetContinuousSpaceBitmap(to_ref);
2037 CHECK(mark_bitmap != nullptr);
2038 CHECK(mark_bitmap->Clear(to_ref));
2039 heap_->non_moving_space_->Free(Thread::Current(), to_ref);
2040 }
2041
2042 // Get the winner's forward ptr.
2043 mirror::Object* lost_fwd_ptr = to_ref;
2044 to_ref = reinterpret_cast<mirror::Object*>(old_lock_word.ForwardingAddress());
2045 CHECK(to_ref != nullptr);
2046 CHECK_NE(to_ref, lost_fwd_ptr);
2047 CHECK(region_space_->IsInToSpace(to_ref) || heap_->non_moving_space_->HasAddress(to_ref));
2048 CHECK_NE(to_ref->GetLockWord(false).GetState(), LockWord::kForwardingAddress);
2049 return to_ref;
2050 }
2051
Hiroshi Yamauchi60f63f52015-04-23 16:12:40 -07002052 // Set the gray ptr.
2053 if (kUseBakerReadBarrier) {
2054 to_ref->SetReadBarrierPointer(ReadBarrier::GrayPtr());
2055 }
2056
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002057 LockWord new_lock_word = LockWord::FromForwardingAddress(reinterpret_cast<size_t>(to_ref));
2058
2059 // Try to atomically write the fwd ptr.
2060 bool success = from_ref->CasLockWordWeakSequentiallyConsistent(old_lock_word, new_lock_word);
2061 if (LIKELY(success)) {
2062 // The CAS succeeded.
2063 objects_moved_.FetchAndAddSequentiallyConsistent(1);
2064 bytes_moved_.FetchAndAddSequentiallyConsistent(region_space_alloc_size);
2065 if (LIKELY(!fall_back_to_non_moving)) {
2066 DCHECK(region_space_->IsInToSpace(to_ref));
2067 } else {
2068 DCHECK(heap_->non_moving_space_->HasAddress(to_ref));
2069 DCHECK_EQ(bytes_allocated, non_moving_space_bytes_allocated);
2070 }
2071 if (kUseBakerReadBarrier) {
2072 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr());
2073 }
2074 DCHECK(GetFwdPtr(from_ref) == to_ref);
2075 CHECK_NE(to_ref->GetLockWord(false).GetState(), LockWord::kForwardingAddress);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002076 PushOntoMarkStack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002077 return to_ref;
2078 } else {
2079 // The CAS failed. It may have lost the race or may have failed
2080 // due to monitor/hashcode ops. Either way, retry.
2081 }
2082 }
2083}
2084
2085mirror::Object* ConcurrentCopying::IsMarked(mirror::Object* from_ref) {
2086 DCHECK(from_ref != nullptr);
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08002087 space::RegionSpace::RegionType rtype = region_space_->GetRegionType(from_ref);
2088 if (rtype == space::RegionSpace::RegionType::kRegionTypeToSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002089 // It's already marked.
2090 return from_ref;
2091 }
2092 mirror::Object* to_ref;
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08002093 if (rtype == space::RegionSpace::RegionType::kRegionTypeFromSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002094 to_ref = GetFwdPtr(from_ref);
2095 DCHECK(to_ref == nullptr || region_space_->IsInToSpace(to_ref) ||
2096 heap_->non_moving_space_->HasAddress(to_ref))
2097 << "from_ref=" << from_ref << " to_ref=" << to_ref;
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08002098 } else if (rtype == space::RegionSpace::RegionType::kRegionTypeUnevacFromSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002099 if (region_space_bitmap_->Test(from_ref)) {
2100 to_ref = from_ref;
2101 } else {
2102 to_ref = nullptr;
2103 }
2104 } else {
2105 // from_ref is in a non-moving space.
Mathieu Chartier763a31e2015-11-16 16:05:55 -08002106 if (immune_spaces_.ContainsObject(from_ref)) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002107 // An immune object is alive.
2108 to_ref = from_ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002109 } else {
2110 // Non-immune non-moving space. Use the mark bitmap.
2111 accounting::ContinuousSpaceBitmap* mark_bitmap =
2112 heap_mark_bitmap_->GetContinuousSpaceBitmap(from_ref);
2113 accounting::LargeObjectBitmap* los_bitmap =
2114 heap_mark_bitmap_->GetLargeObjectBitmap(from_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(from_ref)) {
2118 // Already marked.
2119 to_ref = from_ref;
2120 } else if (is_los && los_bitmap->Test(from_ref)) {
2121 // Already marked in LOS.
2122 to_ref = from_ref;
2123 } else {
2124 // Not marked.
2125 if (IsOnAllocStack(from_ref)) {
2126 // If on the allocation stack, it's considered marked.
2127 to_ref = from_ref;
2128 } else {
2129 // Not marked.
2130 to_ref = nullptr;
2131 }
2132 }
2133 }
2134 }
2135 return to_ref;
2136}
2137
2138bool ConcurrentCopying::IsOnAllocStack(mirror::Object* ref) {
2139 QuasiAtomic::ThreadFenceAcquire();
2140 accounting::ObjectStack* alloc_stack = GetAllocationStack();
Mathieu Chartiercb535da2015-01-23 13:50:03 -08002141 return alloc_stack->Contains(ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002142}
2143
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002144mirror::Object* ConcurrentCopying::MarkNonMoving(mirror::Object* ref) {
2145 // ref is in a non-moving space (from_ref == to_ref).
2146 DCHECK(!region_space_->HasAddress(ref)) << ref;
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002147 DCHECK(!immune_spaces_.ContainsObject(ref));
2148 // Use the mark bitmap.
2149 accounting::ContinuousSpaceBitmap* mark_bitmap =
2150 heap_mark_bitmap_->GetContinuousSpaceBitmap(ref);
2151 accounting::LargeObjectBitmap* los_bitmap =
2152 heap_mark_bitmap_->GetLargeObjectBitmap(ref);
2153 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
2154 bool is_los = mark_bitmap == nullptr;
2155 if (!is_los && mark_bitmap->Test(ref)) {
2156 // Already marked.
2157 if (kUseBakerReadBarrier) {
2158 DCHECK(ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr() ||
2159 ref->GetReadBarrierPointer() == ReadBarrier::WhitePtr());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002160 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002161 } else if (is_los && los_bitmap->Test(ref)) {
2162 // Already marked in LOS.
2163 if (kUseBakerReadBarrier) {
2164 DCHECK(ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr() ||
2165 ref->GetReadBarrierPointer() == ReadBarrier::WhitePtr());
2166 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002167 } else {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002168 // Not marked.
2169 if (IsOnAllocStack(ref)) {
2170 // If it's on the allocation stack, it's considered marked. Keep it white.
2171 // Objects on the allocation stack need not be marked.
2172 if (!is_los) {
2173 DCHECK(!mark_bitmap->Test(ref));
2174 } else {
2175 DCHECK(!los_bitmap->Test(ref));
Nicolas Geoffrayddeb1722016-06-28 08:25:59 +00002176 }
Nicolas Geoffrayddeb1722016-06-28 08:25:59 +00002177 if (kUseBakerReadBarrier) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002178 DCHECK_EQ(ref->GetReadBarrierPointer(), ReadBarrier::WhitePtr());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002179 }
2180 } else {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002181 // For the baker-style RB, we need to handle 'false-gray' cases. See the
2182 // kRegionTypeUnevacFromSpace-case comment in Mark().
2183 if (kUseBakerReadBarrier) {
2184 // Test the bitmap first to reduce the chance of false gray cases.
2185 if ((!is_los && mark_bitmap->Test(ref)) ||
2186 (is_los && los_bitmap->Test(ref))) {
2187 return ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002188 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002189 }
2190 // Not marked or on the allocation stack. Try to mark it.
2191 // This may or may not succeed, which is ok.
2192 bool cas_success = false;
2193 if (kUseBakerReadBarrier) {
2194 cas_success = ref->AtomicSetReadBarrierPointer(ReadBarrier::WhitePtr(),
2195 ReadBarrier::GrayPtr());
2196 }
2197 if (!is_los && mark_bitmap->AtomicTestAndSet(ref)) {
2198 // Already marked.
2199 if (kUseBakerReadBarrier && cas_success &&
2200 ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr()) {
2201 PushOntoFalseGrayStack(ref);
2202 }
2203 } else if (is_los && los_bitmap->AtomicTestAndSet(ref)) {
2204 // Already marked in LOS.
2205 if (kUseBakerReadBarrier && cas_success &&
2206 ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr()) {
2207 PushOntoFalseGrayStack(ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002208 }
2209 } else {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002210 // Newly marked.
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08002211 if (kUseBakerReadBarrier) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002212 DCHECK_EQ(ref->GetReadBarrierPointer(), ReadBarrier::GrayPtr());
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08002213 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002214 PushOntoMarkStack(ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002215 }
2216 }
2217 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002218 return ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002219}
2220
2221void ConcurrentCopying::FinishPhase() {
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -08002222 Thread* const self = Thread::Current();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002223 {
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -08002224 MutexLock mu(self, mark_stack_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002225 CHECK_EQ(pooled_mark_stacks_.size(), kMarkStackPoolSize);
2226 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002227 region_space_ = nullptr;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002228 {
2229 MutexLock mu(Thread::Current(), skipped_blocks_lock_);
2230 skipped_blocks_map_.clear();
2231 }
Mathieu Chartier56fe2582016-07-14 13:30:03 -07002232 {
2233 ReaderMutexLock mu(self, *Locks::mutator_lock_);
Mathieu Chartier21328a12016-07-22 10:47:45 -07002234 {
2235 WriterMutexLock mu2(self, *Locks::heap_bitmap_lock_);
2236 heap_->ClearMarkedObjects();
2237 }
2238 if (kUseBakerReadBarrier && kFilterModUnionCards) {
2239 TimingLogger::ScopedTiming split("FilterModUnionCards", GetTimings());
2240 ReaderMutexLock mu2(self, *Locks::heap_bitmap_lock_);
2241 gc::Heap* const heap = Runtime::Current()->GetHeap();
2242 for (space::ContinuousSpace* space : immune_spaces_.GetSpaces()) {
2243 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
2244 accounting::ModUnionTable* table = heap->FindModUnionTableFromSpace(space);
2245 // Filter out cards that don't need to be set.
2246 if (table != nullptr) {
2247 table->FilterCards();
2248 }
2249 }
2250 }
Mathieu Chartier36a270a2016-07-28 18:08:51 -07002251 if (kUseBakerReadBarrier) {
2252 TimingLogger::ScopedTiming split("EmptyRBMarkBitStack", GetTimings());
2253 DCHECK(rb_mark_bit_stack_.get() != nullptr);
2254 const auto* limit = rb_mark_bit_stack_->End();
2255 for (StackReference<mirror::Object>* it = rb_mark_bit_stack_->Begin(); it != limit; ++it) {
2256 CHECK(it->AsMirrorPtr()->AtomicSetMarkBit(1, 0));
2257 }
2258 rb_mark_bit_stack_->Reset();
2259 }
Mathieu Chartier56fe2582016-07-14 13:30:03 -07002260 }
2261 if (measure_read_barrier_slow_path_) {
2262 MutexLock mu(self, rb_slow_path_histogram_lock_);
2263 rb_slow_path_time_histogram_.AdjustAndAddValue(rb_slow_path_ns_.LoadRelaxed());
2264 rb_slow_path_count_total_ += rb_slow_path_count_.LoadRelaxed();
2265 rb_slow_path_count_gc_total_ += rb_slow_path_count_gc_.LoadRelaxed();
2266 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002267}
2268
Mathieu Chartier97509952015-07-13 14:35:43 -07002269bool ConcurrentCopying::IsMarkedHeapReference(mirror::HeapReference<mirror::Object>* field) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002270 mirror::Object* from_ref = field->AsMirrorPtr();
Mathieu Chartier97509952015-07-13 14:35:43 -07002271 mirror::Object* to_ref = IsMarked(from_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002272 if (to_ref == nullptr) {
2273 return false;
2274 }
2275 if (from_ref != to_ref) {
2276 QuasiAtomic::ThreadFenceRelease();
2277 field->Assign(to_ref);
2278 QuasiAtomic::ThreadFenceSequentiallyConsistent();
2279 }
2280 return true;
2281}
2282
Mathieu Chartier97509952015-07-13 14:35:43 -07002283mirror::Object* ConcurrentCopying::MarkObject(mirror::Object* from_ref) {
2284 return Mark(from_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002285}
2286
2287void ConcurrentCopying::DelayReferenceReferent(mirror::Class* klass, mirror::Reference* reference) {
Mathieu Chartier97509952015-07-13 14:35:43 -07002288 heap_->GetReferenceProcessor()->DelayReferenceReferent(klass, reference, this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002289}
2290
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002291void ConcurrentCopying::ProcessReferences(Thread* self) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002292 TimingLogger::ScopedTiming split("ProcessReferences", GetTimings());
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002293 // 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 -08002294 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
2295 GetHeap()->GetReferenceProcessor()->ProcessReferences(
Mathieu Chartier97509952015-07-13 14:35:43 -07002296 true /*concurrent*/, GetTimings(), GetCurrentIteration()->GetClearSoftReferences(), this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002297}
2298
2299void ConcurrentCopying::RevokeAllThreadLocalBuffers() {
2300 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
2301 region_space_->RevokeAllThreadLocalBuffers();
2302}
2303
Mathieu Chartier56fe2582016-07-14 13:30:03 -07002304mirror::Object* ConcurrentCopying::MarkFromReadBarrierWithMeasurements(mirror::Object* from_ref) {
2305 if (Thread::Current() != thread_running_gc_) {
2306 rb_slow_path_count_.FetchAndAddRelaxed(1u);
2307 } else {
2308 rb_slow_path_count_gc_.FetchAndAddRelaxed(1u);
2309 }
2310 ScopedTrace tr(__FUNCTION__);
2311 const uint64_t start_time = measure_read_barrier_slow_path_ ? NanoTime() : 0u;
2312 mirror::Object* ret = Mark(from_ref);
2313 if (measure_read_barrier_slow_path_) {
2314 rb_slow_path_ns_.FetchAndAddRelaxed(NanoTime() - start_time);
2315 }
2316 return ret;
2317}
2318
2319void ConcurrentCopying::DumpPerformanceInfo(std::ostream& os) {
2320 GarbageCollector::DumpPerformanceInfo(os);
2321 MutexLock mu(Thread::Current(), rb_slow_path_histogram_lock_);
2322 if (rb_slow_path_time_histogram_.SampleSize() > 0) {
2323 Histogram<uint64_t>::CumulativeData cumulative_data;
2324 rb_slow_path_time_histogram_.CreateHistogram(&cumulative_data);
2325 rb_slow_path_time_histogram_.PrintConfidenceIntervals(os, 0.99, cumulative_data);
2326 }
2327 if (rb_slow_path_count_total_ > 0) {
2328 os << "Slow path count " << rb_slow_path_count_total_ << "\n";
2329 }
2330 if (rb_slow_path_count_gc_total_ > 0) {
2331 os << "GC slow path count " << rb_slow_path_count_gc_total_ << "\n";
2332 }
2333}
2334
Hiroshi Yamauchid5307ec2014-03-27 21:07:51 -07002335} // namespace collector
2336} // namespace gc
2337} // namespace art