blob: 0fdc8697547910834795f39206203c865f313637 [file] [log] [blame]
Hiroshi Yamauchid5307ec2014-03-27 21:07:51 -07001/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "concurrent_copying.h"
18
Mathieu Chartierc7853442015-03-27 14:35:38 -070019#include "art_field-inl.h"
Mathieu Chartier56fe2582016-07-14 13:30:03 -070020#include "base/histogram-inl.h"
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070021#include "base/stl_util.h"
Mathieu Chartier56fe2582016-07-14 13:30:03 -070022#include "base/systrace.h"
Mathieu Chartiera6b1ead2015-10-06 10:32:38 -070023#include "debugger.h"
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080024#include "gc/accounting/heap_bitmap-inl.h"
Mathieu Chartier21328a12016-07-22 10:47:45 -070025#include "gc/accounting/mod_union_table-inl.h"
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080026#include "gc/accounting/space_bitmap-inl.h"
Mathieu Chartier3cf22532015-07-09 15:15:09 -070027#include "gc/reference_processor.h"
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080028#include "gc/space/image_space.h"
Mathieu Chartier073b16c2015-11-10 14:13:23 -080029#include "gc/space/space-inl.h"
Mathieu Chartier4a26f172016-01-26 14:26:18 -080030#include "image-inl.h"
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080031#include "intern_table.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070032#include "mirror/class-inl.h"
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080033#include "mirror/object-inl.h"
34#include "scoped_thread_state_change.h"
35#include "thread-inl.h"
36#include "thread_list.h"
37#include "well_known_classes.h"
38
Hiroshi Yamauchid5307ec2014-03-27 21:07:51 -070039namespace art {
40namespace gc {
41namespace collector {
42
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -070043static constexpr size_t kDefaultGcMarkStackSize = 2 * MB;
Mathieu Chartier21328a12016-07-22 10:47:45 -070044// If kGrayDirtyImmuneObjects is true then we gray dirty objects in the GC pause to prevent dirty
45// pages.
46static constexpr bool kGrayDirtyImmuneObjects = true;
47// If kFilterModUnionCards then we attempt to filter cards that don't need to be dirty in the mod
48// union table. Disabled since it does not seem to help the pause much.
49static constexpr bool kFilterModUnionCards = kIsDebugBuild;
Mathieu Chartierd6636d32016-07-28 11:02:38 -070050// If kDisallowReadBarrierDuringScan is true then the GC aborts if there are any that occur during
51// ConcurrentCopying::Scan. May be used to diagnose possibly unnecessary read barriers.
52// Only enabled for kIsDebugBuild to avoid performance hit.
53static constexpr bool kDisallowReadBarrierDuringScan = kIsDebugBuild;
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -070054
Mathieu Chartier56fe2582016-07-14 13:30:03 -070055ConcurrentCopying::ConcurrentCopying(Heap* heap,
56 const std::string& name_prefix,
57 bool measure_read_barrier_slow_path)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080058 : GarbageCollector(heap,
59 name_prefix + (name_prefix.empty() ? "" : " ") +
60 "concurrent copying + mark sweep"),
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070061 region_space_(nullptr), gc_barrier_(new Barrier(0)),
62 gc_mark_stack_(accounting::ObjectStack::Create("concurrent copying gc mark stack",
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -070063 kDefaultGcMarkStackSize,
64 kDefaultGcMarkStackSize)),
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070065 mark_stack_lock_("concurrent copying mark stack lock", kMarkSweepMarkStackLock),
66 thread_running_gc_(nullptr),
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080067 is_marking_(false), is_active_(false), is_asserting_to_space_invariant_(false),
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -070068 region_space_bitmap_(nullptr),
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070069 heap_mark_bitmap_(nullptr), live_stack_freeze_size_(0), mark_stack_mode_(kMarkStackModeOff),
70 weak_ref_access_enabled_(true),
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080071 skipped_blocks_lock_("concurrent copying bytes blocks lock", kMarkSweepMarkStackLock),
Mathieu Chartier56fe2582016-07-14 13:30:03 -070072 measure_read_barrier_slow_path_(measure_read_barrier_slow_path),
73 rb_slow_path_ns_(0),
74 rb_slow_path_count_(0),
75 rb_slow_path_count_gc_(0),
76 rb_slow_path_histogram_lock_("Read barrier histogram lock"),
77 rb_slow_path_time_histogram_("Mutator time in read barrier slow path", 500, 32),
78 rb_slow_path_count_total_(0),
79 rb_slow_path_count_gc_total_(0),
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080080 rb_table_(heap_->GetReadBarrierTable()),
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -070081 force_evacuate_all_(false),
82 immune_gray_stack_lock_("concurrent copying immune gray stack lock",
83 kMarkSweepMarkStackLock) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080084 static_assert(space::RegionSpace::kRegionSize == accounting::ReadBarrierTable::kRegionSize,
85 "The region space size and the read barrier table region size must match");
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070086 Thread* self = Thread::Current();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080087 {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080088 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
89 // Cache this so that we won't have to lock heap_bitmap_lock_ in
90 // Mark() which could cause a nested lock on heap_bitmap_lock_
91 // when GC causes a RB while doing GC or a lock order violation
92 // (class_linker_lock_ and heap_bitmap_lock_).
93 heap_mark_bitmap_ = heap->GetMarkBitmap();
94 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070095 {
96 MutexLock mu(self, mark_stack_lock_);
97 for (size_t i = 0; i < kMarkStackPoolSize; ++i) {
98 accounting::AtomicStack<mirror::Object>* mark_stack =
99 accounting::AtomicStack<mirror::Object>::Create(
100 "thread local mark stack", kMarkStackSize, kMarkStackSize);
101 pooled_mark_stacks_.push_back(mark_stack);
102 }
103 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800104}
105
Mathieu Chartierb19ccb12015-07-15 10:24:16 -0700106void ConcurrentCopying::MarkHeapReference(mirror::HeapReference<mirror::Object>* from_ref) {
107 // Used for preserving soft references, should be OK to not have a CAS here since there should be
108 // no other threads which can trigger read barriers on the same referent during reference
109 // processing.
110 from_ref->Assign(Mark(from_ref->AsMirrorPtr()));
Mathieu Chartier81187812015-07-15 14:24:07 -0700111 DCHECK(!from_ref->IsNull());
Mathieu Chartier97509952015-07-13 14:35:43 -0700112}
113
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800114ConcurrentCopying::~ConcurrentCopying() {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700115 STLDeleteElements(&pooled_mark_stacks_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800116}
117
118void ConcurrentCopying::RunPhases() {
119 CHECK(kUseBakerReadBarrier || kUseTableLookupReadBarrier);
120 CHECK(!is_active_);
121 is_active_ = true;
122 Thread* self = Thread::Current();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700123 thread_running_gc_ = self;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800124 Locks::mutator_lock_->AssertNotHeld(self);
125 {
126 ReaderMutexLock mu(self, *Locks::mutator_lock_);
127 InitializePhase();
128 }
129 FlipThreadRoots();
130 {
131 ReaderMutexLock mu(self, *Locks::mutator_lock_);
132 MarkingPhase();
133 }
134 // Verify no from space refs. This causes a pause.
135 if (kEnableNoFromSpaceRefsVerification || kIsDebugBuild) {
136 TimingLogger::ScopedTiming split("(Paused)VerifyNoFromSpaceReferences", GetTimings());
137 ScopedPause pause(this);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700138 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800139 if (kVerboseMode) {
140 LOG(INFO) << "Verifying no from-space refs";
141 }
142 VerifyNoFromSpaceReferences();
Mathieu Chartier720e71a2015-04-06 17:10:58 -0700143 if (kVerboseMode) {
144 LOG(INFO) << "Done verifying no from-space refs";
145 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700146 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800147 }
148 {
149 ReaderMutexLock mu(self, *Locks::mutator_lock_);
150 ReclaimPhase();
151 }
152 FinishPhase();
153 CHECK(is_active_);
154 is_active_ = false;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700155 thread_running_gc_ = nullptr;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800156}
157
158void ConcurrentCopying::BindBitmaps() {
159 Thread* self = Thread::Current();
160 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
161 // Mark all of the spaces we never collect as immune.
162 for (const auto& space : heap_->GetContinuousSpaces()) {
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800163 if (space->GetGcRetentionPolicy() == space::kGcRetentionPolicyNeverCollect ||
164 space->GetGcRetentionPolicy() == space::kGcRetentionPolicyFullCollect) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800165 CHECK(space->IsZygoteSpace() || space->IsImageSpace());
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800166 immune_spaces_.AddSpace(space);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800167 } else if (space == region_space_) {
168 accounting::ContinuousSpaceBitmap* bitmap =
169 accounting::ContinuousSpaceBitmap::Create("cc region space bitmap",
170 space->Begin(), space->Capacity());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800171 region_space_bitmap_ = bitmap;
172 }
173 }
174}
175
176void ConcurrentCopying::InitializePhase() {
177 TimingLogger::ScopedTiming split("InitializePhase", GetTimings());
178 if (kVerboseMode) {
179 LOG(INFO) << "GC InitializePhase";
180 LOG(INFO) << "Region-space : " << reinterpret_cast<void*>(region_space_->Begin()) << "-"
181 << reinterpret_cast<void*>(region_space_->Limit());
182 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700183 CheckEmptyMarkStack();
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800184 if (kIsDebugBuild) {
185 MutexLock mu(Thread::Current(), mark_stack_lock_);
186 CHECK(false_gray_stack_.empty());
187 }
Mathieu Chartier56fe2582016-07-14 13:30:03 -0700188
189 mark_from_read_barrier_measurements_ = measure_read_barrier_slow_path_;
190 if (measure_read_barrier_slow_path_) {
191 rb_slow_path_ns_.StoreRelaxed(0);
192 rb_slow_path_count_.StoreRelaxed(0);
193 rb_slow_path_count_gc_.StoreRelaxed(0);
194 }
195
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800196 immune_spaces_.Reset();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800197 bytes_moved_.StoreRelaxed(0);
198 objects_moved_.StoreRelaxed(0);
199 if (GetCurrentIteration()->GetGcCause() == kGcCauseExplicit ||
200 GetCurrentIteration()->GetGcCause() == kGcCauseForNativeAlloc ||
201 GetCurrentIteration()->GetClearSoftReferences()) {
202 force_evacuate_all_ = true;
203 } else {
204 force_evacuate_all_ = false;
205 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700206 if (kUseBakerReadBarrier) {
207 updated_all_immune_objects_.StoreRelaxed(false);
208 // GC may gray immune objects in the thread flip.
209 gc_grays_immune_objects_ = true;
210 if (kIsDebugBuild) {
211 MutexLock mu(Thread::Current(), immune_gray_stack_lock_);
212 DCHECK(immune_gray_stack_.empty());
213 }
214 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800215 BindBitmaps();
216 if (kVerboseMode) {
217 LOG(INFO) << "force_evacuate_all=" << force_evacuate_all_;
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800218 LOG(INFO) << "Largest immune region: " << immune_spaces_.GetLargestImmuneRegion().Begin()
219 << "-" << immune_spaces_.GetLargestImmuneRegion().End();
220 for (space::ContinuousSpace* space : immune_spaces_.GetSpaces()) {
221 LOG(INFO) << "Immune space: " << *space;
222 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800223 LOG(INFO) << "GC end of InitializePhase";
224 }
225}
226
227// Used to switch the thread roots of a thread from from-space refs to to-space refs.
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700228class ConcurrentCopying::ThreadFlipVisitor : public Closure, public RootVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800229 public:
Roland Levillain3887c462015-08-12 18:15:42 +0100230 ThreadFlipVisitor(ConcurrentCopying* concurrent_copying, bool use_tlab)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800231 : concurrent_copying_(concurrent_copying), use_tlab_(use_tlab) {
232 }
233
Mathieu Chartier90443472015-07-16 20:32:27 -0700234 virtual void Run(Thread* thread) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800235 // Note: self is not necessarily equal to thread since thread may be suspended.
236 Thread* self = Thread::Current();
237 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
238 << thread->GetState() << " thread " << thread << " self " << self;
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700239 thread->SetIsGcMarking(true);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800240 if (use_tlab_ && thread->HasTlab()) {
241 if (ConcurrentCopying::kEnableFromSpaceAccountingCheck) {
242 // This must come before the revoke.
243 size_t thread_local_objects = thread->GetThreadLocalObjectsAllocated();
244 concurrent_copying_->region_space_->RevokeThreadLocalBuffers(thread);
245 reinterpret_cast<Atomic<size_t>*>(&concurrent_copying_->from_space_num_objects_at_first_pause_)->
246 FetchAndAddSequentiallyConsistent(thread_local_objects);
247 } else {
248 concurrent_copying_->region_space_->RevokeThreadLocalBuffers(thread);
249 }
250 }
251 if (kUseThreadLocalAllocationStack) {
252 thread->RevokeThreadLocalAllocationStack();
253 }
254 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700255 // We can use the non-CAS VisitRoots functions below because we update thread-local GC roots
256 // only.
257 thread->VisitRoots(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800258 concurrent_copying_->GetBarrier().Pass(self);
259 }
260
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700261 void VisitRoots(mirror::Object*** roots,
262 size_t count,
263 const RootInfo& info ATTRIBUTE_UNUSED)
264 SHARED_REQUIRES(Locks::mutator_lock_) {
265 for (size_t i = 0; i < count; ++i) {
266 mirror::Object** root = roots[i];
267 mirror::Object* ref = *root;
268 if (ref != nullptr) {
269 mirror::Object* to_ref = concurrent_copying_->Mark(ref);
270 if (to_ref != ref) {
271 *root = to_ref;
272 }
273 }
274 }
275 }
276
277 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots,
278 size_t count,
279 const RootInfo& info ATTRIBUTE_UNUSED)
280 SHARED_REQUIRES(Locks::mutator_lock_) {
281 for (size_t i = 0; i < count; ++i) {
282 mirror::CompressedReference<mirror::Object>* const root = roots[i];
283 if (!root->IsNull()) {
284 mirror::Object* ref = root->AsMirrorPtr();
285 mirror::Object* to_ref = concurrent_copying_->Mark(ref);
286 if (to_ref != ref) {
287 root->Assign(to_ref);
288 }
289 }
290 }
291 }
292
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800293 private:
294 ConcurrentCopying* const concurrent_copying_;
295 const bool use_tlab_;
296};
297
298// Called back from Runtime::FlipThreadRoots() during a pause.
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700299class ConcurrentCopying::FlipCallback : public Closure {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800300 public:
301 explicit FlipCallback(ConcurrentCopying* concurrent_copying)
302 : concurrent_copying_(concurrent_copying) {
303 }
304
Mathieu Chartier90443472015-07-16 20:32:27 -0700305 virtual void Run(Thread* thread) OVERRIDE REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800306 ConcurrentCopying* cc = concurrent_copying_;
307 TimingLogger::ScopedTiming split("(Paused)FlipCallback", cc->GetTimings());
308 // Note: self is not necessarily equal to thread since thread may be suspended.
309 Thread* self = Thread::Current();
310 CHECK(thread == self);
311 Locks::mutator_lock_->AssertExclusiveHeld(self);
312 cc->region_space_->SetFromSpace(cc->rb_table_, cc->force_evacuate_all_);
Mathieu Chartiera4f6af92015-08-11 17:35:25 -0700313 cc->SwapStacks();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800314 if (ConcurrentCopying::kEnableFromSpaceAccountingCheck) {
315 cc->RecordLiveStackFreezeSize(self);
316 cc->from_space_num_objects_at_first_pause_ = cc->region_space_->GetObjectsAllocated();
317 cc->from_space_num_bytes_at_first_pause_ = cc->region_space_->GetBytesAllocated();
318 }
319 cc->is_marking_ = true;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700320 cc->mark_stack_mode_.StoreRelaxed(ConcurrentCopying::kMarkStackModeThreadLocal);
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800321 if (kIsDebugBuild) {
322 cc->region_space_->AssertAllRegionLiveBytesZeroOrCleared();
323 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800324 if (UNLIKELY(Runtime::Current()->IsActiveTransaction())) {
Mathieu Chartier184c9dc2015-03-05 13:20:54 -0800325 CHECK(Runtime::Current()->IsAotCompiler());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800326 TimingLogger::ScopedTiming split2("(Paused)VisitTransactionRoots", cc->GetTimings());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700327 Runtime::Current()->VisitTransactionRoots(cc);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800328 }
Mathieu Chartier21328a12016-07-22 10:47:45 -0700329 if (kUseBakerReadBarrier && kGrayDirtyImmuneObjects) {
330 cc->GrayAllDirtyImmuneObjects();
331 if (kIsDebugBuild) {
332 // Check that all non-gray immune objects only refernce immune objects.
333 cc->VerifyGrayImmuneObjects();
334 }
335 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800336 }
337
338 private:
339 ConcurrentCopying* const concurrent_copying_;
340};
341
Mathieu Chartier21328a12016-07-22 10:47:45 -0700342class ConcurrentCopying::VerifyGrayImmuneObjectsVisitor {
343 public:
344 explicit VerifyGrayImmuneObjectsVisitor(ConcurrentCopying* collector)
345 : collector_(collector) {}
346
347 void operator()(mirror::Object* obj, MemberOffset offset, bool /* is_static */)
348 const ALWAYS_INLINE SHARED_REQUIRES(Locks::mutator_lock_)
349 SHARED_REQUIRES(Locks::heap_bitmap_lock_) {
350 CheckReference(obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(offset),
351 obj, offset);
352 }
353
354 void operator()(mirror::Class* klass, mirror::Reference* ref) const
355 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
356 CHECK(klass->IsTypeOfReferenceClass());
357 CheckReference(ref->GetReferent<kWithoutReadBarrier>(),
358 ref,
359 mirror::Reference::ReferentOffset());
360 }
361
362 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
363 ALWAYS_INLINE
364 SHARED_REQUIRES(Locks::mutator_lock_) {
365 if (!root->IsNull()) {
366 VisitRoot(root);
367 }
368 }
369
370 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
371 ALWAYS_INLINE
372 SHARED_REQUIRES(Locks::mutator_lock_) {
373 CheckReference(root->AsMirrorPtr(), nullptr, MemberOffset(0));
374 }
375
376 private:
377 ConcurrentCopying* const collector_;
378
379 void CheckReference(mirror::Object* ref, mirror::Object* holder, MemberOffset offset) const
380 SHARED_REQUIRES(Locks::mutator_lock_) {
381 if (ref != nullptr) {
382 CHECK(collector_->immune_spaces_.ContainsObject(ref))
383 << "Non gray object references non immune object "<< ref << " " << PrettyTypeOf(ref)
384 << " in holder " << holder << " " << PrettyTypeOf(holder) << " offset="
385 << offset.Uint32Value();
386 }
387 }
388};
389
390void ConcurrentCopying::VerifyGrayImmuneObjects() {
391 TimingLogger::ScopedTiming split(__FUNCTION__, GetTimings());
392 for (auto& space : immune_spaces_.GetSpaces()) {
393 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
394 accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
395 VerifyGrayImmuneObjectsVisitor visitor(this);
396 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()),
397 reinterpret_cast<uintptr_t>(space->Limit()),
398 [&visitor](mirror::Object* obj)
399 SHARED_REQUIRES(Locks::mutator_lock_) {
400 // If an object is not gray, it should only have references to things in the immune spaces.
401 if (obj->GetReadBarrierPointer() != ReadBarrier::GrayPtr()) {
402 obj->VisitReferences</*kVisitNativeRoots*/true,
403 kDefaultVerifyFlags,
404 kWithoutReadBarrier>(visitor, visitor);
405 }
406 });
407 }
408}
409
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800410// Switch threads that from from-space to to-space refs. Forward/mark the thread roots.
411void ConcurrentCopying::FlipThreadRoots() {
412 TimingLogger::ScopedTiming split("FlipThreadRoots", GetTimings());
413 if (kVerboseMode) {
414 LOG(INFO) << "time=" << region_space_->Time();
415 region_space_->DumpNonFreeRegions(LOG(INFO));
416 }
417 Thread* self = Thread::Current();
418 Locks::mutator_lock_->AssertNotHeld(self);
419 gc_barrier_->Init(self, 0);
420 ThreadFlipVisitor thread_flip_visitor(this, heap_->use_tlab_);
421 FlipCallback flip_callback(this);
Hiroshi Yamauchi76f55b02015-08-21 16:10:39 -0700422 heap_->ThreadFlipBegin(self); // Sync with JNI critical calls.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800423 size_t barrier_count = Runtime::Current()->FlipThreadRoots(
424 &thread_flip_visitor, &flip_callback, this);
Hiroshi Yamauchi76f55b02015-08-21 16:10:39 -0700425 heap_->ThreadFlipEnd(self);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800426 {
427 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
428 gc_barrier_->Increment(self, barrier_count);
429 }
430 is_asserting_to_space_invariant_ = true;
431 QuasiAtomic::ThreadFenceForConstructor();
432 if (kVerboseMode) {
433 LOG(INFO) << "time=" << region_space_->Time();
434 region_space_->DumpNonFreeRegions(LOG(INFO));
435 LOG(INFO) << "GC end of FlipThreadRoots";
436 }
437}
438
Mathieu Chartier21328a12016-07-22 10:47:45 -0700439class ConcurrentCopying::GrayImmuneObjectVisitor {
440 public:
441 explicit GrayImmuneObjectVisitor() {}
442
443 ALWAYS_INLINE void operator()(mirror::Object* obj) const SHARED_REQUIRES(Locks::mutator_lock_) {
444 if (kUseBakerReadBarrier) {
445 if (kIsDebugBuild) {
446 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
447 }
448 obj->SetReadBarrierPointer(ReadBarrier::GrayPtr());
449 }
450 }
451
452 static void Callback(mirror::Object* obj, void* arg) SHARED_REQUIRES(Locks::mutator_lock_) {
453 reinterpret_cast<GrayImmuneObjectVisitor*>(arg)->operator()(obj);
454 }
455};
456
457void ConcurrentCopying::GrayAllDirtyImmuneObjects() {
458 TimingLogger::ScopedTiming split(__FUNCTION__, GetTimings());
459 gc::Heap* const heap = Runtime::Current()->GetHeap();
460 accounting::CardTable* const card_table = heap->GetCardTable();
461 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
462 for (space::ContinuousSpace* space : immune_spaces_.GetSpaces()) {
463 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
464 GrayImmuneObjectVisitor visitor;
465 accounting::ModUnionTable* table = heap->FindModUnionTableFromSpace(space);
466 // Mark all the objects on dirty cards since these may point to objects in other space.
467 // Once these are marked, the GC will eventually clear them later.
468 // Table is non null for boot image and zygote spaces. It is only null for application image
469 // spaces.
470 if (table != nullptr) {
471 // TODO: Add preclean outside the pause.
472 table->ClearCards();
473 table->VisitObjects(GrayImmuneObjectVisitor::Callback, &visitor);
474 } else {
475 // TODO: Consider having a mark bitmap for app image spaces and avoid scanning during the
476 // pause because app image spaces are all dirty pages anyways.
477 card_table->Scan<false>(space->GetMarkBitmap(), space->Begin(), space->End(), visitor);
478 }
479 }
480 // Since all of the objects that may point to other spaces are marked, we can avoid all the read
481 // barriers in the immune spaces.
482 updated_all_immune_objects_.StoreRelaxed(true);
483}
484
Mathieu Chartiera4f6af92015-08-11 17:35:25 -0700485void ConcurrentCopying::SwapStacks() {
486 heap_->SwapStacks();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800487}
488
489void ConcurrentCopying::RecordLiveStackFreezeSize(Thread* self) {
490 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
491 live_stack_freeze_size_ = heap_->GetLiveStack()->Size();
492}
493
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800494class EmptyCheckpoint : public Closure {
495 public:
496 explicit EmptyCheckpoint(ConcurrentCopying* concurrent_copying)
497 : concurrent_copying_(concurrent_copying) {
498 }
499
500 virtual void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
501 // Note: self is not necessarily equal to thread since thread may be suspended.
502 Thread* self = Thread::Current();
503 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
504 << thread->GetState() << " thread " << thread << " self " << self;
Lei Lidd9943d2015-02-02 14:24:44 +0800505 // If thread is a running mutator, then act on behalf of the garbage collector.
506 // See the code in ThreadList::RunCheckpoint.
Mathieu Chartier10d25082015-10-28 18:36:09 -0700507 concurrent_copying_->GetBarrier().Pass(self);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800508 }
509
510 private:
511 ConcurrentCopying* const concurrent_copying_;
512};
513
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700514// Used to visit objects in the immune spaces.
515inline void ConcurrentCopying::ScanImmuneObject(mirror::Object* obj) {
516 DCHECK(obj != nullptr);
517 DCHECK(immune_spaces_.ContainsObject(obj));
518 // Update the fields without graying it or pushing it onto the mark stack.
519 Scan(obj);
520}
521
522class ConcurrentCopying::ImmuneSpaceScanObjVisitor {
523 public:
524 explicit ImmuneSpaceScanObjVisitor(ConcurrentCopying* cc)
525 : collector_(cc) {}
526
Hiroshi Yamauchiccf7c8a2016-07-29 17:41:01 +0000527 void operator()(mirror::Object* obj) const SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700528 if (kUseBakerReadBarrier && kGrayDirtyImmuneObjects) {
529 if (obj->GetReadBarrierPointer() == ReadBarrier::GrayPtr()) {
530 collector_->ScanImmuneObject(obj);
531 // Done scanning the object, go back to white.
532 bool success = obj->AtomicSetReadBarrierPointer(ReadBarrier::GrayPtr(),
533 ReadBarrier::WhitePtr());
534 CHECK(success);
535 }
536 } else {
537 collector_->ScanImmuneObject(obj);
538 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700539 }
540
541 private:
542 ConcurrentCopying* const collector_;
543};
544
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800545// Concurrently mark roots that are guarded by read barriers and process the mark stack.
546void ConcurrentCopying::MarkingPhase() {
547 TimingLogger::ScopedTiming split("MarkingPhase", GetTimings());
548 if (kVerboseMode) {
549 LOG(INFO) << "GC MarkingPhase";
550 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700551 CHECK(weak_ref_access_enabled_);
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700552
553 // Scan immune spaces.
554 // Update all the fields in the immune spaces first without graying the objects so that we
555 // minimize dirty pages in the immune spaces. Note mutators can concurrently access and gray some
556 // of the objects.
557 if (kUseBakerReadBarrier) {
558 gc_grays_immune_objects_ = false;
Hiroshi Yamauchi16292fc2016-06-20 20:23:34 -0700559 }
Mathieu Chartier21328a12016-07-22 10:47:45 -0700560 {
561 TimingLogger::ScopedTiming split2("ScanImmuneSpaces", GetTimings());
562 for (auto& space : immune_spaces_.GetSpaces()) {
563 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
564 accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
565 ImmuneSpaceScanObjVisitor visitor(this);
Hiroshi Yamauchiccf7c8a2016-07-29 17:41:01 +0000566 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()),
567 reinterpret_cast<uintptr_t>(space->Limit()),
568 visitor);
Mathieu Chartier21328a12016-07-22 10:47:45 -0700569 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700570 }
571 if (kUseBakerReadBarrier) {
572 // This release fence makes the field updates in the above loop visible before allowing mutator
573 // getting access to immune objects without graying it first.
574 updated_all_immune_objects_.StoreRelease(true);
575 // Now whiten immune objects concurrently accessed and grayed by mutators. We can't do this in
576 // the above loop because we would incorrectly disable the read barrier by whitening an object
577 // which may point to an unscanned, white object, breaking the to-space invariant.
578 //
579 // Make sure no mutators are in the middle of marking an immune object before whitening immune
580 // objects.
581 IssueEmptyCheckpoint();
582 MutexLock mu(Thread::Current(), immune_gray_stack_lock_);
583 if (kVerboseMode) {
584 LOG(INFO) << "immune gray stack size=" << immune_gray_stack_.size();
585 }
586 for (mirror::Object* obj : immune_gray_stack_) {
587 DCHECK(obj->GetReadBarrierPointer() == ReadBarrier::GrayPtr());
588 bool success = obj->AtomicSetReadBarrierPointer(ReadBarrier::GrayPtr(),
589 ReadBarrier::WhitePtr());
590 DCHECK(success);
591 }
592 immune_gray_stack_.clear();
593 }
594
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800595 {
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -0700596 TimingLogger::ScopedTiming split2("VisitConcurrentRoots", GetTimings());
597 Runtime::Current()->VisitConcurrentRoots(this, kVisitRootFlagAllRoots);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800598 }
599 {
600 // TODO: don't visit the transaction roots if it's not active.
601 TimingLogger::ScopedTiming split5("VisitNonThreadRoots", GetTimings());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700602 Runtime::Current()->VisitNonThreadRoots(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800603 }
604
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800605 Thread* self = Thread::Current();
606 {
Mathieu Chartiera6b1ead2015-10-06 10:32:38 -0700607 TimingLogger::ScopedTiming split7("ProcessMarkStack", GetTimings());
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700608 // We transition through three mark stack modes (thread-local, shared, GC-exclusive). The
609 // primary reasons are the fact that we need to use a checkpoint to process thread-local mark
610 // stacks, but after we disable weak refs accesses, we can't use a checkpoint due to a deadlock
611 // issue because running threads potentially blocking at WaitHoldingLocks, and that once we
612 // reach the point where we process weak references, we can avoid using a lock when accessing
613 // the GC mark stack, which makes mark stack processing more efficient.
614
615 // Process the mark stack once in the thread local stack mode. This marks most of the live
616 // objects, aside from weak ref accesses with read barriers (Reference::GetReferent() and system
617 // weaks) that may happen concurrently while we processing the mark stack and newly mark/gray
618 // objects and push refs on the mark stack.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800619 ProcessMarkStack();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700620 // Switch to the shared mark stack mode. That is, revoke and process thread-local mark stacks
621 // for the last time before transitioning to the shared mark stack mode, which would process new
622 // refs that may have been concurrently pushed onto the mark stack during the ProcessMarkStack()
623 // call above. At the same time, disable weak ref accesses using a per-thread flag. It's
624 // important to do these together in a single checkpoint so that we can ensure that mutators
625 // won't newly gray objects and push new refs onto the mark stack due to weak ref accesses and
626 // mutators safely transition to the shared mark stack mode (without leaving unprocessed refs on
627 // the thread-local mark stacks), without a race. This is why we use a thread-local weak ref
628 // access flag Thread::tls32_.weak_ref_access_enabled_ instead of the global ones.
629 SwitchToSharedMarkStackMode();
630 CHECK(!self->GetWeakRefAccessEnabled());
631 // Now that weak refs accesses are disabled, once we exhaust the shared mark stack again here
632 // (which may be non-empty if there were refs found on thread-local mark stacks during the above
633 // SwitchToSharedMarkStackMode() call), we won't have new refs to process, that is, mutators
634 // (via read barriers) have no way to produce any more refs to process. Marking converges once
635 // before we process weak refs below.
636 ProcessMarkStack();
637 CheckEmptyMarkStack();
638 // Switch to the GC exclusive mark stack mode so that we can process the mark stack without a
639 // lock from this point on.
640 SwitchToGcExclusiveMarkStackMode();
641 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800642 if (kVerboseMode) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800643 LOG(INFO) << "ProcessReferences";
644 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700645 // Process weak references. This may produce new refs to process and have them processed via
Mathieu Chartier97509952015-07-13 14:35:43 -0700646 // ProcessMarkStack (in the GC exclusive mark stack mode).
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700647 ProcessReferences(self);
648 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800649 if (kVerboseMode) {
650 LOG(INFO) << "SweepSystemWeaks";
651 }
652 SweepSystemWeaks(self);
653 if (kVerboseMode) {
654 LOG(INFO) << "SweepSystemWeaks done";
655 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700656 // Process the mark stack here one last time because the above SweepSystemWeaks() call may have
657 // marked some objects (strings alive) as hash_set::Erase() can call the hash function for
658 // arbitrary elements in the weak intern table in InternTable::Table::SweepWeaks().
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800659 ProcessMarkStack();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700660 CheckEmptyMarkStack();
661 // Re-enable weak ref accesses.
662 ReenableWeakRefAccess(self);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -0700663 // Free data for class loaders that we unloaded.
664 Runtime::Current()->GetClassLinker()->CleanupClassLoaders();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700665 // Marking is done. Disable marking.
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700666 DisableMarking();
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800667 if (kUseBakerReadBarrier) {
668 ProcessFalseGrayStack();
669 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700670 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800671 }
672
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700673 CHECK(weak_ref_access_enabled_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800674 if (kVerboseMode) {
675 LOG(INFO) << "GC end of MarkingPhase";
676 }
677}
678
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700679void ConcurrentCopying::ReenableWeakRefAccess(Thread* self) {
680 if (kVerboseMode) {
681 LOG(INFO) << "ReenableWeakRefAccess";
682 }
683 weak_ref_access_enabled_.StoreRelaxed(true); // This is for new threads.
684 QuasiAtomic::ThreadFenceForConstructor();
685 // Iterate all threads (don't need to or can't use a checkpoint) and re-enable weak ref access.
686 {
687 MutexLock mu(self, *Locks::thread_list_lock_);
688 std::list<Thread*> thread_list = Runtime::Current()->GetThreadList()->GetList();
689 for (Thread* thread : thread_list) {
690 thread->SetWeakRefAccessEnabled(true);
691 }
692 }
693 // Unblock blocking threads.
694 GetHeap()->GetReferenceProcessor()->BroadcastForSlowPath(self);
695 Runtime::Current()->BroadcastForNewSystemWeaks();
696}
697
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700698class ConcurrentCopying::DisableMarkingCheckpoint : public Closure {
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700699 public:
700 explicit DisableMarkingCheckpoint(ConcurrentCopying* concurrent_copying)
701 : concurrent_copying_(concurrent_copying) {
702 }
703
704 void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
705 // Note: self is not necessarily equal to thread since thread may be suspended.
706 Thread* self = Thread::Current();
707 DCHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
708 << thread->GetState() << " thread " << thread << " self " << self;
709 // Disable the thread-local is_gc_marking flag.
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -0700710 // Note a thread that has just started right before this checkpoint may have already this flag
711 // set to false, which is ok.
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700712 thread->SetIsGcMarking(false);
713 // If thread is a running mutator, then act on behalf of the garbage collector.
714 // See the code in ThreadList::RunCheckpoint.
Mathieu Chartier10d25082015-10-28 18:36:09 -0700715 concurrent_copying_->GetBarrier().Pass(self);
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700716 }
717
718 private:
719 ConcurrentCopying* const concurrent_copying_;
720};
721
722void ConcurrentCopying::IssueDisableMarkingCheckpoint() {
723 Thread* self = Thread::Current();
724 DisableMarkingCheckpoint check_point(this);
725 ThreadList* thread_list = Runtime::Current()->GetThreadList();
726 gc_barrier_->Init(self, 0);
727 size_t barrier_count = thread_list->RunCheckpoint(&check_point);
728 // If there are no threads to wait which implies that all the checkpoint functions are finished,
729 // then no need to release the mutator lock.
730 if (barrier_count == 0) {
731 return;
732 }
733 // Release locks then wait for all mutator threads to pass the barrier.
734 Locks::mutator_lock_->SharedUnlock(self);
735 {
736 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
737 gc_barrier_->Increment(self, barrier_count);
738 }
739 Locks::mutator_lock_->SharedLock(self);
740}
741
742void ConcurrentCopying::DisableMarking() {
743 // Change the global is_marking flag to false. Do a fence before doing a checkpoint to update the
744 // thread-local flags so that a new thread starting up will get the correct is_marking flag.
745 is_marking_ = false;
746 QuasiAtomic::ThreadFenceForConstructor();
747 // Use a checkpoint to turn off the thread-local is_gc_marking flags and to ensure no threads are
748 // still in the middle of a read barrier which may have a from-space ref cached in a local
749 // variable.
750 IssueDisableMarkingCheckpoint();
751 if (kUseTableLookupReadBarrier) {
752 heap_->rb_table_->ClearAll();
753 DCHECK(heap_->rb_table_->IsAllCleared());
754 }
755 is_mark_stack_push_disallowed_.StoreSequentiallyConsistent(1);
756 mark_stack_mode_.StoreSequentiallyConsistent(kMarkStackModeOff);
757}
758
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800759void ConcurrentCopying::PushOntoFalseGrayStack(mirror::Object* ref) {
760 CHECK(kUseBakerReadBarrier);
761 DCHECK(ref != nullptr);
762 MutexLock mu(Thread::Current(), mark_stack_lock_);
763 false_gray_stack_.push_back(ref);
764}
765
766void ConcurrentCopying::ProcessFalseGrayStack() {
767 CHECK(kUseBakerReadBarrier);
768 // Change the objects on the false gray stack from gray to white.
769 MutexLock mu(Thread::Current(), mark_stack_lock_);
770 for (mirror::Object* obj : false_gray_stack_) {
771 DCHECK(IsMarked(obj));
772 // The object could be white here if a thread got preempted after a success at the
773 // AtomicSetReadBarrierPointer in Mark(), GC started marking through it (but not finished so
774 // still gray), and the thread ran to register it onto the false gray stack.
775 if (obj->GetReadBarrierPointer() == ReadBarrier::GrayPtr()) {
776 bool success = obj->AtomicSetReadBarrierPointer(ReadBarrier::GrayPtr(),
777 ReadBarrier::WhitePtr());
778 DCHECK(success);
779 }
780 }
781 false_gray_stack_.clear();
782}
783
784
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800785void ConcurrentCopying::IssueEmptyCheckpoint() {
786 Thread* self = Thread::Current();
787 EmptyCheckpoint check_point(this);
788 ThreadList* thread_list = Runtime::Current()->GetThreadList();
789 gc_barrier_->Init(self, 0);
790 size_t barrier_count = thread_list->RunCheckpoint(&check_point);
Lei Lidd9943d2015-02-02 14:24:44 +0800791 // If there are no threads to wait which implys that all the checkpoint functions are finished,
792 // then no need to release the mutator lock.
793 if (barrier_count == 0) {
794 return;
795 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800796 // Release locks then wait for all mutator threads to pass the barrier.
797 Locks::mutator_lock_->SharedUnlock(self);
798 {
799 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
800 gc_barrier_->Increment(self, barrier_count);
801 }
802 Locks::mutator_lock_->SharedLock(self);
803}
804
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -0700805void ConcurrentCopying::ExpandGcMarkStack() {
806 DCHECK(gc_mark_stack_->IsFull());
807 const size_t new_size = gc_mark_stack_->Capacity() * 2;
808 std::vector<StackReference<mirror::Object>> temp(gc_mark_stack_->Begin(),
809 gc_mark_stack_->End());
810 gc_mark_stack_->Resize(new_size);
811 for (auto& ref : temp) {
812 gc_mark_stack_->PushBack(ref.AsMirrorPtr());
813 }
814 DCHECK(!gc_mark_stack_->IsFull());
815}
816
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800817void ConcurrentCopying::PushOntoMarkStack(mirror::Object* to_ref) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700818 CHECK_EQ(is_mark_stack_push_disallowed_.LoadRelaxed(), 0)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800819 << " " << to_ref << " " << PrettyTypeOf(to_ref);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700820 Thread* self = Thread::Current(); // TODO: pass self as an argument from call sites?
821 CHECK(thread_running_gc_ != nullptr);
822 MarkStackMode mark_stack_mode = mark_stack_mode_.LoadRelaxed();
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -0700823 if (LIKELY(mark_stack_mode == kMarkStackModeThreadLocal)) {
824 if (LIKELY(self == thread_running_gc_)) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700825 // If GC-running thread, use the GC mark stack instead of a thread-local mark stack.
826 CHECK(self->GetThreadLocalMarkStack() == nullptr);
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -0700827 if (UNLIKELY(gc_mark_stack_->IsFull())) {
828 ExpandGcMarkStack();
829 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700830 gc_mark_stack_->PushBack(to_ref);
831 } else {
832 // Otherwise, use a thread-local mark stack.
833 accounting::AtomicStack<mirror::Object>* tl_mark_stack = self->GetThreadLocalMarkStack();
834 if (UNLIKELY(tl_mark_stack == nullptr || tl_mark_stack->IsFull())) {
835 MutexLock mu(self, mark_stack_lock_);
836 // Get a new thread local mark stack.
837 accounting::AtomicStack<mirror::Object>* new_tl_mark_stack;
838 if (!pooled_mark_stacks_.empty()) {
839 // Use a pooled mark stack.
840 new_tl_mark_stack = pooled_mark_stacks_.back();
841 pooled_mark_stacks_.pop_back();
842 } else {
843 // None pooled. Create a new one.
844 new_tl_mark_stack =
845 accounting::AtomicStack<mirror::Object>::Create(
846 "thread local mark stack", 4 * KB, 4 * KB);
847 }
848 DCHECK(new_tl_mark_stack != nullptr);
849 DCHECK(new_tl_mark_stack->IsEmpty());
850 new_tl_mark_stack->PushBack(to_ref);
851 self->SetThreadLocalMarkStack(new_tl_mark_stack);
852 if (tl_mark_stack != nullptr) {
853 // Store the old full stack into a vector.
854 revoked_mark_stacks_.push_back(tl_mark_stack);
855 }
856 } else {
857 tl_mark_stack->PushBack(to_ref);
858 }
859 }
860 } else if (mark_stack_mode == kMarkStackModeShared) {
861 // Access the shared GC mark stack with a lock.
862 MutexLock mu(self, mark_stack_lock_);
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -0700863 if (UNLIKELY(gc_mark_stack_->IsFull())) {
864 ExpandGcMarkStack();
865 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700866 gc_mark_stack_->PushBack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800867 } else {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700868 CHECK_EQ(static_cast<uint32_t>(mark_stack_mode),
Hiroshi Yamauchifa755182015-09-30 20:12:11 -0700869 static_cast<uint32_t>(kMarkStackModeGcExclusive))
870 << "ref=" << to_ref
871 << " self->gc_marking=" << self->GetIsGcMarking()
872 << " cc->is_marking=" << is_marking_;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700873 CHECK(self == thread_running_gc_)
874 << "Only GC-running thread should access the mark stack "
875 << "in the GC exclusive mark stack mode";
876 // Access the GC mark stack without a lock.
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -0700877 if (UNLIKELY(gc_mark_stack_->IsFull())) {
878 ExpandGcMarkStack();
879 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700880 gc_mark_stack_->PushBack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800881 }
882}
883
884accounting::ObjectStack* ConcurrentCopying::GetAllocationStack() {
885 return heap_->allocation_stack_.get();
886}
887
888accounting::ObjectStack* ConcurrentCopying::GetLiveStack() {
889 return heap_->live_stack_.get();
890}
891
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800892// The following visitors are used to verify that there's no references to the from-space left after
893// marking.
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700894class ConcurrentCopying::VerifyNoFromSpaceRefsVisitor : public SingleRootVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800895 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700896 explicit VerifyNoFromSpaceRefsVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800897 : collector_(collector) {}
898
899 void operator()(mirror::Object* ref) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700900 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800901 if (ref == nullptr) {
902 // OK.
903 return;
904 }
905 collector_->AssertToSpaceInvariant(nullptr, MemberOffset(0), ref);
906 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800907 CHECK(ref->GetReadBarrierPointer() == ReadBarrier::WhitePtr())
908 << "Ref " << ref << " " << PrettyTypeOf(ref)
909 << " has non-white rb_ptr " << ref->GetReadBarrierPointer();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800910 }
911 }
912
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700913 void VisitRoot(mirror::Object* root, const RootInfo& info ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -0700914 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800915 DCHECK(root != nullptr);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700916 operator()(root);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800917 }
918
919 private:
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700920 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800921};
922
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700923class ConcurrentCopying::VerifyNoFromSpaceRefsFieldVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800924 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700925 explicit VerifyNoFromSpaceRefsFieldVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800926 : collector_(collector) {}
927
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700928 void operator()(mirror::Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700929 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800930 mirror::Object* ref =
931 obj->GetFieldObject<mirror::Object, kDefaultVerifyFlags, kWithoutReadBarrier>(offset);
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700932 VerifyNoFromSpaceRefsVisitor visitor(collector_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800933 visitor(ref);
934 }
935 void operator()(mirror::Class* klass, mirror::Reference* ref) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700936 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800937 CHECK(klass->IsTypeOfReferenceClass());
938 this->operator()(ref, mirror::Reference::ReferentOffset(), false);
939 }
940
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700941 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
942 SHARED_REQUIRES(Locks::mutator_lock_) {
943 if (!root->IsNull()) {
944 VisitRoot(root);
945 }
946 }
947
948 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
949 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700950 VerifyNoFromSpaceRefsVisitor visitor(collector_);
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700951 visitor(root->AsMirrorPtr());
952 }
953
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800954 private:
Mathieu Chartier97509952015-07-13 14:35:43 -0700955 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800956};
957
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700958class ConcurrentCopying::VerifyNoFromSpaceRefsObjectVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800959 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700960 explicit VerifyNoFromSpaceRefsObjectVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800961 : collector_(collector) {}
962 void operator()(mirror::Object* obj) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700963 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800964 ObjectCallback(obj, collector_);
965 }
966 static void ObjectCallback(mirror::Object* obj, void *arg)
Mathieu Chartier90443472015-07-16 20:32:27 -0700967 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800968 CHECK(obj != nullptr);
969 ConcurrentCopying* collector = reinterpret_cast<ConcurrentCopying*>(arg);
970 space::RegionSpace* region_space = collector->RegionSpace();
971 CHECK(!region_space->IsInFromSpace(obj)) << "Scanning object " << obj << " in from space";
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700972 VerifyNoFromSpaceRefsFieldVisitor visitor(collector);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -0700973 obj->VisitReferences(visitor, visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800974 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800975 CHECK(obj->GetReadBarrierPointer() == ReadBarrier::WhitePtr())
976 << "obj=" << obj << " non-white rb_ptr " << obj->GetReadBarrierPointer();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800977 }
978 }
979
980 private:
981 ConcurrentCopying* const collector_;
982};
983
984// Verify there's no from-space references left after the marking phase.
985void ConcurrentCopying::VerifyNoFromSpaceReferences() {
986 Thread* self = Thread::Current();
987 DCHECK(Locks::mutator_lock_->IsExclusiveHeld(self));
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700988 // Verify all threads have is_gc_marking to be false
989 {
990 MutexLock mu(self, *Locks::thread_list_lock_);
991 std::list<Thread*> thread_list = Runtime::Current()->GetThreadList()->GetList();
992 for (Thread* thread : thread_list) {
993 CHECK(!thread->GetIsGcMarking());
994 }
995 }
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700996 VerifyNoFromSpaceRefsObjectVisitor visitor(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800997 // Roots.
998 {
999 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001000 VerifyNoFromSpaceRefsVisitor ref_visitor(this);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001001 Runtime::Current()->VisitRoots(&ref_visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001002 }
1003 // The to-space.
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001004 region_space_->WalkToSpace(VerifyNoFromSpaceRefsObjectVisitor::ObjectCallback, this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001005 // Non-moving spaces.
1006 {
1007 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1008 heap_->GetMarkBitmap()->Visit(visitor);
1009 }
1010 // The alloc stack.
1011 {
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001012 VerifyNoFromSpaceRefsVisitor ref_visitor(this);
Mathieu Chartiercb535da2015-01-23 13:50:03 -08001013 for (auto* it = heap_->allocation_stack_->Begin(), *end = heap_->allocation_stack_->End();
1014 it < end; ++it) {
1015 mirror::Object* const obj = it->AsMirrorPtr();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001016 if (obj != nullptr && obj->GetClass() != nullptr) {
1017 // TODO: need to call this only if obj is alive?
1018 ref_visitor(obj);
1019 visitor(obj);
1020 }
1021 }
1022 }
1023 // TODO: LOS. But only refs in LOS are classes.
1024}
1025
1026// The following visitors are used to assert the to-space invariant.
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001027class ConcurrentCopying::AssertToSpaceInvariantRefsVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001028 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001029 explicit AssertToSpaceInvariantRefsVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001030 : collector_(collector) {}
1031
1032 void operator()(mirror::Object* ref) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001033 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001034 if (ref == nullptr) {
1035 // OK.
1036 return;
1037 }
1038 collector_->AssertToSpaceInvariant(nullptr, MemberOffset(0), ref);
1039 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001040
1041 private:
Mathieu Chartier97509952015-07-13 14:35:43 -07001042 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001043};
1044
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001045class ConcurrentCopying::AssertToSpaceInvariantFieldVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001046 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001047 explicit AssertToSpaceInvariantFieldVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001048 : collector_(collector) {}
1049
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001050 void operator()(mirror::Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001051 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001052 mirror::Object* ref =
1053 obj->GetFieldObject<mirror::Object, kDefaultVerifyFlags, kWithoutReadBarrier>(offset);
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001054 AssertToSpaceInvariantRefsVisitor visitor(collector_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001055 visitor(ref);
1056 }
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001057 void operator()(mirror::Class* klass, mirror::Reference* ref ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001058 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001059 CHECK(klass->IsTypeOfReferenceClass());
1060 }
1061
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001062 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
1063 SHARED_REQUIRES(Locks::mutator_lock_) {
1064 if (!root->IsNull()) {
1065 VisitRoot(root);
1066 }
1067 }
1068
1069 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
1070 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001071 AssertToSpaceInvariantRefsVisitor visitor(collector_);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001072 visitor(root->AsMirrorPtr());
1073 }
1074
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001075 private:
Mathieu Chartier97509952015-07-13 14:35:43 -07001076 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001077};
1078
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001079class ConcurrentCopying::AssertToSpaceInvariantObjectVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001080 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001081 explicit AssertToSpaceInvariantObjectVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001082 : collector_(collector) {}
1083 void operator()(mirror::Object* obj) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001084 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001085 ObjectCallback(obj, collector_);
1086 }
1087 static void ObjectCallback(mirror::Object* obj, void *arg)
Mathieu Chartier90443472015-07-16 20:32:27 -07001088 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001089 CHECK(obj != nullptr);
1090 ConcurrentCopying* collector = reinterpret_cast<ConcurrentCopying*>(arg);
1091 space::RegionSpace* region_space = collector->RegionSpace();
1092 CHECK(!region_space->IsInFromSpace(obj)) << "Scanning object " << obj << " in from space";
1093 collector->AssertToSpaceInvariant(nullptr, MemberOffset(0), obj);
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001094 AssertToSpaceInvariantFieldVisitor visitor(collector);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07001095 obj->VisitReferences(visitor, visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001096 }
1097
1098 private:
Mathieu Chartier97509952015-07-13 14:35:43 -07001099 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001100};
1101
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001102class ConcurrentCopying::RevokeThreadLocalMarkStackCheckpoint : public Closure {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001103 public:
Roland Levillain3887c462015-08-12 18:15:42 +01001104 RevokeThreadLocalMarkStackCheckpoint(ConcurrentCopying* concurrent_copying,
1105 bool disable_weak_ref_access)
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001106 : concurrent_copying_(concurrent_copying),
1107 disable_weak_ref_access_(disable_weak_ref_access) {
1108 }
1109
1110 virtual void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
1111 // Note: self is not necessarily equal to thread since thread may be suspended.
1112 Thread* self = Thread::Current();
1113 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
1114 << thread->GetState() << " thread " << thread << " self " << self;
1115 // Revoke thread local mark stacks.
1116 accounting::AtomicStack<mirror::Object>* tl_mark_stack = thread->GetThreadLocalMarkStack();
1117 if (tl_mark_stack != nullptr) {
1118 MutexLock mu(self, concurrent_copying_->mark_stack_lock_);
1119 concurrent_copying_->revoked_mark_stacks_.push_back(tl_mark_stack);
1120 thread->SetThreadLocalMarkStack(nullptr);
1121 }
1122 // Disable weak ref access.
1123 if (disable_weak_ref_access_) {
1124 thread->SetWeakRefAccessEnabled(false);
1125 }
1126 // If thread is a running mutator, then act on behalf of the garbage collector.
1127 // See the code in ThreadList::RunCheckpoint.
Mathieu Chartier10d25082015-10-28 18:36:09 -07001128 concurrent_copying_->GetBarrier().Pass(self);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001129 }
1130
1131 private:
1132 ConcurrentCopying* const concurrent_copying_;
1133 const bool disable_weak_ref_access_;
1134};
1135
1136void ConcurrentCopying::RevokeThreadLocalMarkStacks(bool disable_weak_ref_access) {
1137 Thread* self = Thread::Current();
1138 RevokeThreadLocalMarkStackCheckpoint check_point(this, disable_weak_ref_access);
1139 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1140 gc_barrier_->Init(self, 0);
1141 size_t barrier_count = thread_list->RunCheckpoint(&check_point);
1142 // If there are no threads to wait which implys that all the checkpoint functions are finished,
1143 // then no need to release the mutator lock.
1144 if (barrier_count == 0) {
1145 return;
1146 }
1147 Locks::mutator_lock_->SharedUnlock(self);
1148 {
1149 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
1150 gc_barrier_->Increment(self, barrier_count);
1151 }
1152 Locks::mutator_lock_->SharedLock(self);
1153}
1154
1155void ConcurrentCopying::RevokeThreadLocalMarkStack(Thread* thread) {
1156 Thread* self = Thread::Current();
1157 CHECK_EQ(self, thread);
1158 accounting::AtomicStack<mirror::Object>* tl_mark_stack = thread->GetThreadLocalMarkStack();
1159 if (tl_mark_stack != nullptr) {
1160 CHECK(is_marking_);
1161 MutexLock mu(self, mark_stack_lock_);
1162 revoked_mark_stacks_.push_back(tl_mark_stack);
1163 thread->SetThreadLocalMarkStack(nullptr);
1164 }
1165}
1166
1167void ConcurrentCopying::ProcessMarkStack() {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001168 if (kVerboseMode) {
1169 LOG(INFO) << "ProcessMarkStack. ";
1170 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001171 bool empty_prev = false;
1172 while (true) {
1173 bool empty = ProcessMarkStackOnce();
1174 if (empty_prev && empty) {
1175 // Saw empty mark stack for a second time, done.
1176 break;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001177 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001178 empty_prev = empty;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001179 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001180}
1181
1182bool ConcurrentCopying::ProcessMarkStackOnce() {
1183 Thread* self = Thread::Current();
1184 CHECK(thread_running_gc_ != nullptr);
1185 CHECK(self == thread_running_gc_);
1186 CHECK(self->GetThreadLocalMarkStack() == nullptr);
1187 size_t count = 0;
1188 MarkStackMode mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1189 if (mark_stack_mode == kMarkStackModeThreadLocal) {
1190 // Process the thread-local mark stacks and the GC mark stack.
1191 count += ProcessThreadLocalMarkStacks(false);
1192 while (!gc_mark_stack_->IsEmpty()) {
1193 mirror::Object* to_ref = gc_mark_stack_->PopBack();
1194 ProcessMarkStackRef(to_ref);
1195 ++count;
1196 }
1197 gc_mark_stack_->Reset();
1198 } else if (mark_stack_mode == kMarkStackModeShared) {
1199 // Process the shared GC mark stack with a lock.
1200 {
1201 MutexLock mu(self, mark_stack_lock_);
1202 CHECK(revoked_mark_stacks_.empty());
1203 }
1204 while (true) {
1205 std::vector<mirror::Object*> refs;
1206 {
1207 // Copy refs with lock. Note the number of refs should be small.
1208 MutexLock mu(self, mark_stack_lock_);
1209 if (gc_mark_stack_->IsEmpty()) {
1210 break;
1211 }
1212 for (StackReference<mirror::Object>* p = gc_mark_stack_->Begin();
1213 p != gc_mark_stack_->End(); ++p) {
1214 refs.push_back(p->AsMirrorPtr());
1215 }
1216 gc_mark_stack_->Reset();
1217 }
1218 for (mirror::Object* ref : refs) {
1219 ProcessMarkStackRef(ref);
1220 ++count;
1221 }
1222 }
1223 } else {
1224 CHECK_EQ(static_cast<uint32_t>(mark_stack_mode),
1225 static_cast<uint32_t>(kMarkStackModeGcExclusive));
1226 {
1227 MutexLock mu(self, mark_stack_lock_);
1228 CHECK(revoked_mark_stacks_.empty());
1229 }
1230 // Process the GC mark stack in the exclusive mode. No need to take the lock.
1231 while (!gc_mark_stack_->IsEmpty()) {
1232 mirror::Object* to_ref = gc_mark_stack_->PopBack();
1233 ProcessMarkStackRef(to_ref);
1234 ++count;
1235 }
1236 gc_mark_stack_->Reset();
1237 }
1238
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001239 // Return true if the stack was empty.
1240 return count == 0;
1241}
1242
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001243size_t ConcurrentCopying::ProcessThreadLocalMarkStacks(bool disable_weak_ref_access) {
1244 // Run a checkpoint to collect all thread local mark stacks and iterate over them all.
1245 RevokeThreadLocalMarkStacks(disable_weak_ref_access);
1246 size_t count = 0;
1247 std::vector<accounting::AtomicStack<mirror::Object>*> mark_stacks;
1248 {
1249 MutexLock mu(Thread::Current(), mark_stack_lock_);
1250 // Make a copy of the mark stack vector.
1251 mark_stacks = revoked_mark_stacks_;
1252 revoked_mark_stacks_.clear();
1253 }
1254 for (accounting::AtomicStack<mirror::Object>* mark_stack : mark_stacks) {
1255 for (StackReference<mirror::Object>* p = mark_stack->Begin(); p != mark_stack->End(); ++p) {
1256 mirror::Object* to_ref = p->AsMirrorPtr();
1257 ProcessMarkStackRef(to_ref);
1258 ++count;
1259 }
1260 {
1261 MutexLock mu(Thread::Current(), mark_stack_lock_);
1262 if (pooled_mark_stacks_.size() >= kMarkStackPoolSize) {
1263 // The pool has enough. Delete it.
1264 delete mark_stack;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001265 } else {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001266 // Otherwise, put it into the pool for later reuse.
1267 mark_stack->Reset();
1268 pooled_mark_stacks_.push_back(mark_stack);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001269 }
1270 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001271 }
1272 return count;
1273}
1274
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001275inline void ConcurrentCopying::ProcessMarkStackRef(mirror::Object* to_ref) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001276 DCHECK(!region_space_->IsInFromSpace(to_ref));
1277 if (kUseBakerReadBarrier) {
1278 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr())
1279 << " " << to_ref << " " << to_ref->GetReadBarrierPointer()
1280 << " is_marked=" << IsMarked(to_ref);
1281 }
1282 // Scan ref fields.
1283 Scan(to_ref);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001284 if (kUseBakerReadBarrier) {
1285 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr())
1286 << " " << to_ref << " " << to_ref->GetReadBarrierPointer()
1287 << " is_marked=" << IsMarked(to_ref);
1288 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001289#ifdef USE_BAKER_OR_BROOKS_READ_BARRIER
1290 if (UNLIKELY((to_ref->GetClass<kVerifyNone, kWithoutReadBarrier>()->IsTypeOfReferenceClass() &&
1291 to_ref->AsReference()->GetReferent<kWithoutReadBarrier>() != nullptr &&
1292 !IsInToSpace(to_ref->AsReference()->GetReferent<kWithoutReadBarrier>())))) {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001293 // Leave this reference gray in the queue so that GetReferent() will trigger a read barrier. We
1294 // will change it to white later in ReferenceQueue::DequeuePendingReference().
Richard Uhlere3627402016-02-02 13:36:55 -08001295 DCHECK(to_ref->AsReference()->GetPendingNext() != nullptr) << "Left unenqueued ref gray " << to_ref;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001296 } else {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001297 // We may occasionally leave a reference white in the queue if its referent happens to be
1298 // concurrently marked after the Scan() call above has enqueued the Reference, in which case the
1299 // above IsInToSpace() evaluates to true and we change the color from gray to white here in this
1300 // else block.
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001301 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001302 bool success = to_ref->AtomicSetReadBarrierPointer</*kCasRelease*/true>(
1303 ReadBarrier::GrayPtr(),
1304 ReadBarrier::WhitePtr());
1305 DCHECK(success) << "Must succeed as we won the race.";
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001306 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001307 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001308#else
1309 DCHECK(!kUseBakerReadBarrier);
1310#endif
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001311
1312 if (region_space_->IsInUnevacFromSpace(to_ref)) {
1313 // Add to the live bytes per unevacuated from space. Note this code is always run by the
1314 // GC-running thread (no synchronization required).
1315 DCHECK(region_space_bitmap_->Test(to_ref));
1316 // Disable the read barrier in SizeOf for performance, which is safe.
1317 size_t obj_size = to_ref->SizeOf<kDefaultVerifyFlags, kWithoutReadBarrier>();
1318 size_t alloc_size = RoundUp(obj_size, space::RegionSpace::kAlignment);
1319 region_space_->AddLiveBytes(to_ref, alloc_size);
1320 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001321 if (ReadBarrier::kEnableToSpaceInvariantChecks || kIsDebugBuild) {
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001322 AssertToSpaceInvariantObjectVisitor visitor(this);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001323 visitor(to_ref);
1324 }
1325}
1326
1327void ConcurrentCopying::SwitchToSharedMarkStackMode() {
1328 Thread* self = Thread::Current();
1329 CHECK(thread_running_gc_ != nullptr);
1330 CHECK_EQ(self, thread_running_gc_);
1331 CHECK(self->GetThreadLocalMarkStack() == nullptr);
1332 MarkStackMode before_mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1333 CHECK_EQ(static_cast<uint32_t>(before_mark_stack_mode),
1334 static_cast<uint32_t>(kMarkStackModeThreadLocal));
1335 mark_stack_mode_.StoreRelaxed(kMarkStackModeShared);
1336 CHECK(weak_ref_access_enabled_.LoadRelaxed());
1337 weak_ref_access_enabled_.StoreRelaxed(false);
1338 QuasiAtomic::ThreadFenceForConstructor();
1339 // Process the thread local mark stacks one last time after switching to the shared mark stack
1340 // mode and disable weak ref accesses.
1341 ProcessThreadLocalMarkStacks(true);
1342 if (kVerboseMode) {
1343 LOG(INFO) << "Switched to shared mark stack mode and disabled weak ref access";
1344 }
1345}
1346
1347void ConcurrentCopying::SwitchToGcExclusiveMarkStackMode() {
1348 Thread* self = Thread::Current();
1349 CHECK(thread_running_gc_ != nullptr);
1350 CHECK_EQ(self, thread_running_gc_);
1351 CHECK(self->GetThreadLocalMarkStack() == nullptr);
1352 MarkStackMode before_mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1353 CHECK_EQ(static_cast<uint32_t>(before_mark_stack_mode),
1354 static_cast<uint32_t>(kMarkStackModeShared));
1355 mark_stack_mode_.StoreRelaxed(kMarkStackModeGcExclusive);
1356 QuasiAtomic::ThreadFenceForConstructor();
1357 if (kVerboseMode) {
1358 LOG(INFO) << "Switched to GC exclusive mark stack mode";
1359 }
1360}
1361
1362void ConcurrentCopying::CheckEmptyMarkStack() {
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 mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1368 if (mark_stack_mode == kMarkStackModeThreadLocal) {
1369 // Thread-local mark stack mode.
1370 RevokeThreadLocalMarkStacks(false);
1371 MutexLock mu(Thread::Current(), mark_stack_lock_);
1372 if (!revoked_mark_stacks_.empty()) {
1373 for (accounting::AtomicStack<mirror::Object>* mark_stack : revoked_mark_stacks_) {
1374 while (!mark_stack->IsEmpty()) {
1375 mirror::Object* obj = mark_stack->PopBack();
1376 if (kUseBakerReadBarrier) {
1377 mirror::Object* rb_ptr = obj->GetReadBarrierPointer();
1378 LOG(INFO) << "On mark queue : " << obj << " " << PrettyTypeOf(obj) << " rb_ptr=" << rb_ptr
1379 << " is_marked=" << IsMarked(obj);
1380 } else {
1381 LOG(INFO) << "On mark queue : " << obj << " " << PrettyTypeOf(obj)
1382 << " is_marked=" << IsMarked(obj);
1383 }
1384 }
1385 }
1386 LOG(FATAL) << "mark stack is not empty";
1387 }
1388 } else {
1389 // Shared, GC-exclusive, or off.
1390 MutexLock mu(Thread::Current(), mark_stack_lock_);
1391 CHECK(gc_mark_stack_->IsEmpty());
1392 CHECK(revoked_mark_stacks_.empty());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001393 }
1394}
1395
1396void ConcurrentCopying::SweepSystemWeaks(Thread* self) {
1397 TimingLogger::ScopedTiming split("SweepSystemWeaks", GetTimings());
1398 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier97509952015-07-13 14:35:43 -07001399 Runtime::Current()->SweepSystemWeaks(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001400}
1401
1402void ConcurrentCopying::Sweep(bool swap_bitmaps) {
1403 {
1404 TimingLogger::ScopedTiming t("MarkStackAsLive", GetTimings());
1405 accounting::ObjectStack* live_stack = heap_->GetLiveStack();
1406 if (kEnableFromSpaceAccountingCheck) {
1407 CHECK_GE(live_stack_freeze_size_, live_stack->Size());
1408 }
1409 heap_->MarkAllocStackAsLive(live_stack);
1410 live_stack->Reset();
1411 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001412 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001413 TimingLogger::ScopedTiming split("Sweep", GetTimings());
1414 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
1415 if (space->IsContinuousMemMapAllocSpace()) {
1416 space::ContinuousMemMapAllocSpace* alloc_space = space->AsContinuousMemMapAllocSpace();
Mathieu Chartier763a31e2015-11-16 16:05:55 -08001417 if (space == region_space_ || immune_spaces_.ContainsSpace(space)) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001418 continue;
1419 }
1420 TimingLogger::ScopedTiming split2(
1421 alloc_space->IsZygoteSpace() ? "SweepZygoteSpace" : "SweepAllocSpace", GetTimings());
1422 RecordFree(alloc_space->Sweep(swap_bitmaps));
1423 }
1424 }
1425 SweepLargeObjects(swap_bitmaps);
1426}
1427
1428void ConcurrentCopying::SweepLargeObjects(bool swap_bitmaps) {
1429 TimingLogger::ScopedTiming split("SweepLargeObjects", GetTimings());
1430 RecordFreeLOS(heap_->GetLargeObjectsSpace()->Sweep(swap_bitmaps));
1431}
1432
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001433void ConcurrentCopying::ReclaimPhase() {
1434 TimingLogger::ScopedTiming split("ReclaimPhase", GetTimings());
1435 if (kVerboseMode) {
1436 LOG(INFO) << "GC ReclaimPhase";
1437 }
1438 Thread* self = Thread::Current();
1439
1440 {
1441 // Double-check that the mark stack is empty.
1442 // Note: need to set this after VerifyNoFromSpaceRef().
1443 is_asserting_to_space_invariant_ = false;
1444 QuasiAtomic::ThreadFenceForConstructor();
1445 if (kVerboseMode) {
1446 LOG(INFO) << "Issue an empty check point. ";
1447 }
1448 IssueEmptyCheckpoint();
1449 // Disable the check.
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001450 is_mark_stack_push_disallowed_.StoreSequentiallyConsistent(0);
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001451 if (kUseBakerReadBarrier) {
1452 updated_all_immune_objects_.StoreSequentiallyConsistent(false);
1453 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001454 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001455 }
1456
1457 {
1458 // Record freed objects.
1459 TimingLogger::ScopedTiming split2("RecordFree", GetTimings());
1460 // Don't include thread-locals that are in the to-space.
1461 uint64_t from_bytes = region_space_->GetBytesAllocatedInFromSpace();
1462 uint64_t from_objects = region_space_->GetObjectsAllocatedInFromSpace();
1463 uint64_t unevac_from_bytes = region_space_->GetBytesAllocatedInUnevacFromSpace();
1464 uint64_t unevac_from_objects = region_space_->GetObjectsAllocatedInUnevacFromSpace();
1465 uint64_t to_bytes = bytes_moved_.LoadSequentiallyConsistent();
1466 uint64_t to_objects = objects_moved_.LoadSequentiallyConsistent();
1467 if (kEnableFromSpaceAccountingCheck) {
1468 CHECK_EQ(from_space_num_objects_at_first_pause_, from_objects + unevac_from_objects);
1469 CHECK_EQ(from_space_num_bytes_at_first_pause_, from_bytes + unevac_from_bytes);
1470 }
1471 CHECK_LE(to_objects, from_objects);
1472 CHECK_LE(to_bytes, from_bytes);
1473 int64_t freed_bytes = from_bytes - to_bytes;
1474 int64_t freed_objects = from_objects - to_objects;
1475 if (kVerboseMode) {
1476 LOG(INFO) << "RecordFree:"
1477 << " from_bytes=" << from_bytes << " from_objects=" << from_objects
1478 << " unevac_from_bytes=" << unevac_from_bytes << " unevac_from_objects=" << unevac_from_objects
1479 << " to_bytes=" << to_bytes << " to_objects=" << to_objects
1480 << " freed_bytes=" << freed_bytes << " freed_objects=" << freed_objects
1481 << " from_space size=" << region_space_->FromSpaceSize()
1482 << " unevac_from_space size=" << region_space_->UnevacFromSpaceSize()
1483 << " to_space size=" << region_space_->ToSpaceSize();
1484 LOG(INFO) << "(before) num_bytes_allocated=" << heap_->num_bytes_allocated_.LoadSequentiallyConsistent();
1485 }
1486 RecordFree(ObjectBytePair(freed_objects, freed_bytes));
1487 if (kVerboseMode) {
1488 LOG(INFO) << "(after) num_bytes_allocated=" << heap_->num_bytes_allocated_.LoadSequentiallyConsistent();
1489 }
1490 }
1491
1492 {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001493 TimingLogger::ScopedTiming split4("ClearFromSpace", GetTimings());
1494 region_space_->ClearFromSpace();
1495 }
1496
1497 {
1498 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001499 Sweep(false);
1500 SwapBitmaps();
1501 heap_->UnBindBitmaps();
1502
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001503 // Delete the region bitmap.
1504 DCHECK(region_space_bitmap_ != nullptr);
1505 delete region_space_bitmap_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001506 region_space_bitmap_ = nullptr;
1507 }
1508
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001509 CheckEmptyMarkStack();
1510
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001511 if (kVerboseMode) {
1512 LOG(INFO) << "GC end of ReclaimPhase";
1513 }
1514}
1515
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001516// Assert the to-space invariant.
1517void ConcurrentCopying::AssertToSpaceInvariant(mirror::Object* obj, MemberOffset offset,
1518 mirror::Object* ref) {
1519 CHECK(heap_->collector_type_ == kCollectorTypeCC) << static_cast<size_t>(heap_->collector_type_);
1520 if (is_asserting_to_space_invariant_) {
1521 if (region_space_->IsInToSpace(ref)) {
1522 // OK.
1523 return;
1524 } else if (region_space_->IsInUnevacFromSpace(ref)) {
1525 CHECK(region_space_bitmap_->Test(ref)) << ref;
1526 } else if (region_space_->IsInFromSpace(ref)) {
1527 // Not OK. Do extra logging.
1528 if (obj != nullptr) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001529 LogFromSpaceRefHolder(obj, offset);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001530 }
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001531 ref->GetLockWord(false).Dump(LOG(INTERNAL_FATAL));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001532 CHECK(false) << "Found from-space ref " << ref << " " << PrettyTypeOf(ref);
1533 } else {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001534 AssertToSpaceInvariantInNonMovingSpace(obj, ref);
1535 }
1536 }
1537}
1538
1539class RootPrinter {
1540 public:
1541 RootPrinter() { }
1542
1543 template <class MirrorType>
1544 ALWAYS_INLINE void VisitRootIfNonNull(mirror::CompressedReference<MirrorType>* root)
Mathieu Chartier90443472015-07-16 20:32:27 -07001545 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001546 if (!root->IsNull()) {
1547 VisitRoot(root);
1548 }
1549 }
1550
1551 template <class MirrorType>
1552 void VisitRoot(mirror::Object** root)
Mathieu Chartier90443472015-07-16 20:32:27 -07001553 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001554 LOG(INTERNAL_FATAL) << "root=" << root << " ref=" << *root;
1555 }
1556
1557 template <class MirrorType>
1558 void VisitRoot(mirror::CompressedReference<MirrorType>* root)
Mathieu Chartier90443472015-07-16 20:32:27 -07001559 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001560 LOG(INTERNAL_FATAL) << "root=" << root << " ref=" << root->AsMirrorPtr();
1561 }
1562};
1563
1564void ConcurrentCopying::AssertToSpaceInvariant(GcRootSource* gc_root_source,
1565 mirror::Object* ref) {
1566 CHECK(heap_->collector_type_ == kCollectorTypeCC) << static_cast<size_t>(heap_->collector_type_);
1567 if (is_asserting_to_space_invariant_) {
1568 if (region_space_->IsInToSpace(ref)) {
1569 // OK.
1570 return;
1571 } else if (region_space_->IsInUnevacFromSpace(ref)) {
1572 CHECK(region_space_bitmap_->Test(ref)) << ref;
1573 } else if (region_space_->IsInFromSpace(ref)) {
1574 // Not OK. Do extra logging.
1575 if (gc_root_source == nullptr) {
1576 // No info.
1577 } else if (gc_root_source->HasArtField()) {
1578 ArtField* field = gc_root_source->GetArtField();
1579 LOG(INTERNAL_FATAL) << "gc root in field " << field << " " << PrettyField(field);
1580 RootPrinter root_printer;
1581 field->VisitRoots(root_printer);
1582 } else if (gc_root_source->HasArtMethod()) {
1583 ArtMethod* method = gc_root_source->GetArtMethod();
1584 LOG(INTERNAL_FATAL) << "gc root in method " << method << " " << PrettyMethod(method);
1585 RootPrinter root_printer;
Mathieu Chartier1147b9b2015-09-14 18:50:08 -07001586 method->VisitRoots(root_printer, sizeof(void*));
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001587 }
1588 ref->GetLockWord(false).Dump(LOG(INTERNAL_FATAL));
1589 region_space_->DumpNonFreeRegions(LOG(INTERNAL_FATAL));
1590 PrintFileToLog("/proc/self/maps", LogSeverity::INTERNAL_FATAL);
1591 MemMap::DumpMaps(LOG(INTERNAL_FATAL), true);
1592 CHECK(false) << "Found from-space ref " << ref << " " << PrettyTypeOf(ref);
1593 } else {
1594 AssertToSpaceInvariantInNonMovingSpace(nullptr, ref);
1595 }
1596 }
1597}
1598
1599void ConcurrentCopying::LogFromSpaceRefHolder(mirror::Object* obj, MemberOffset offset) {
1600 if (kUseBakerReadBarrier) {
1601 LOG(INFO) << "holder=" << obj << " " << PrettyTypeOf(obj)
1602 << " holder rb_ptr=" << obj->GetReadBarrierPointer();
1603 } else {
1604 LOG(INFO) << "holder=" << obj << " " << PrettyTypeOf(obj);
1605 }
1606 if (region_space_->IsInFromSpace(obj)) {
1607 LOG(INFO) << "holder is in the from-space.";
1608 } else if (region_space_->IsInToSpace(obj)) {
1609 LOG(INFO) << "holder is in the to-space.";
1610 } else if (region_space_->IsInUnevacFromSpace(obj)) {
1611 LOG(INFO) << "holder is in the unevac from-space.";
1612 if (region_space_bitmap_->Test(obj)) {
1613 LOG(INFO) << "holder is marked in the region space bitmap.";
1614 } else {
1615 LOG(INFO) << "holder is not marked in the region space bitmap.";
1616 }
1617 } else {
1618 // In a non-moving space.
Mathieu Chartier763a31e2015-11-16 16:05:55 -08001619 if (immune_spaces_.ContainsObject(obj)) {
1620 LOG(INFO) << "holder is in an immune image or the zygote space.";
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001621 } else {
Mathieu Chartier763a31e2015-11-16 16:05:55 -08001622 LOG(INFO) << "holder is in a non-immune, non-moving (or main) space.";
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001623 accounting::ContinuousSpaceBitmap* mark_bitmap =
1624 heap_mark_bitmap_->GetContinuousSpaceBitmap(obj);
1625 accounting::LargeObjectBitmap* los_bitmap =
1626 heap_mark_bitmap_->GetLargeObjectBitmap(obj);
1627 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
1628 bool is_los = mark_bitmap == nullptr;
1629 if (!is_los && mark_bitmap->Test(obj)) {
1630 LOG(INFO) << "holder is marked in the mark bit map.";
1631 } else if (is_los && los_bitmap->Test(obj)) {
1632 LOG(INFO) << "holder is marked in the los bit map.";
1633 } else {
1634 // If ref is on the allocation stack, then it is considered
1635 // mark/alive (but not necessarily on the live stack.)
1636 if (IsOnAllocStack(obj)) {
1637 LOG(INFO) << "holder is on the alloc stack.";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001638 } else {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001639 LOG(INFO) << "holder is not marked or on the alloc stack.";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001640 }
1641 }
1642 }
1643 }
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001644 LOG(INFO) << "offset=" << offset.SizeValue();
1645}
1646
1647void ConcurrentCopying::AssertToSpaceInvariantInNonMovingSpace(mirror::Object* obj,
1648 mirror::Object* ref) {
1649 // In a non-moving spaces. Check that the ref is marked.
Mathieu Chartier763a31e2015-11-16 16:05:55 -08001650 if (immune_spaces_.ContainsObject(ref)) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001651 if (kUseBakerReadBarrier) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001652 // Immune object may not be gray if called from the GC.
1653 if (Thread::Current() == thread_running_gc_ && !gc_grays_immune_objects_) {
1654 return;
1655 }
1656 bool updated_all_immune_objects = updated_all_immune_objects_.LoadSequentiallyConsistent();
1657 CHECK(updated_all_immune_objects || ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr())
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001658 << "Unmarked immune space ref. obj=" << obj << " rb_ptr="
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001659 << (obj != nullptr ? obj->GetReadBarrierPointer() : nullptr)
1660 << " ref=" << ref << " ref rb_ptr=" << ref->GetReadBarrierPointer()
1661 << " updated_all_immune_objects=" << updated_all_immune_objects;
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001662 }
1663 } else {
1664 accounting::ContinuousSpaceBitmap* mark_bitmap =
1665 heap_mark_bitmap_->GetContinuousSpaceBitmap(ref);
1666 accounting::LargeObjectBitmap* los_bitmap =
1667 heap_mark_bitmap_->GetLargeObjectBitmap(ref);
1668 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
1669 bool is_los = mark_bitmap == nullptr;
1670 if ((!is_los && mark_bitmap->Test(ref)) ||
1671 (is_los && los_bitmap->Test(ref))) {
1672 // OK.
1673 } else {
1674 // If ref is on the allocation stack, then it may not be
1675 // marked live, but considered marked/alive (but not
1676 // necessarily on the live stack).
1677 CHECK(IsOnAllocStack(ref)) << "Unmarked ref that's not on the allocation stack. "
1678 << "obj=" << obj << " ref=" << ref;
1679 }
1680 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001681}
1682
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001683// Used to scan ref fields of an object.
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001684class ConcurrentCopying::RefFieldsVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001685 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001686 explicit RefFieldsVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001687 : collector_(collector) {}
1688
1689 void operator()(mirror::Object* obj, MemberOffset offset, bool /* is_static */)
Mathieu Chartier90443472015-07-16 20:32:27 -07001690 const ALWAYS_INLINE SHARED_REQUIRES(Locks::mutator_lock_)
1691 SHARED_REQUIRES(Locks::heap_bitmap_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001692 collector_->Process(obj, offset);
1693 }
1694
1695 void operator()(mirror::Class* klass, mirror::Reference* ref) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001696 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001697 CHECK(klass->IsTypeOfReferenceClass());
1698 collector_->DelayReferenceReferent(klass, ref);
1699 }
1700
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001701 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001702 ALWAYS_INLINE
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001703 SHARED_REQUIRES(Locks::mutator_lock_) {
1704 if (!root->IsNull()) {
1705 VisitRoot(root);
1706 }
1707 }
1708
1709 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001710 ALWAYS_INLINE
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001711 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001712 collector_->MarkRoot</*kGrayImmuneObject*/false>(root);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001713 }
1714
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001715 private:
1716 ConcurrentCopying* const collector_;
1717};
1718
1719// Scan ref fields of an object.
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001720inline void ConcurrentCopying::Scan(mirror::Object* to_ref) {
Mathieu Chartierd6636d32016-07-28 11:02:38 -07001721 if (kDisallowReadBarrierDuringScan) {
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07001722 // Avoid all read barriers during visit references to help performance.
1723 Thread::Current()->ModifyDebugDisallowReadBarrier(1);
1724 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001725 DCHECK(!region_space_->IsInFromSpace(to_ref));
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001726 DCHECK_EQ(Thread::Current(), thread_running_gc_);
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001727 RefFieldsVisitor visitor(this);
Hiroshi Yamauchi5496f692016-02-17 13:29:59 -08001728 // Disable the read barrier for a performance reason.
1729 to_ref->VisitReferences</*kVisitNativeRoots*/true, kDefaultVerifyFlags, kWithoutReadBarrier>(
1730 visitor, visitor);
Mathieu Chartierd6636d32016-07-28 11:02:38 -07001731 if (kDisallowReadBarrierDuringScan) {
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07001732 Thread::Current()->ModifyDebugDisallowReadBarrier(-1);
1733 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001734}
1735
1736// Process a field.
1737inline void ConcurrentCopying::Process(mirror::Object* obj, MemberOffset offset) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001738 DCHECK_EQ(Thread::Current(), thread_running_gc_);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001739 mirror::Object* ref = obj->GetFieldObject<
1740 mirror::Object, kVerifyNone, kWithoutReadBarrier, false>(offset);
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001741 mirror::Object* to_ref = Mark</*kGrayImmuneObject*/false>(ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001742 if (to_ref == ref) {
1743 return;
1744 }
1745 // This may fail if the mutator writes to the field at the same time. But it's ok.
1746 mirror::Object* expected_ref = ref;
1747 mirror::Object* new_ref = to_ref;
1748 do {
1749 if (expected_ref !=
1750 obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier, false>(offset)) {
1751 // It was updated by the mutator.
1752 break;
1753 }
Hiroshi Yamauchifed3e2f2015-10-20 11:11:56 -07001754 } while (!obj->CasFieldWeakRelaxedObjectWithoutWriteBarrier<
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001755 false, false, kVerifyNone>(offset, expected_ref, new_ref));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001756}
1757
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001758// Process some roots.
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001759inline void ConcurrentCopying::VisitRoots(
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001760 mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED) {
1761 for (size_t i = 0; i < count; ++i) {
1762 mirror::Object** root = roots[i];
1763 mirror::Object* ref = *root;
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001764 mirror::Object* to_ref = Mark(ref);
1765 if (to_ref == ref) {
Mathieu Chartier4809d0a2015-04-07 10:39:04 -07001766 continue;
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001767 }
1768 Atomic<mirror::Object*>* addr = reinterpret_cast<Atomic<mirror::Object*>*>(root);
1769 mirror::Object* expected_ref = ref;
1770 mirror::Object* new_ref = to_ref;
1771 do {
1772 if (expected_ref != addr->LoadRelaxed()) {
1773 // It was updated by the mutator.
1774 break;
1775 }
Hiroshi Yamauchifed3e2f2015-10-20 11:11:56 -07001776 } while (!addr->CompareExchangeWeakRelaxed(expected_ref, new_ref));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001777 }
1778}
1779
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001780template<bool kGrayImmuneObject>
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001781inline void ConcurrentCopying::MarkRoot(mirror::CompressedReference<mirror::Object>* root) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001782 DCHECK(!root->IsNull());
1783 mirror::Object* const ref = root->AsMirrorPtr();
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001784 mirror::Object* to_ref = Mark<kGrayImmuneObject>(ref);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001785 if (to_ref != ref) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001786 auto* addr = reinterpret_cast<Atomic<mirror::CompressedReference<mirror::Object>>*>(root);
1787 auto expected_ref = mirror::CompressedReference<mirror::Object>::FromMirrorPtr(ref);
1788 auto new_ref = mirror::CompressedReference<mirror::Object>::FromMirrorPtr(to_ref);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001789 // If the cas fails, then it was updated by the mutator.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001790 do {
1791 if (ref != addr->LoadRelaxed().AsMirrorPtr()) {
1792 // It was updated by the mutator.
1793 break;
1794 }
Hiroshi Yamauchifed3e2f2015-10-20 11:11:56 -07001795 } while (!addr->CompareExchangeWeakRelaxed(expected_ref, new_ref));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001796 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001797}
1798
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001799inline void ConcurrentCopying::VisitRoots(
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001800 mirror::CompressedReference<mirror::Object>** roots, size_t count,
1801 const RootInfo& info ATTRIBUTE_UNUSED) {
1802 for (size_t i = 0; i < count; ++i) {
1803 mirror::CompressedReference<mirror::Object>* const root = roots[i];
1804 if (!root->IsNull()) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001805 // kGrayImmuneObject is true because this is used for the thread flip.
1806 MarkRoot</*kGrayImmuneObject*/true>(root);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001807 }
1808 }
1809}
1810
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001811// Temporary set gc_grays_immune_objects_ to true in a scope if the current thread is GC.
1812class ConcurrentCopying::ScopedGcGraysImmuneObjects {
1813 public:
1814 explicit ScopedGcGraysImmuneObjects(ConcurrentCopying* collector)
1815 : collector_(collector), enabled_(false) {
1816 if (kUseBakerReadBarrier &&
1817 collector_->thread_running_gc_ == Thread::Current() &&
1818 !collector_->gc_grays_immune_objects_) {
1819 collector_->gc_grays_immune_objects_ = true;
1820 enabled_ = true;
1821 }
1822 }
1823
1824 ~ScopedGcGraysImmuneObjects() {
1825 if (kUseBakerReadBarrier &&
1826 collector_->thread_running_gc_ == Thread::Current() &&
1827 enabled_) {
1828 DCHECK(collector_->gc_grays_immune_objects_);
1829 collector_->gc_grays_immune_objects_ = false;
1830 }
1831 }
1832
1833 private:
1834 ConcurrentCopying* const collector_;
1835 bool enabled_;
1836};
1837
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001838// Fill the given memory block with a dummy object. Used to fill in a
1839// copy of objects that was lost in race.
1840void ConcurrentCopying::FillWithDummyObject(mirror::Object* dummy_obj, size_t byte_size) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001841 // GC doesn't gray immune objects while scanning immune objects. But we need to trigger the read
1842 // barriers here because we need the updated reference to the int array class, etc. Temporary set
1843 // gc_grays_immune_objects_ to true so that we won't cause a DCHECK failure in MarkImmuneSpace().
1844 ScopedGcGraysImmuneObjects scoped_gc_gray_immune_objects(this);
Roland Levillain14d90572015-07-16 10:52:26 +01001845 CHECK_ALIGNED(byte_size, kObjectAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001846 memset(dummy_obj, 0, byte_size);
Mathieu Chartierd6636d32016-07-28 11:02:38 -07001847 // Avoid going through read barrier for since kDisallowReadBarrierDuringScan may be enabled.
1848 // Explicitly mark to make sure to get an object in the to-space.
1849 mirror::Class* int_array_class = down_cast<mirror::Class*>(
1850 Mark(mirror::IntArray::GetArrayClass<kWithoutReadBarrier>()));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001851 CHECK(int_array_class != nullptr);
1852 AssertToSpaceInvariant(nullptr, MemberOffset(0), int_array_class);
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07001853 size_t component_size = int_array_class->GetComponentSize<kWithoutReadBarrier>();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001854 CHECK_EQ(component_size, sizeof(int32_t));
1855 size_t data_offset = mirror::Array::DataOffset(component_size).SizeValue();
1856 if (data_offset > byte_size) {
1857 // An int array is too big. Use java.lang.Object.
1858 mirror::Class* java_lang_Object = WellKnownClasses::ToClass(WellKnownClasses::java_lang_Object);
1859 AssertToSpaceInvariant(nullptr, MemberOffset(0), java_lang_Object);
Mathieu Chartierd6636d32016-07-28 11:02:38 -07001860 CHECK_EQ(byte_size, (java_lang_Object->GetObjectSize<kVerifyNone, kWithoutReadBarrier>()));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001861 dummy_obj->SetClass(java_lang_Object);
Mathieu Chartierd6636d32016-07-28 11:02:38 -07001862 CHECK_EQ(byte_size, (dummy_obj->SizeOf<kVerifyNone, kWithoutReadBarrier>()));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001863 } else {
1864 // Use an int array.
1865 dummy_obj->SetClass(int_array_class);
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07001866 CHECK((dummy_obj->IsArrayInstance<kVerifyNone, kWithoutReadBarrier>()));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001867 int32_t length = (byte_size - data_offset) / component_size;
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07001868 mirror::Array* dummy_arr = dummy_obj->AsArray<kVerifyNone, kWithoutReadBarrier>();
1869 dummy_arr->SetLength(length);
1870 CHECK_EQ(dummy_arr->GetLength(), length)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001871 << "byte_size=" << byte_size << " length=" << length
1872 << " component_size=" << component_size << " data_offset=" << data_offset;
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07001873 CHECK_EQ(byte_size, (dummy_obj->SizeOf<kVerifyNone, kWithoutReadBarrier>()))
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001874 << "byte_size=" << byte_size << " length=" << length
1875 << " component_size=" << component_size << " data_offset=" << data_offset;
1876 }
1877}
1878
1879// Reuse the memory blocks that were copy of objects that were lost in race.
1880mirror::Object* ConcurrentCopying::AllocateInSkippedBlock(size_t alloc_size) {
1881 // Try to reuse the blocks that were unused due to CAS failures.
Roland Levillain14d90572015-07-16 10:52:26 +01001882 CHECK_ALIGNED(alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001883 Thread* self = Thread::Current();
1884 size_t min_object_size = RoundUp(sizeof(mirror::Object), space::RegionSpace::kAlignment);
Mathieu Chartierd6636d32016-07-28 11:02:38 -07001885 size_t byte_size;
1886 uint8_t* addr;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001887 {
Mathieu Chartierd6636d32016-07-28 11:02:38 -07001888 MutexLock mu(self, skipped_blocks_lock_);
1889 auto it = skipped_blocks_map_.lower_bound(alloc_size);
1890 if (it == skipped_blocks_map_.end()) {
1891 // Not found.
1892 return nullptr;
1893 }
1894 byte_size = it->first;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001895 CHECK_GE(byte_size, alloc_size);
1896 if (byte_size > alloc_size && byte_size - alloc_size < min_object_size) {
1897 // If remainder would be too small for a dummy object, retry with a larger request size.
1898 it = skipped_blocks_map_.lower_bound(alloc_size + min_object_size);
1899 if (it == skipped_blocks_map_.end()) {
1900 // Not found.
1901 return nullptr;
1902 }
Roland Levillain14d90572015-07-16 10:52:26 +01001903 CHECK_ALIGNED(it->first - alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001904 CHECK_GE(it->first - alloc_size, min_object_size)
1905 << "byte_size=" << byte_size << " it->first=" << it->first << " alloc_size=" << alloc_size;
1906 }
Mathieu Chartierd6636d32016-07-28 11:02:38 -07001907 // Found a block.
1908 CHECK(it != skipped_blocks_map_.end());
1909 byte_size = it->first;
1910 addr = it->second;
1911 CHECK_GE(byte_size, alloc_size);
1912 CHECK(region_space_->IsInToSpace(reinterpret_cast<mirror::Object*>(addr)));
1913 CHECK_ALIGNED(byte_size, space::RegionSpace::kAlignment);
1914 if (kVerboseMode) {
1915 LOG(INFO) << "Reusing skipped bytes : " << reinterpret_cast<void*>(addr) << ", " << byte_size;
1916 }
1917 skipped_blocks_map_.erase(it);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001918 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001919 memset(addr, 0, byte_size);
1920 if (byte_size > alloc_size) {
1921 // Return the remainder to the map.
Roland Levillain14d90572015-07-16 10:52:26 +01001922 CHECK_ALIGNED(byte_size - alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001923 CHECK_GE(byte_size - alloc_size, min_object_size);
Mathieu Chartierd6636d32016-07-28 11:02:38 -07001924 // FillWithDummyObject may mark an object, avoid holding skipped_blocks_lock_ to prevent lock
1925 // violation and possible deadlock. The deadlock case is a recursive case:
1926 // FillWithDummyObject -> IntArray::GetArrayClass -> Mark -> Copy -> AllocateInSkippedBlock.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001927 FillWithDummyObject(reinterpret_cast<mirror::Object*>(addr + alloc_size),
1928 byte_size - alloc_size);
1929 CHECK(region_space_->IsInToSpace(reinterpret_cast<mirror::Object*>(addr + alloc_size)));
Mathieu Chartierd6636d32016-07-28 11:02:38 -07001930 {
1931 MutexLock mu(self, skipped_blocks_lock_);
1932 skipped_blocks_map_.insert(std::make_pair(byte_size - alloc_size, addr + alloc_size));
1933 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001934 }
1935 return reinterpret_cast<mirror::Object*>(addr);
1936}
1937
1938mirror::Object* ConcurrentCopying::Copy(mirror::Object* from_ref) {
1939 DCHECK(region_space_->IsInFromSpace(from_ref));
1940 // No read barrier to avoid nested RB that might violate the to-space
1941 // invariant. Note that from_ref is a from space ref so the SizeOf()
1942 // call will access the from-space meta objects, but it's ok and necessary.
1943 size_t obj_size = from_ref->SizeOf<kDefaultVerifyFlags, kWithoutReadBarrier>();
1944 size_t region_space_alloc_size = RoundUp(obj_size, space::RegionSpace::kAlignment);
1945 size_t region_space_bytes_allocated = 0U;
1946 size_t non_moving_space_bytes_allocated = 0U;
1947 size_t bytes_allocated = 0U;
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001948 size_t dummy;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001949 mirror::Object* to_ref = region_space_->AllocNonvirtual<true>(
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001950 region_space_alloc_size, &region_space_bytes_allocated, nullptr, &dummy);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001951 bytes_allocated = region_space_bytes_allocated;
1952 if (to_ref != nullptr) {
1953 DCHECK_EQ(region_space_alloc_size, region_space_bytes_allocated);
1954 }
1955 bool fall_back_to_non_moving = false;
1956 if (UNLIKELY(to_ref == nullptr)) {
1957 // Failed to allocate in the region space. Try the skipped blocks.
1958 to_ref = AllocateInSkippedBlock(region_space_alloc_size);
1959 if (to_ref != nullptr) {
1960 // Succeeded to allocate in a skipped block.
1961 if (heap_->use_tlab_) {
1962 // This is necessary for the tlab case as it's not accounted in the space.
1963 region_space_->RecordAlloc(to_ref);
1964 }
1965 bytes_allocated = region_space_alloc_size;
1966 } else {
1967 // Fall back to the non-moving space.
1968 fall_back_to_non_moving = true;
1969 if (kVerboseMode) {
1970 LOG(INFO) << "Out of memory in the to-space. Fall back to non-moving. skipped_bytes="
1971 << to_space_bytes_skipped_.LoadSequentiallyConsistent()
1972 << " skipped_objects=" << to_space_objects_skipped_.LoadSequentiallyConsistent();
1973 }
1974 fall_back_to_non_moving = true;
1975 to_ref = heap_->non_moving_space_->Alloc(Thread::Current(), obj_size,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001976 &non_moving_space_bytes_allocated, nullptr, &dummy);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001977 CHECK(to_ref != nullptr) << "Fall-back non-moving space allocation failed";
1978 bytes_allocated = non_moving_space_bytes_allocated;
1979 // Mark it in the mark bitmap.
1980 accounting::ContinuousSpaceBitmap* mark_bitmap =
1981 heap_mark_bitmap_->GetContinuousSpaceBitmap(to_ref);
1982 CHECK(mark_bitmap != nullptr);
1983 CHECK(!mark_bitmap->AtomicTestAndSet(to_ref));
1984 }
1985 }
1986 DCHECK(to_ref != nullptr);
1987
1988 // Attempt to install the forward pointer. This is in a loop as the
1989 // lock word atomic write can fail.
1990 while (true) {
1991 // Copy the object. TODO: copy only the lockword in the second iteration and on?
1992 memcpy(to_ref, from_ref, obj_size);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001993
1994 LockWord old_lock_word = to_ref->GetLockWord(false);
1995
1996 if (old_lock_word.GetState() == LockWord::kForwardingAddress) {
1997 // Lost the race. Another thread (either GC or mutator) stored
1998 // the forwarding pointer first. Make the lost copy (to_ref)
1999 // look like a valid but dead (dummy) object and keep it for
2000 // future reuse.
2001 FillWithDummyObject(to_ref, bytes_allocated);
2002 if (!fall_back_to_non_moving) {
2003 DCHECK(region_space_->IsInToSpace(to_ref));
2004 if (bytes_allocated > space::RegionSpace::kRegionSize) {
2005 // Free the large alloc.
2006 region_space_->FreeLarge(to_ref, bytes_allocated);
2007 } else {
2008 // Record the lost copy for later reuse.
2009 heap_->num_bytes_allocated_.FetchAndAddSequentiallyConsistent(bytes_allocated);
2010 to_space_bytes_skipped_.FetchAndAddSequentiallyConsistent(bytes_allocated);
2011 to_space_objects_skipped_.FetchAndAddSequentiallyConsistent(1);
2012 MutexLock mu(Thread::Current(), skipped_blocks_lock_);
2013 skipped_blocks_map_.insert(std::make_pair(bytes_allocated,
2014 reinterpret_cast<uint8_t*>(to_ref)));
2015 }
2016 } else {
2017 DCHECK(heap_->non_moving_space_->HasAddress(to_ref));
2018 DCHECK_EQ(bytes_allocated, non_moving_space_bytes_allocated);
2019 // Free the non-moving-space chunk.
2020 accounting::ContinuousSpaceBitmap* mark_bitmap =
2021 heap_mark_bitmap_->GetContinuousSpaceBitmap(to_ref);
2022 CHECK(mark_bitmap != nullptr);
2023 CHECK(mark_bitmap->Clear(to_ref));
2024 heap_->non_moving_space_->Free(Thread::Current(), to_ref);
2025 }
2026
2027 // Get the winner's forward ptr.
2028 mirror::Object* lost_fwd_ptr = to_ref;
2029 to_ref = reinterpret_cast<mirror::Object*>(old_lock_word.ForwardingAddress());
2030 CHECK(to_ref != nullptr);
2031 CHECK_NE(to_ref, lost_fwd_ptr);
2032 CHECK(region_space_->IsInToSpace(to_ref) || heap_->non_moving_space_->HasAddress(to_ref));
2033 CHECK_NE(to_ref->GetLockWord(false).GetState(), LockWord::kForwardingAddress);
2034 return to_ref;
2035 }
2036
Hiroshi Yamauchi60f63f52015-04-23 16:12:40 -07002037 // Set the gray ptr.
2038 if (kUseBakerReadBarrier) {
2039 to_ref->SetReadBarrierPointer(ReadBarrier::GrayPtr());
2040 }
2041
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002042 LockWord new_lock_word = LockWord::FromForwardingAddress(reinterpret_cast<size_t>(to_ref));
2043
2044 // Try to atomically write the fwd ptr.
2045 bool success = from_ref->CasLockWordWeakSequentiallyConsistent(old_lock_word, new_lock_word);
2046 if (LIKELY(success)) {
2047 // The CAS succeeded.
2048 objects_moved_.FetchAndAddSequentiallyConsistent(1);
2049 bytes_moved_.FetchAndAddSequentiallyConsistent(region_space_alloc_size);
2050 if (LIKELY(!fall_back_to_non_moving)) {
2051 DCHECK(region_space_->IsInToSpace(to_ref));
2052 } else {
2053 DCHECK(heap_->non_moving_space_->HasAddress(to_ref));
2054 DCHECK_EQ(bytes_allocated, non_moving_space_bytes_allocated);
2055 }
2056 if (kUseBakerReadBarrier) {
2057 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr());
2058 }
2059 DCHECK(GetFwdPtr(from_ref) == to_ref);
2060 CHECK_NE(to_ref->GetLockWord(false).GetState(), LockWord::kForwardingAddress);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002061 PushOntoMarkStack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002062 return to_ref;
2063 } else {
2064 // The CAS failed. It may have lost the race or may have failed
2065 // due to monitor/hashcode ops. Either way, retry.
2066 }
2067 }
2068}
2069
2070mirror::Object* ConcurrentCopying::IsMarked(mirror::Object* from_ref) {
2071 DCHECK(from_ref != nullptr);
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08002072 space::RegionSpace::RegionType rtype = region_space_->GetRegionType(from_ref);
2073 if (rtype == space::RegionSpace::RegionType::kRegionTypeToSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002074 // It's already marked.
2075 return from_ref;
2076 }
2077 mirror::Object* to_ref;
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08002078 if (rtype == space::RegionSpace::RegionType::kRegionTypeFromSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002079 to_ref = GetFwdPtr(from_ref);
2080 DCHECK(to_ref == nullptr || region_space_->IsInToSpace(to_ref) ||
2081 heap_->non_moving_space_->HasAddress(to_ref))
2082 << "from_ref=" << from_ref << " to_ref=" << to_ref;
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08002083 } else if (rtype == space::RegionSpace::RegionType::kRegionTypeUnevacFromSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002084 if (region_space_bitmap_->Test(from_ref)) {
2085 to_ref = from_ref;
2086 } else {
2087 to_ref = nullptr;
2088 }
2089 } else {
2090 // from_ref is in a non-moving space.
Mathieu Chartier763a31e2015-11-16 16:05:55 -08002091 if (immune_spaces_.ContainsObject(from_ref)) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002092 // An immune object is alive.
2093 to_ref = from_ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002094 } else {
2095 // Non-immune non-moving space. Use the mark bitmap.
2096 accounting::ContinuousSpaceBitmap* mark_bitmap =
2097 heap_mark_bitmap_->GetContinuousSpaceBitmap(from_ref);
2098 accounting::LargeObjectBitmap* los_bitmap =
2099 heap_mark_bitmap_->GetLargeObjectBitmap(from_ref);
2100 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
2101 bool is_los = mark_bitmap == nullptr;
2102 if (!is_los && mark_bitmap->Test(from_ref)) {
2103 // Already marked.
2104 to_ref = from_ref;
2105 } else if (is_los && los_bitmap->Test(from_ref)) {
2106 // Already marked in LOS.
2107 to_ref = from_ref;
2108 } else {
2109 // Not marked.
2110 if (IsOnAllocStack(from_ref)) {
2111 // If on the allocation stack, it's considered marked.
2112 to_ref = from_ref;
2113 } else {
2114 // Not marked.
2115 to_ref = nullptr;
2116 }
2117 }
2118 }
2119 }
2120 return to_ref;
2121}
2122
2123bool ConcurrentCopying::IsOnAllocStack(mirror::Object* ref) {
2124 QuasiAtomic::ThreadFenceAcquire();
2125 accounting::ObjectStack* alloc_stack = GetAllocationStack();
Mathieu Chartiercb535da2015-01-23 13:50:03 -08002126 return alloc_stack->Contains(ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002127}
2128
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002129mirror::Object* ConcurrentCopying::MarkNonMoving(mirror::Object* ref) {
2130 // ref is in a non-moving space (from_ref == to_ref).
2131 DCHECK(!region_space_->HasAddress(ref)) << ref;
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002132 DCHECK(!immune_spaces_.ContainsObject(ref));
2133 // Use the mark bitmap.
2134 accounting::ContinuousSpaceBitmap* mark_bitmap =
2135 heap_mark_bitmap_->GetContinuousSpaceBitmap(ref);
2136 accounting::LargeObjectBitmap* los_bitmap =
2137 heap_mark_bitmap_->GetLargeObjectBitmap(ref);
2138 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
2139 bool is_los = mark_bitmap == nullptr;
2140 if (!is_los && mark_bitmap->Test(ref)) {
2141 // Already marked.
2142 if (kUseBakerReadBarrier) {
2143 DCHECK(ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr() ||
2144 ref->GetReadBarrierPointer() == ReadBarrier::WhitePtr());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002145 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002146 } else if (is_los && los_bitmap->Test(ref)) {
2147 // Already marked in LOS.
2148 if (kUseBakerReadBarrier) {
2149 DCHECK(ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr() ||
2150 ref->GetReadBarrierPointer() == ReadBarrier::WhitePtr());
2151 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002152 } else {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002153 // Not marked.
2154 if (IsOnAllocStack(ref)) {
2155 // If it's on the allocation stack, it's considered marked. Keep it white.
2156 // Objects on the allocation stack need not be marked.
2157 if (!is_los) {
2158 DCHECK(!mark_bitmap->Test(ref));
2159 } else {
2160 DCHECK(!los_bitmap->Test(ref));
Nicolas Geoffrayddeb1722016-06-28 08:25:59 +00002161 }
Nicolas Geoffrayddeb1722016-06-28 08:25:59 +00002162 if (kUseBakerReadBarrier) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002163 DCHECK_EQ(ref->GetReadBarrierPointer(), ReadBarrier::WhitePtr());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002164 }
2165 } else {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002166 // For the baker-style RB, we need to handle 'false-gray' cases. See the
2167 // kRegionTypeUnevacFromSpace-case comment in Mark().
2168 if (kUseBakerReadBarrier) {
2169 // Test the bitmap first to reduce the chance of false gray cases.
2170 if ((!is_los && mark_bitmap->Test(ref)) ||
2171 (is_los && los_bitmap->Test(ref))) {
2172 return ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002173 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002174 }
2175 // Not marked or on the allocation stack. Try to mark it.
2176 // This may or may not succeed, which is ok.
2177 bool cas_success = false;
2178 if (kUseBakerReadBarrier) {
2179 cas_success = ref->AtomicSetReadBarrierPointer(ReadBarrier::WhitePtr(),
2180 ReadBarrier::GrayPtr());
2181 }
2182 if (!is_los && mark_bitmap->AtomicTestAndSet(ref)) {
2183 // Already marked.
2184 if (kUseBakerReadBarrier && cas_success &&
2185 ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr()) {
2186 PushOntoFalseGrayStack(ref);
2187 }
2188 } else if (is_los && los_bitmap->AtomicTestAndSet(ref)) {
2189 // Already marked in LOS.
2190 if (kUseBakerReadBarrier && cas_success &&
2191 ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr()) {
2192 PushOntoFalseGrayStack(ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002193 }
2194 } else {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002195 // Newly marked.
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08002196 if (kUseBakerReadBarrier) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002197 DCHECK_EQ(ref->GetReadBarrierPointer(), ReadBarrier::GrayPtr());
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08002198 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002199 PushOntoMarkStack(ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002200 }
2201 }
2202 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002203 return ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002204}
2205
2206void ConcurrentCopying::FinishPhase() {
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -08002207 Thread* const self = Thread::Current();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002208 {
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -08002209 MutexLock mu(self, mark_stack_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002210 CHECK_EQ(pooled_mark_stacks_.size(), kMarkStackPoolSize);
2211 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002212 region_space_ = nullptr;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002213 {
2214 MutexLock mu(Thread::Current(), skipped_blocks_lock_);
2215 skipped_blocks_map_.clear();
2216 }
Mathieu Chartier56fe2582016-07-14 13:30:03 -07002217 {
2218 ReaderMutexLock mu(self, *Locks::mutator_lock_);
Mathieu Chartier21328a12016-07-22 10:47:45 -07002219 {
2220 WriterMutexLock mu2(self, *Locks::heap_bitmap_lock_);
2221 heap_->ClearMarkedObjects();
2222 }
2223 if (kUseBakerReadBarrier && kFilterModUnionCards) {
2224 TimingLogger::ScopedTiming split("FilterModUnionCards", GetTimings());
2225 ReaderMutexLock mu2(self, *Locks::heap_bitmap_lock_);
2226 gc::Heap* const heap = Runtime::Current()->GetHeap();
2227 for (space::ContinuousSpace* space : immune_spaces_.GetSpaces()) {
2228 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
2229 accounting::ModUnionTable* table = heap->FindModUnionTableFromSpace(space);
2230 // Filter out cards that don't need to be set.
2231 if (table != nullptr) {
2232 table->FilterCards();
2233 }
2234 }
2235 }
Mathieu Chartier56fe2582016-07-14 13:30:03 -07002236 }
2237 if (measure_read_barrier_slow_path_) {
2238 MutexLock mu(self, rb_slow_path_histogram_lock_);
2239 rb_slow_path_time_histogram_.AdjustAndAddValue(rb_slow_path_ns_.LoadRelaxed());
2240 rb_slow_path_count_total_ += rb_slow_path_count_.LoadRelaxed();
2241 rb_slow_path_count_gc_total_ += rb_slow_path_count_gc_.LoadRelaxed();
2242 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002243}
2244
Mathieu Chartier97509952015-07-13 14:35:43 -07002245bool ConcurrentCopying::IsMarkedHeapReference(mirror::HeapReference<mirror::Object>* field) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002246 mirror::Object* from_ref = field->AsMirrorPtr();
Mathieu Chartier97509952015-07-13 14:35:43 -07002247 mirror::Object* to_ref = IsMarked(from_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002248 if (to_ref == nullptr) {
2249 return false;
2250 }
2251 if (from_ref != to_ref) {
2252 QuasiAtomic::ThreadFenceRelease();
2253 field->Assign(to_ref);
2254 QuasiAtomic::ThreadFenceSequentiallyConsistent();
2255 }
2256 return true;
2257}
2258
Mathieu Chartier97509952015-07-13 14:35:43 -07002259mirror::Object* ConcurrentCopying::MarkObject(mirror::Object* from_ref) {
2260 return Mark(from_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002261}
2262
2263void ConcurrentCopying::DelayReferenceReferent(mirror::Class* klass, mirror::Reference* reference) {
Mathieu Chartier97509952015-07-13 14:35:43 -07002264 heap_->GetReferenceProcessor()->DelayReferenceReferent(klass, reference, this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002265}
2266
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002267void ConcurrentCopying::ProcessReferences(Thread* self) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002268 TimingLogger::ScopedTiming split("ProcessReferences", GetTimings());
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002269 // 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 -08002270 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
2271 GetHeap()->GetReferenceProcessor()->ProcessReferences(
Mathieu Chartier97509952015-07-13 14:35:43 -07002272 true /*concurrent*/, GetTimings(), GetCurrentIteration()->GetClearSoftReferences(), this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002273}
2274
2275void ConcurrentCopying::RevokeAllThreadLocalBuffers() {
2276 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
2277 region_space_->RevokeAllThreadLocalBuffers();
2278}
2279
Mathieu Chartier56fe2582016-07-14 13:30:03 -07002280mirror::Object* ConcurrentCopying::MarkFromReadBarrierWithMeasurements(mirror::Object* from_ref) {
2281 if (Thread::Current() != thread_running_gc_) {
2282 rb_slow_path_count_.FetchAndAddRelaxed(1u);
2283 } else {
2284 rb_slow_path_count_gc_.FetchAndAddRelaxed(1u);
2285 }
2286 ScopedTrace tr(__FUNCTION__);
2287 const uint64_t start_time = measure_read_barrier_slow_path_ ? NanoTime() : 0u;
2288 mirror::Object* ret = Mark(from_ref);
2289 if (measure_read_barrier_slow_path_) {
2290 rb_slow_path_ns_.FetchAndAddRelaxed(NanoTime() - start_time);
2291 }
2292 return ret;
2293}
2294
2295void ConcurrentCopying::DumpPerformanceInfo(std::ostream& os) {
2296 GarbageCollector::DumpPerformanceInfo(os);
2297 MutexLock mu(Thread::Current(), rb_slow_path_histogram_lock_);
2298 if (rb_slow_path_time_histogram_.SampleSize() > 0) {
2299 Histogram<uint64_t>::CumulativeData cumulative_data;
2300 rb_slow_path_time_histogram_.CreateHistogram(&cumulative_data);
2301 rb_slow_path_time_histogram_.PrintConfidenceIntervals(os, 0.99, cumulative_data);
2302 }
2303 if (rb_slow_path_count_total_ > 0) {
2304 os << "Slow path count " << rb_slow_path_count_total_ << "\n";
2305 }
2306 if (rb_slow_path_count_gc_total_ > 0) {
2307 os << "GC slow path count " << rb_slow_path_count_gc_total_ << "\n";
2308 }
2309}
2310
Hiroshi Yamauchid5307ec2014-03-27 21:07:51 -07002311} // namespace collector
2312} // namespace gc
2313} // namespace art