blob: 285b111c4d0f1d18b8f7bed30dca9799b764207f [file] [log] [blame]
Hiroshi Yamauchid5307ec2014-03-27 21:07:51 -07001/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "concurrent_copying.h"
18
Mathieu Chartierc7853442015-03-27 14:35:38 -070019#include "art_field-inl.h"
Andreas Gampe542451c2016-07-26 09:02:02 -070020#include "base/enums.h"
Mathieu Chartier56fe2582016-07-14 13:30:03 -070021#include "base/histogram-inl.h"
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070022#include "base/stl_util.h"
Mathieu Chartier56fe2582016-07-14 13:30:03 -070023#include "base/systrace.h"
Mathieu Chartiera6b1ead2015-10-06 10:32:38 -070024#include "debugger.h"
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080025#include "gc/accounting/heap_bitmap-inl.h"
Mathieu Chartier21328a12016-07-22 10:47:45 -070026#include "gc/accounting/mod_union_table-inl.h"
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080027#include "gc/accounting/space_bitmap-inl.h"
Mathieu Chartier3cf22532015-07-09 15:15:09 -070028#include "gc/reference_processor.h"
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080029#include "gc/space/image_space.h"
Mathieu Chartier073b16c2015-11-10 14:13:23 -080030#include "gc/space/space-inl.h"
Mathieu Chartier4a26f172016-01-26 14:26:18 -080031#include "image-inl.h"
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080032#include "intern_table.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070033#include "mirror/class-inl.h"
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080034#include "mirror/object-inl.h"
35#include "scoped_thread_state_change.h"
36#include "thread-inl.h"
37#include "thread_list.h"
38#include "well_known_classes.h"
39
Hiroshi Yamauchid5307ec2014-03-27 21:07:51 -070040namespace art {
41namespace gc {
42namespace collector {
43
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -070044static constexpr size_t kDefaultGcMarkStackSize = 2 * MB;
Mathieu Chartier21328a12016-07-22 10:47:45 -070045// If kFilterModUnionCards then we attempt to filter cards that don't need to be dirty in the mod
46// union table. Disabled since it does not seem to help the pause much.
47static constexpr bool kFilterModUnionCards = kIsDebugBuild;
Mathieu Chartierd6636d32016-07-28 11:02:38 -070048// If kDisallowReadBarrierDuringScan is true then the GC aborts if there are any that occur during
49// ConcurrentCopying::Scan. May be used to diagnose possibly unnecessary read barriers.
50// Only enabled for kIsDebugBuild to avoid performance hit.
51static constexpr bool kDisallowReadBarrierDuringScan = kIsDebugBuild;
Mathieu Chartier36a270a2016-07-28 18:08:51 -070052// Slow path mark stack size, increase this if the stack is getting full and it is causing
53// performance problems.
54static constexpr size_t kReadBarrierMarkStackSize = 512 * KB;
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -070055
Mathieu Chartier56fe2582016-07-14 13:30:03 -070056ConcurrentCopying::ConcurrentCopying(Heap* heap,
57 const std::string& name_prefix,
58 bool measure_read_barrier_slow_path)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080059 : GarbageCollector(heap,
60 name_prefix + (name_prefix.empty() ? "" : " ") +
61 "concurrent copying + mark sweep"),
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070062 region_space_(nullptr), gc_barrier_(new Barrier(0)),
63 gc_mark_stack_(accounting::ObjectStack::Create("concurrent copying gc mark stack",
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -070064 kDefaultGcMarkStackSize,
65 kDefaultGcMarkStackSize)),
Mathieu Chartier36a270a2016-07-28 18:08:51 -070066 rb_mark_bit_stack_(accounting::ObjectStack::Create("rb copying gc mark stack",
67 kReadBarrierMarkStackSize,
68 kReadBarrierMarkStackSize)),
69 rb_mark_bit_stack_full_(false),
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070070 mark_stack_lock_("concurrent copying mark stack lock", kMarkSweepMarkStackLock),
71 thread_running_gc_(nullptr),
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080072 is_marking_(false), is_active_(false), is_asserting_to_space_invariant_(false),
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -070073 region_space_bitmap_(nullptr),
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070074 heap_mark_bitmap_(nullptr), live_stack_freeze_size_(0), mark_stack_mode_(kMarkStackModeOff),
75 weak_ref_access_enabled_(true),
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080076 skipped_blocks_lock_("concurrent copying bytes blocks lock", kMarkSweepMarkStackLock),
Mathieu Chartier56fe2582016-07-14 13:30:03 -070077 measure_read_barrier_slow_path_(measure_read_barrier_slow_path),
78 rb_slow_path_ns_(0),
79 rb_slow_path_count_(0),
80 rb_slow_path_count_gc_(0),
81 rb_slow_path_histogram_lock_("Read barrier histogram lock"),
82 rb_slow_path_time_histogram_("Mutator time in read barrier slow path", 500, 32),
83 rb_slow_path_count_total_(0),
84 rb_slow_path_count_gc_total_(0),
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080085 rb_table_(heap_->GetReadBarrierTable()),
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -070086 force_evacuate_all_(false),
87 immune_gray_stack_lock_("concurrent copying immune gray stack lock",
88 kMarkSweepMarkStackLock) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080089 static_assert(space::RegionSpace::kRegionSize == accounting::ReadBarrierTable::kRegionSize,
90 "The region space size and the read barrier table region size must match");
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070091 Thread* self = Thread::Current();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080092 {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080093 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
94 // Cache this so that we won't have to lock heap_bitmap_lock_ in
95 // Mark() which could cause a nested lock on heap_bitmap_lock_
96 // when GC causes a RB while doing GC or a lock order violation
97 // (class_linker_lock_ and heap_bitmap_lock_).
98 heap_mark_bitmap_ = heap->GetMarkBitmap();
99 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700100 {
101 MutexLock mu(self, mark_stack_lock_);
102 for (size_t i = 0; i < kMarkStackPoolSize; ++i) {
103 accounting::AtomicStack<mirror::Object>* mark_stack =
104 accounting::AtomicStack<mirror::Object>::Create(
105 "thread local mark stack", kMarkStackSize, kMarkStackSize);
106 pooled_mark_stacks_.push_back(mark_stack);
107 }
108 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800109}
110
Mathieu Chartierb19ccb12015-07-15 10:24:16 -0700111void ConcurrentCopying::MarkHeapReference(mirror::HeapReference<mirror::Object>* from_ref) {
112 // Used for preserving soft references, should be OK to not have a CAS here since there should be
113 // no other threads which can trigger read barriers on the same referent during reference
114 // processing.
115 from_ref->Assign(Mark(from_ref->AsMirrorPtr()));
Mathieu Chartier81187812015-07-15 14:24:07 -0700116 DCHECK(!from_ref->IsNull());
Mathieu Chartier97509952015-07-13 14:35:43 -0700117}
118
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800119ConcurrentCopying::~ConcurrentCopying() {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700120 STLDeleteElements(&pooled_mark_stacks_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800121}
122
123void ConcurrentCopying::RunPhases() {
124 CHECK(kUseBakerReadBarrier || kUseTableLookupReadBarrier);
125 CHECK(!is_active_);
126 is_active_ = true;
127 Thread* self = Thread::Current();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700128 thread_running_gc_ = self;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800129 Locks::mutator_lock_->AssertNotHeld(self);
130 {
131 ReaderMutexLock mu(self, *Locks::mutator_lock_);
132 InitializePhase();
133 }
134 FlipThreadRoots();
135 {
136 ReaderMutexLock mu(self, *Locks::mutator_lock_);
137 MarkingPhase();
138 }
139 // Verify no from space refs. This causes a pause.
140 if (kEnableNoFromSpaceRefsVerification || kIsDebugBuild) {
141 TimingLogger::ScopedTiming split("(Paused)VerifyNoFromSpaceReferences", GetTimings());
142 ScopedPause pause(this);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700143 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800144 if (kVerboseMode) {
145 LOG(INFO) << "Verifying no from-space refs";
146 }
147 VerifyNoFromSpaceReferences();
Mathieu Chartier720e71a2015-04-06 17:10:58 -0700148 if (kVerboseMode) {
149 LOG(INFO) << "Done verifying no from-space refs";
150 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700151 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800152 }
153 {
154 ReaderMutexLock mu(self, *Locks::mutator_lock_);
155 ReclaimPhase();
156 }
157 FinishPhase();
158 CHECK(is_active_);
159 is_active_ = false;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700160 thread_running_gc_ = nullptr;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800161}
162
163void ConcurrentCopying::BindBitmaps() {
164 Thread* self = Thread::Current();
165 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
166 // Mark all of the spaces we never collect as immune.
167 for (const auto& space : heap_->GetContinuousSpaces()) {
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800168 if (space->GetGcRetentionPolicy() == space::kGcRetentionPolicyNeverCollect ||
169 space->GetGcRetentionPolicy() == space::kGcRetentionPolicyFullCollect) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800170 CHECK(space->IsZygoteSpace() || space->IsImageSpace());
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800171 immune_spaces_.AddSpace(space);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800172 } else if (space == region_space_) {
173 accounting::ContinuousSpaceBitmap* bitmap =
174 accounting::ContinuousSpaceBitmap::Create("cc region space bitmap",
175 space->Begin(), space->Capacity());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800176 region_space_bitmap_ = bitmap;
177 }
178 }
179}
180
181void ConcurrentCopying::InitializePhase() {
182 TimingLogger::ScopedTiming split("InitializePhase", GetTimings());
183 if (kVerboseMode) {
184 LOG(INFO) << "GC InitializePhase";
185 LOG(INFO) << "Region-space : " << reinterpret_cast<void*>(region_space_->Begin()) << "-"
186 << reinterpret_cast<void*>(region_space_->Limit());
187 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700188 CheckEmptyMarkStack();
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800189 if (kIsDebugBuild) {
190 MutexLock mu(Thread::Current(), mark_stack_lock_);
191 CHECK(false_gray_stack_.empty());
192 }
Mathieu Chartier56fe2582016-07-14 13:30:03 -0700193
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700194 rb_mark_bit_stack_full_ = false;
Mathieu Chartier56fe2582016-07-14 13:30:03 -0700195 mark_from_read_barrier_measurements_ = measure_read_barrier_slow_path_;
196 if (measure_read_barrier_slow_path_) {
197 rb_slow_path_ns_.StoreRelaxed(0);
198 rb_slow_path_count_.StoreRelaxed(0);
199 rb_slow_path_count_gc_.StoreRelaxed(0);
200 }
201
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800202 immune_spaces_.Reset();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800203 bytes_moved_.StoreRelaxed(0);
204 objects_moved_.StoreRelaxed(0);
Hiroshi Yamauchi60985b72016-08-24 13:53:12 -0700205 GcCause gc_cause = GetCurrentIteration()->GetGcCause();
206 if (gc_cause == kGcCauseExplicit ||
207 gc_cause == kGcCauseForNativeAlloc ||
208 gc_cause == kGcCauseCollectorTransition ||
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800209 GetCurrentIteration()->GetClearSoftReferences()) {
210 force_evacuate_all_ = true;
211 } else {
212 force_evacuate_all_ = false;
213 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700214 if (kUseBakerReadBarrier) {
215 updated_all_immune_objects_.StoreRelaxed(false);
216 // GC may gray immune objects in the thread flip.
217 gc_grays_immune_objects_ = true;
218 if (kIsDebugBuild) {
219 MutexLock mu(Thread::Current(), immune_gray_stack_lock_);
220 DCHECK(immune_gray_stack_.empty());
221 }
222 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800223 BindBitmaps();
224 if (kVerboseMode) {
225 LOG(INFO) << "force_evacuate_all=" << force_evacuate_all_;
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800226 LOG(INFO) << "Largest immune region: " << immune_spaces_.GetLargestImmuneRegion().Begin()
227 << "-" << immune_spaces_.GetLargestImmuneRegion().End();
228 for (space::ContinuousSpace* space : immune_spaces_.GetSpaces()) {
229 LOG(INFO) << "Immune space: " << *space;
230 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800231 LOG(INFO) << "GC end of InitializePhase";
232 }
Mathieu Chartier962cd7a2016-08-16 12:15:59 -0700233 // Mark all of the zygote large objects without graying them.
234 MarkZygoteLargeObjects();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800235}
236
237// Used to switch the thread roots of a thread from from-space refs to to-space refs.
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700238class ConcurrentCopying::ThreadFlipVisitor : public Closure, public RootVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800239 public:
Roland Levillain3887c462015-08-12 18:15:42 +0100240 ThreadFlipVisitor(ConcurrentCopying* concurrent_copying, bool use_tlab)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800241 : concurrent_copying_(concurrent_copying), use_tlab_(use_tlab) {
242 }
243
Mathieu Chartier90443472015-07-16 20:32:27 -0700244 virtual void Run(Thread* thread) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800245 // Note: self is not necessarily equal to thread since thread may be suspended.
246 Thread* self = Thread::Current();
247 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
248 << thread->GetState() << " thread " << thread << " self " << self;
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700249 thread->SetIsGcMarking(true);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800250 if (use_tlab_ && thread->HasTlab()) {
251 if (ConcurrentCopying::kEnableFromSpaceAccountingCheck) {
252 // This must come before the revoke.
253 size_t thread_local_objects = thread->GetThreadLocalObjectsAllocated();
254 concurrent_copying_->region_space_->RevokeThreadLocalBuffers(thread);
255 reinterpret_cast<Atomic<size_t>*>(&concurrent_copying_->from_space_num_objects_at_first_pause_)->
256 FetchAndAddSequentiallyConsistent(thread_local_objects);
257 } else {
258 concurrent_copying_->region_space_->RevokeThreadLocalBuffers(thread);
259 }
260 }
261 if (kUseThreadLocalAllocationStack) {
262 thread->RevokeThreadLocalAllocationStack();
263 }
264 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700265 // We can use the non-CAS VisitRoots functions below because we update thread-local GC roots
266 // only.
267 thread->VisitRoots(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800268 concurrent_copying_->GetBarrier().Pass(self);
269 }
270
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700271 void VisitRoots(mirror::Object*** roots,
272 size_t count,
273 const RootInfo& info ATTRIBUTE_UNUSED)
274 SHARED_REQUIRES(Locks::mutator_lock_) {
275 for (size_t i = 0; i < count; ++i) {
276 mirror::Object** root = roots[i];
277 mirror::Object* ref = *root;
278 if (ref != nullptr) {
279 mirror::Object* to_ref = concurrent_copying_->Mark(ref);
280 if (to_ref != ref) {
281 *root = to_ref;
282 }
283 }
284 }
285 }
286
287 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots,
288 size_t count,
289 const RootInfo& info ATTRIBUTE_UNUSED)
290 SHARED_REQUIRES(Locks::mutator_lock_) {
291 for (size_t i = 0; i < count; ++i) {
292 mirror::CompressedReference<mirror::Object>* const root = roots[i];
293 if (!root->IsNull()) {
294 mirror::Object* ref = root->AsMirrorPtr();
295 mirror::Object* to_ref = concurrent_copying_->Mark(ref);
296 if (to_ref != ref) {
297 root->Assign(to_ref);
298 }
299 }
300 }
301 }
302
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800303 private:
304 ConcurrentCopying* const concurrent_copying_;
305 const bool use_tlab_;
306};
307
308// Called back from Runtime::FlipThreadRoots() during a pause.
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700309class ConcurrentCopying::FlipCallback : public Closure {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800310 public:
311 explicit FlipCallback(ConcurrentCopying* concurrent_copying)
312 : concurrent_copying_(concurrent_copying) {
313 }
314
Mathieu Chartier90443472015-07-16 20:32:27 -0700315 virtual void Run(Thread* thread) OVERRIDE REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800316 ConcurrentCopying* cc = concurrent_copying_;
317 TimingLogger::ScopedTiming split("(Paused)FlipCallback", cc->GetTimings());
318 // Note: self is not necessarily equal to thread since thread may be suspended.
319 Thread* self = Thread::Current();
320 CHECK(thread == self);
321 Locks::mutator_lock_->AssertExclusiveHeld(self);
322 cc->region_space_->SetFromSpace(cc->rb_table_, cc->force_evacuate_all_);
Mathieu Chartiera4f6af92015-08-11 17:35:25 -0700323 cc->SwapStacks();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800324 if (ConcurrentCopying::kEnableFromSpaceAccountingCheck) {
325 cc->RecordLiveStackFreezeSize(self);
326 cc->from_space_num_objects_at_first_pause_ = cc->region_space_->GetObjectsAllocated();
327 cc->from_space_num_bytes_at_first_pause_ = cc->region_space_->GetBytesAllocated();
328 }
329 cc->is_marking_ = true;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700330 cc->mark_stack_mode_.StoreRelaxed(ConcurrentCopying::kMarkStackModeThreadLocal);
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800331 if (kIsDebugBuild) {
332 cc->region_space_->AssertAllRegionLiveBytesZeroOrCleared();
333 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800334 if (UNLIKELY(Runtime::Current()->IsActiveTransaction())) {
Mathieu Chartier184c9dc2015-03-05 13:20:54 -0800335 CHECK(Runtime::Current()->IsAotCompiler());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800336 TimingLogger::ScopedTiming split2("(Paused)VisitTransactionRoots", cc->GetTimings());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700337 Runtime::Current()->VisitTransactionRoots(cc);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800338 }
Mathieu Chartier21328a12016-07-22 10:47:45 -0700339 if (kUseBakerReadBarrier && kGrayDirtyImmuneObjects) {
340 cc->GrayAllDirtyImmuneObjects();
341 if (kIsDebugBuild) {
342 // Check that all non-gray immune objects only refernce immune objects.
343 cc->VerifyGrayImmuneObjects();
344 }
345 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800346 }
347
348 private:
349 ConcurrentCopying* const concurrent_copying_;
350};
351
Mathieu Chartier21328a12016-07-22 10:47:45 -0700352class ConcurrentCopying::VerifyGrayImmuneObjectsVisitor {
353 public:
354 explicit VerifyGrayImmuneObjectsVisitor(ConcurrentCopying* collector)
355 : collector_(collector) {}
356
357 void operator()(mirror::Object* obj, MemberOffset offset, bool /* is_static */)
358 const ALWAYS_INLINE SHARED_REQUIRES(Locks::mutator_lock_)
359 SHARED_REQUIRES(Locks::heap_bitmap_lock_) {
360 CheckReference(obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(offset),
361 obj, offset);
362 }
363
364 void operator()(mirror::Class* klass, mirror::Reference* ref) const
365 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
366 CHECK(klass->IsTypeOfReferenceClass());
367 CheckReference(ref->GetReferent<kWithoutReadBarrier>(),
368 ref,
369 mirror::Reference::ReferentOffset());
370 }
371
372 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
373 ALWAYS_INLINE
374 SHARED_REQUIRES(Locks::mutator_lock_) {
375 if (!root->IsNull()) {
376 VisitRoot(root);
377 }
378 }
379
380 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
381 ALWAYS_INLINE
382 SHARED_REQUIRES(Locks::mutator_lock_) {
383 CheckReference(root->AsMirrorPtr(), nullptr, MemberOffset(0));
384 }
385
386 private:
387 ConcurrentCopying* const collector_;
388
389 void CheckReference(mirror::Object* ref, mirror::Object* holder, MemberOffset offset) const
390 SHARED_REQUIRES(Locks::mutator_lock_) {
391 if (ref != nullptr) {
Mathieu Chartier962cd7a2016-08-16 12:15:59 -0700392 if (!collector_->immune_spaces_.ContainsObject(ref)) {
393 // Not immune, must be a zygote large object.
394 CHECK(Runtime::Current()->GetHeap()->GetLargeObjectsSpace()->IsZygoteLargeObject(
395 Thread::Current(), ref))
396 << "Non gray object references non immune, non zygote large object "<< ref << " "
397 << PrettyTypeOf(ref) << " in holder " << holder << " " << PrettyTypeOf(holder)
398 << " offset=" << offset.Uint32Value();
399 } else {
400 // Make sure the large object class is immune since we will never scan the large object.
401 CHECK(collector_->immune_spaces_.ContainsObject(
402 ref->GetClass<kVerifyNone, kWithoutReadBarrier>()));
403 }
Mathieu Chartier21328a12016-07-22 10:47:45 -0700404 }
405 }
406};
407
408void ConcurrentCopying::VerifyGrayImmuneObjects() {
409 TimingLogger::ScopedTiming split(__FUNCTION__, GetTimings());
410 for (auto& space : immune_spaces_.GetSpaces()) {
411 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
412 accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
413 VerifyGrayImmuneObjectsVisitor visitor(this);
414 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()),
415 reinterpret_cast<uintptr_t>(space->Limit()),
416 [&visitor](mirror::Object* obj)
417 SHARED_REQUIRES(Locks::mutator_lock_) {
418 // If an object is not gray, it should only have references to things in the immune spaces.
419 if (obj->GetReadBarrierPointer() != ReadBarrier::GrayPtr()) {
420 obj->VisitReferences</*kVisitNativeRoots*/true,
421 kDefaultVerifyFlags,
422 kWithoutReadBarrier>(visitor, visitor);
423 }
424 });
425 }
426}
427
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800428// Switch threads that from from-space to to-space refs. Forward/mark the thread roots.
429void ConcurrentCopying::FlipThreadRoots() {
430 TimingLogger::ScopedTiming split("FlipThreadRoots", GetTimings());
431 if (kVerboseMode) {
432 LOG(INFO) << "time=" << region_space_->Time();
433 region_space_->DumpNonFreeRegions(LOG(INFO));
434 }
435 Thread* self = Thread::Current();
436 Locks::mutator_lock_->AssertNotHeld(self);
437 gc_barrier_->Init(self, 0);
438 ThreadFlipVisitor thread_flip_visitor(this, heap_->use_tlab_);
439 FlipCallback flip_callback(this);
440 size_t barrier_count = Runtime::Current()->FlipThreadRoots(
441 &thread_flip_visitor, &flip_callback, this);
442 {
443 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
444 gc_barrier_->Increment(self, barrier_count);
445 }
446 is_asserting_to_space_invariant_ = true;
447 QuasiAtomic::ThreadFenceForConstructor();
448 if (kVerboseMode) {
449 LOG(INFO) << "time=" << region_space_->Time();
450 region_space_->DumpNonFreeRegions(LOG(INFO));
451 LOG(INFO) << "GC end of FlipThreadRoots";
452 }
453}
454
Mathieu Chartier21328a12016-07-22 10:47:45 -0700455class ConcurrentCopying::GrayImmuneObjectVisitor {
456 public:
457 explicit GrayImmuneObjectVisitor() {}
458
459 ALWAYS_INLINE void operator()(mirror::Object* obj) const SHARED_REQUIRES(Locks::mutator_lock_) {
460 if (kUseBakerReadBarrier) {
461 if (kIsDebugBuild) {
462 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
463 }
464 obj->SetReadBarrierPointer(ReadBarrier::GrayPtr());
465 }
466 }
467
468 static void Callback(mirror::Object* obj, void* arg) SHARED_REQUIRES(Locks::mutator_lock_) {
469 reinterpret_cast<GrayImmuneObjectVisitor*>(arg)->operator()(obj);
470 }
471};
472
473void ConcurrentCopying::GrayAllDirtyImmuneObjects() {
474 TimingLogger::ScopedTiming split(__FUNCTION__, GetTimings());
475 gc::Heap* const heap = Runtime::Current()->GetHeap();
476 accounting::CardTable* const card_table = heap->GetCardTable();
477 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
478 for (space::ContinuousSpace* space : immune_spaces_.GetSpaces()) {
479 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
480 GrayImmuneObjectVisitor visitor;
481 accounting::ModUnionTable* table = heap->FindModUnionTableFromSpace(space);
482 // Mark all the objects on dirty cards since these may point to objects in other space.
483 // Once these are marked, the GC will eventually clear them later.
484 // Table is non null for boot image and zygote spaces. It is only null for application image
485 // spaces.
486 if (table != nullptr) {
487 // TODO: Add preclean outside the pause.
488 table->ClearCards();
489 table->VisitObjects(GrayImmuneObjectVisitor::Callback, &visitor);
490 } else {
491 // TODO: Consider having a mark bitmap for app image spaces and avoid scanning during the
492 // pause because app image spaces are all dirty pages anyways.
493 card_table->Scan<false>(space->GetMarkBitmap(), space->Begin(), space->End(), visitor);
494 }
495 }
496 // Since all of the objects that may point to other spaces are marked, we can avoid all the read
497 // barriers in the immune spaces.
498 updated_all_immune_objects_.StoreRelaxed(true);
499}
500
Mathieu Chartiera4f6af92015-08-11 17:35:25 -0700501void ConcurrentCopying::SwapStacks() {
502 heap_->SwapStacks();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800503}
504
505void ConcurrentCopying::RecordLiveStackFreezeSize(Thread* self) {
506 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
507 live_stack_freeze_size_ = heap_->GetLiveStack()->Size();
508}
509
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800510class EmptyCheckpoint : public Closure {
511 public:
512 explicit EmptyCheckpoint(ConcurrentCopying* concurrent_copying)
513 : concurrent_copying_(concurrent_copying) {
514 }
515
516 virtual void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
517 // Note: self is not necessarily equal to thread since thread may be suspended.
518 Thread* self = Thread::Current();
519 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
520 << thread->GetState() << " thread " << thread << " self " << self;
Lei Lidd9943d2015-02-02 14:24:44 +0800521 // If thread is a running mutator, then act on behalf of the garbage collector.
522 // See the code in ThreadList::RunCheckpoint.
Mathieu Chartier10d25082015-10-28 18:36:09 -0700523 concurrent_copying_->GetBarrier().Pass(self);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800524 }
525
526 private:
527 ConcurrentCopying* const concurrent_copying_;
528};
529
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700530// Used to visit objects in the immune spaces.
531inline void ConcurrentCopying::ScanImmuneObject(mirror::Object* obj) {
532 DCHECK(obj != nullptr);
533 DCHECK(immune_spaces_.ContainsObject(obj));
534 // Update the fields without graying it or pushing it onto the mark stack.
535 Scan(obj);
536}
537
538class ConcurrentCopying::ImmuneSpaceScanObjVisitor {
539 public:
540 explicit ImmuneSpaceScanObjVisitor(ConcurrentCopying* cc)
541 : collector_(cc) {}
542
Hiroshi Yamauchi5408f232016-07-29 15:07:05 -0700543 ALWAYS_INLINE void operator()(mirror::Object* obj) const SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700544 if (kUseBakerReadBarrier && kGrayDirtyImmuneObjects) {
545 if (obj->GetReadBarrierPointer() == ReadBarrier::GrayPtr()) {
546 collector_->ScanImmuneObject(obj);
547 // Done scanning the object, go back to white.
548 bool success = obj->AtomicSetReadBarrierPointer(ReadBarrier::GrayPtr(),
549 ReadBarrier::WhitePtr());
550 CHECK(success);
551 }
552 } else {
553 collector_->ScanImmuneObject(obj);
554 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700555 }
556
Hiroshi Yamauchi5408f232016-07-29 15:07:05 -0700557 static void Callback(mirror::Object* obj, void* arg) SHARED_REQUIRES(Locks::mutator_lock_) {
558 reinterpret_cast<ImmuneSpaceScanObjVisitor*>(arg)->operator()(obj);
559 }
560
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700561 private:
562 ConcurrentCopying* const collector_;
563};
564
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800565// Concurrently mark roots that are guarded by read barriers and process the mark stack.
566void ConcurrentCopying::MarkingPhase() {
567 TimingLogger::ScopedTiming split("MarkingPhase", GetTimings());
568 if (kVerboseMode) {
569 LOG(INFO) << "GC MarkingPhase";
570 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700571 CHECK(weak_ref_access_enabled_);
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700572
573 // Scan immune spaces.
574 // Update all the fields in the immune spaces first without graying the objects so that we
575 // minimize dirty pages in the immune spaces. Note mutators can concurrently access and gray some
576 // of the objects.
577 if (kUseBakerReadBarrier) {
578 gc_grays_immune_objects_ = false;
Hiroshi Yamauchi16292fc2016-06-20 20:23:34 -0700579 }
Mathieu Chartier21328a12016-07-22 10:47:45 -0700580 {
581 TimingLogger::ScopedTiming split2("ScanImmuneSpaces", GetTimings());
582 for (auto& space : immune_spaces_.GetSpaces()) {
583 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
584 accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
Hiroshi Yamauchi5408f232016-07-29 15:07:05 -0700585 accounting::ModUnionTable* table = heap_->FindModUnionTableFromSpace(space);
Mathieu Chartier21328a12016-07-22 10:47:45 -0700586 ImmuneSpaceScanObjVisitor visitor(this);
Hiroshi Yamauchi5408f232016-07-29 15:07:05 -0700587 if (kUseBakerReadBarrier && kGrayDirtyImmuneObjects && table != nullptr) {
588 table->VisitObjects(ImmuneSpaceScanObjVisitor::Callback, &visitor);
589 } else {
590 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()),
591 reinterpret_cast<uintptr_t>(space->Limit()),
592 visitor);
593 }
Mathieu Chartier21328a12016-07-22 10:47:45 -0700594 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700595 }
596 if (kUseBakerReadBarrier) {
597 // This release fence makes the field updates in the above loop visible before allowing mutator
598 // getting access to immune objects without graying it first.
599 updated_all_immune_objects_.StoreRelease(true);
600 // Now whiten immune objects concurrently accessed and grayed by mutators. We can't do this in
601 // the above loop because we would incorrectly disable the read barrier by whitening an object
602 // which may point to an unscanned, white object, breaking the to-space invariant.
603 //
604 // Make sure no mutators are in the middle of marking an immune object before whitening immune
605 // objects.
606 IssueEmptyCheckpoint();
607 MutexLock mu(Thread::Current(), immune_gray_stack_lock_);
608 if (kVerboseMode) {
609 LOG(INFO) << "immune gray stack size=" << immune_gray_stack_.size();
610 }
611 for (mirror::Object* obj : immune_gray_stack_) {
612 DCHECK(obj->GetReadBarrierPointer() == ReadBarrier::GrayPtr());
613 bool success = obj->AtomicSetReadBarrierPointer(ReadBarrier::GrayPtr(),
614 ReadBarrier::WhitePtr());
615 DCHECK(success);
616 }
617 immune_gray_stack_.clear();
618 }
619
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800620 {
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -0700621 TimingLogger::ScopedTiming split2("VisitConcurrentRoots", GetTimings());
622 Runtime::Current()->VisitConcurrentRoots(this, kVisitRootFlagAllRoots);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800623 }
624 {
625 // TODO: don't visit the transaction roots if it's not active.
626 TimingLogger::ScopedTiming split5("VisitNonThreadRoots", GetTimings());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700627 Runtime::Current()->VisitNonThreadRoots(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800628 }
629
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800630 Thread* self = Thread::Current();
631 {
Mathieu Chartiera6b1ead2015-10-06 10:32:38 -0700632 TimingLogger::ScopedTiming split7("ProcessMarkStack", GetTimings());
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700633 // We transition through three mark stack modes (thread-local, shared, GC-exclusive). The
634 // primary reasons are the fact that we need to use a checkpoint to process thread-local mark
635 // stacks, but after we disable weak refs accesses, we can't use a checkpoint due to a deadlock
636 // issue because running threads potentially blocking at WaitHoldingLocks, and that once we
637 // reach the point where we process weak references, we can avoid using a lock when accessing
638 // the GC mark stack, which makes mark stack processing more efficient.
639
640 // Process the mark stack once in the thread local stack mode. This marks most of the live
641 // objects, aside from weak ref accesses with read barriers (Reference::GetReferent() and system
642 // weaks) that may happen concurrently while we processing the mark stack and newly mark/gray
643 // objects and push refs on the mark stack.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800644 ProcessMarkStack();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700645 // Switch to the shared mark stack mode. That is, revoke and process thread-local mark stacks
646 // for the last time before transitioning to the shared mark stack mode, which would process new
647 // refs that may have been concurrently pushed onto the mark stack during the ProcessMarkStack()
648 // call above. At the same time, disable weak ref accesses using a per-thread flag. It's
649 // important to do these together in a single checkpoint so that we can ensure that mutators
650 // won't newly gray objects and push new refs onto the mark stack due to weak ref accesses and
651 // mutators safely transition to the shared mark stack mode (without leaving unprocessed refs on
652 // the thread-local mark stacks), without a race. This is why we use a thread-local weak ref
653 // access flag Thread::tls32_.weak_ref_access_enabled_ instead of the global ones.
654 SwitchToSharedMarkStackMode();
655 CHECK(!self->GetWeakRefAccessEnabled());
656 // Now that weak refs accesses are disabled, once we exhaust the shared mark stack again here
657 // (which may be non-empty if there were refs found on thread-local mark stacks during the above
658 // SwitchToSharedMarkStackMode() call), we won't have new refs to process, that is, mutators
659 // (via read barriers) have no way to produce any more refs to process. Marking converges once
660 // before we process weak refs below.
661 ProcessMarkStack();
662 CheckEmptyMarkStack();
663 // Switch to the GC exclusive mark stack mode so that we can process the mark stack without a
664 // lock from this point on.
665 SwitchToGcExclusiveMarkStackMode();
666 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800667 if (kVerboseMode) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800668 LOG(INFO) << "ProcessReferences";
669 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700670 // Process weak references. This may produce new refs to process and have them processed via
Mathieu Chartier97509952015-07-13 14:35:43 -0700671 // ProcessMarkStack (in the GC exclusive mark stack mode).
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700672 ProcessReferences(self);
673 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800674 if (kVerboseMode) {
675 LOG(INFO) << "SweepSystemWeaks";
676 }
677 SweepSystemWeaks(self);
678 if (kVerboseMode) {
679 LOG(INFO) << "SweepSystemWeaks done";
680 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700681 // Process the mark stack here one last time because the above SweepSystemWeaks() call may have
682 // marked some objects (strings alive) as hash_set::Erase() can call the hash function for
683 // arbitrary elements in the weak intern table in InternTable::Table::SweepWeaks().
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800684 ProcessMarkStack();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700685 CheckEmptyMarkStack();
686 // Re-enable weak ref accesses.
687 ReenableWeakRefAccess(self);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -0700688 // Free data for class loaders that we unloaded.
689 Runtime::Current()->GetClassLinker()->CleanupClassLoaders();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700690 // Marking is done. Disable marking.
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700691 DisableMarking();
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800692 if (kUseBakerReadBarrier) {
693 ProcessFalseGrayStack();
694 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700695 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800696 }
697
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700698 CHECK(weak_ref_access_enabled_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800699 if (kVerboseMode) {
700 LOG(INFO) << "GC end of MarkingPhase";
701 }
702}
703
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700704void ConcurrentCopying::ReenableWeakRefAccess(Thread* self) {
705 if (kVerboseMode) {
706 LOG(INFO) << "ReenableWeakRefAccess";
707 }
708 weak_ref_access_enabled_.StoreRelaxed(true); // This is for new threads.
709 QuasiAtomic::ThreadFenceForConstructor();
710 // Iterate all threads (don't need to or can't use a checkpoint) and re-enable weak ref access.
711 {
712 MutexLock mu(self, *Locks::thread_list_lock_);
713 std::list<Thread*> thread_list = Runtime::Current()->GetThreadList()->GetList();
714 for (Thread* thread : thread_list) {
715 thread->SetWeakRefAccessEnabled(true);
716 }
717 }
718 // Unblock blocking threads.
719 GetHeap()->GetReferenceProcessor()->BroadcastForSlowPath(self);
720 Runtime::Current()->BroadcastForNewSystemWeaks();
721}
722
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700723class ConcurrentCopying::DisableMarkingCheckpoint : public Closure {
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700724 public:
725 explicit DisableMarkingCheckpoint(ConcurrentCopying* concurrent_copying)
726 : concurrent_copying_(concurrent_copying) {
727 }
728
729 void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
730 // Note: self is not necessarily equal to thread since thread may be suspended.
731 Thread* self = Thread::Current();
732 DCHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
733 << thread->GetState() << " thread " << thread << " self " << self;
734 // Disable the thread-local is_gc_marking flag.
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -0700735 // Note a thread that has just started right before this checkpoint may have already this flag
736 // set to false, which is ok.
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700737 thread->SetIsGcMarking(false);
738 // If thread is a running mutator, then act on behalf of the garbage collector.
739 // See the code in ThreadList::RunCheckpoint.
Mathieu Chartier10d25082015-10-28 18:36:09 -0700740 concurrent_copying_->GetBarrier().Pass(self);
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700741 }
742
743 private:
744 ConcurrentCopying* const concurrent_copying_;
745};
746
747void ConcurrentCopying::IssueDisableMarkingCheckpoint() {
748 Thread* self = Thread::Current();
749 DisableMarkingCheckpoint check_point(this);
750 ThreadList* thread_list = Runtime::Current()->GetThreadList();
751 gc_barrier_->Init(self, 0);
752 size_t barrier_count = thread_list->RunCheckpoint(&check_point);
753 // If there are no threads to wait which implies that all the checkpoint functions are finished,
754 // then no need to release the mutator lock.
755 if (barrier_count == 0) {
756 return;
757 }
758 // Release locks then wait for all mutator threads to pass the barrier.
759 Locks::mutator_lock_->SharedUnlock(self);
760 {
761 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
762 gc_barrier_->Increment(self, barrier_count);
763 }
764 Locks::mutator_lock_->SharedLock(self);
765}
766
767void ConcurrentCopying::DisableMarking() {
768 // Change the global is_marking flag to false. Do a fence before doing a checkpoint to update the
769 // thread-local flags so that a new thread starting up will get the correct is_marking flag.
770 is_marking_ = false;
771 QuasiAtomic::ThreadFenceForConstructor();
772 // Use a checkpoint to turn off the thread-local is_gc_marking flags and to ensure no threads are
773 // still in the middle of a read barrier which may have a from-space ref cached in a local
774 // variable.
775 IssueDisableMarkingCheckpoint();
776 if (kUseTableLookupReadBarrier) {
777 heap_->rb_table_->ClearAll();
778 DCHECK(heap_->rb_table_->IsAllCleared());
779 }
780 is_mark_stack_push_disallowed_.StoreSequentiallyConsistent(1);
781 mark_stack_mode_.StoreSequentiallyConsistent(kMarkStackModeOff);
782}
783
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800784void ConcurrentCopying::PushOntoFalseGrayStack(mirror::Object* ref) {
785 CHECK(kUseBakerReadBarrier);
786 DCHECK(ref != nullptr);
787 MutexLock mu(Thread::Current(), mark_stack_lock_);
788 false_gray_stack_.push_back(ref);
789}
790
791void ConcurrentCopying::ProcessFalseGrayStack() {
792 CHECK(kUseBakerReadBarrier);
793 // Change the objects on the false gray stack from gray to white.
794 MutexLock mu(Thread::Current(), mark_stack_lock_);
795 for (mirror::Object* obj : false_gray_stack_) {
796 DCHECK(IsMarked(obj));
797 // The object could be white here if a thread got preempted after a success at the
798 // AtomicSetReadBarrierPointer in Mark(), GC started marking through it (but not finished so
799 // still gray), and the thread ran to register it onto the false gray stack.
800 if (obj->GetReadBarrierPointer() == ReadBarrier::GrayPtr()) {
801 bool success = obj->AtomicSetReadBarrierPointer(ReadBarrier::GrayPtr(),
802 ReadBarrier::WhitePtr());
803 DCHECK(success);
804 }
805 }
806 false_gray_stack_.clear();
807}
808
809
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800810void ConcurrentCopying::IssueEmptyCheckpoint() {
811 Thread* self = Thread::Current();
812 EmptyCheckpoint check_point(this);
813 ThreadList* thread_list = Runtime::Current()->GetThreadList();
814 gc_barrier_->Init(self, 0);
815 size_t barrier_count = thread_list->RunCheckpoint(&check_point);
Lei Lidd9943d2015-02-02 14:24:44 +0800816 // If there are no threads to wait which implys that all the checkpoint functions are finished,
817 // then no need to release the mutator lock.
818 if (barrier_count == 0) {
819 return;
820 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800821 // Release locks then wait for all mutator threads to pass the barrier.
822 Locks::mutator_lock_->SharedUnlock(self);
823 {
824 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
825 gc_barrier_->Increment(self, barrier_count);
826 }
827 Locks::mutator_lock_->SharedLock(self);
828}
829
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -0700830void ConcurrentCopying::ExpandGcMarkStack() {
831 DCHECK(gc_mark_stack_->IsFull());
832 const size_t new_size = gc_mark_stack_->Capacity() * 2;
833 std::vector<StackReference<mirror::Object>> temp(gc_mark_stack_->Begin(),
834 gc_mark_stack_->End());
835 gc_mark_stack_->Resize(new_size);
836 for (auto& ref : temp) {
837 gc_mark_stack_->PushBack(ref.AsMirrorPtr());
838 }
839 DCHECK(!gc_mark_stack_->IsFull());
840}
841
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800842void ConcurrentCopying::PushOntoMarkStack(mirror::Object* to_ref) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700843 CHECK_EQ(is_mark_stack_push_disallowed_.LoadRelaxed(), 0)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800844 << " " << to_ref << " " << PrettyTypeOf(to_ref);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700845 Thread* self = Thread::Current(); // TODO: pass self as an argument from call sites?
846 CHECK(thread_running_gc_ != nullptr);
847 MarkStackMode mark_stack_mode = mark_stack_mode_.LoadRelaxed();
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -0700848 if (LIKELY(mark_stack_mode == kMarkStackModeThreadLocal)) {
849 if (LIKELY(self == thread_running_gc_)) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700850 // If GC-running thread, use the GC mark stack instead of a thread-local mark stack.
851 CHECK(self->GetThreadLocalMarkStack() == nullptr);
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -0700852 if (UNLIKELY(gc_mark_stack_->IsFull())) {
853 ExpandGcMarkStack();
854 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700855 gc_mark_stack_->PushBack(to_ref);
856 } else {
857 // Otherwise, use a thread-local mark stack.
858 accounting::AtomicStack<mirror::Object>* tl_mark_stack = self->GetThreadLocalMarkStack();
859 if (UNLIKELY(tl_mark_stack == nullptr || tl_mark_stack->IsFull())) {
860 MutexLock mu(self, mark_stack_lock_);
861 // Get a new thread local mark stack.
862 accounting::AtomicStack<mirror::Object>* new_tl_mark_stack;
863 if (!pooled_mark_stacks_.empty()) {
864 // Use a pooled mark stack.
865 new_tl_mark_stack = pooled_mark_stacks_.back();
866 pooled_mark_stacks_.pop_back();
867 } else {
868 // None pooled. Create a new one.
869 new_tl_mark_stack =
870 accounting::AtomicStack<mirror::Object>::Create(
871 "thread local mark stack", 4 * KB, 4 * KB);
872 }
873 DCHECK(new_tl_mark_stack != nullptr);
874 DCHECK(new_tl_mark_stack->IsEmpty());
875 new_tl_mark_stack->PushBack(to_ref);
876 self->SetThreadLocalMarkStack(new_tl_mark_stack);
877 if (tl_mark_stack != nullptr) {
878 // Store the old full stack into a vector.
879 revoked_mark_stacks_.push_back(tl_mark_stack);
880 }
881 } else {
882 tl_mark_stack->PushBack(to_ref);
883 }
884 }
885 } else if (mark_stack_mode == kMarkStackModeShared) {
886 // Access the shared GC mark stack with a lock.
887 MutexLock mu(self, mark_stack_lock_);
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -0700888 if (UNLIKELY(gc_mark_stack_->IsFull())) {
889 ExpandGcMarkStack();
890 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700891 gc_mark_stack_->PushBack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800892 } else {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700893 CHECK_EQ(static_cast<uint32_t>(mark_stack_mode),
Hiroshi Yamauchifa755182015-09-30 20:12:11 -0700894 static_cast<uint32_t>(kMarkStackModeGcExclusive))
895 << "ref=" << to_ref
896 << " self->gc_marking=" << self->GetIsGcMarking()
897 << " cc->is_marking=" << is_marking_;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700898 CHECK(self == thread_running_gc_)
899 << "Only GC-running thread should access the mark stack "
900 << "in the GC exclusive mark stack mode";
901 // Access the GC mark stack without a lock.
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -0700902 if (UNLIKELY(gc_mark_stack_->IsFull())) {
903 ExpandGcMarkStack();
904 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700905 gc_mark_stack_->PushBack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800906 }
907}
908
909accounting::ObjectStack* ConcurrentCopying::GetAllocationStack() {
910 return heap_->allocation_stack_.get();
911}
912
913accounting::ObjectStack* ConcurrentCopying::GetLiveStack() {
914 return heap_->live_stack_.get();
915}
916
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800917// The following visitors are used to verify that there's no references to the from-space left after
918// marking.
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700919class ConcurrentCopying::VerifyNoFromSpaceRefsVisitor : public SingleRootVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800920 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700921 explicit VerifyNoFromSpaceRefsVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800922 : collector_(collector) {}
923
924 void operator()(mirror::Object* ref) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700925 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800926 if (ref == nullptr) {
927 // OK.
928 return;
929 }
930 collector_->AssertToSpaceInvariant(nullptr, MemberOffset(0), ref);
931 if (kUseBakerReadBarrier) {
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700932 CHECK_EQ(ref->GetReadBarrierPointer(), ReadBarrier::WhitePtr())
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800933 << "Ref " << ref << " " << PrettyTypeOf(ref)
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700934 << " has non-white rb_ptr ";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800935 }
936 }
937
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700938 void VisitRoot(mirror::Object* root, const RootInfo& info ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -0700939 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800940 DCHECK(root != nullptr);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700941 operator()(root);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800942 }
943
944 private:
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700945 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800946};
947
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700948class ConcurrentCopying::VerifyNoFromSpaceRefsFieldVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800949 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700950 explicit VerifyNoFromSpaceRefsFieldVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800951 : collector_(collector) {}
952
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700953 void operator()(mirror::Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700954 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800955 mirror::Object* ref =
956 obj->GetFieldObject<mirror::Object, kDefaultVerifyFlags, kWithoutReadBarrier>(offset);
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700957 VerifyNoFromSpaceRefsVisitor visitor(collector_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800958 visitor(ref);
959 }
960 void operator()(mirror::Class* klass, mirror::Reference* ref) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700961 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800962 CHECK(klass->IsTypeOfReferenceClass());
963 this->operator()(ref, mirror::Reference::ReferentOffset(), false);
964 }
965
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700966 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
967 SHARED_REQUIRES(Locks::mutator_lock_) {
968 if (!root->IsNull()) {
969 VisitRoot(root);
970 }
971 }
972
973 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
974 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700975 VerifyNoFromSpaceRefsVisitor visitor(collector_);
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700976 visitor(root->AsMirrorPtr());
977 }
978
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800979 private:
Mathieu Chartier97509952015-07-13 14:35:43 -0700980 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800981};
982
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700983class ConcurrentCopying::VerifyNoFromSpaceRefsObjectVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800984 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700985 explicit VerifyNoFromSpaceRefsObjectVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800986 : collector_(collector) {}
987 void operator()(mirror::Object* obj) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700988 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800989 ObjectCallback(obj, collector_);
990 }
991 static void ObjectCallback(mirror::Object* obj, void *arg)
Mathieu Chartier90443472015-07-16 20:32:27 -0700992 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800993 CHECK(obj != nullptr);
994 ConcurrentCopying* collector = reinterpret_cast<ConcurrentCopying*>(arg);
995 space::RegionSpace* region_space = collector->RegionSpace();
996 CHECK(!region_space->IsInFromSpace(obj)) << "Scanning object " << obj << " in from space";
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700997 VerifyNoFromSpaceRefsFieldVisitor visitor(collector);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -0700998 obj->VisitReferences(visitor, visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800999 if (kUseBakerReadBarrier) {
Mathieu Chartier36a270a2016-07-28 18:08:51 -07001000 CHECK_EQ(obj->GetReadBarrierPointer(), ReadBarrier::WhitePtr())
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001001 << "obj=" << obj << " non-white rb_ptr " << obj->GetReadBarrierPointer();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001002 }
1003 }
1004
1005 private:
1006 ConcurrentCopying* const collector_;
1007};
1008
1009// Verify there's no from-space references left after the marking phase.
1010void ConcurrentCopying::VerifyNoFromSpaceReferences() {
1011 Thread* self = Thread::Current();
1012 DCHECK(Locks::mutator_lock_->IsExclusiveHeld(self));
Hiroshi Yamauchi00370822015-08-18 14:47:25 -07001013 // Verify all threads have is_gc_marking to be false
1014 {
1015 MutexLock mu(self, *Locks::thread_list_lock_);
1016 std::list<Thread*> thread_list = Runtime::Current()->GetThreadList()->GetList();
1017 for (Thread* thread : thread_list) {
1018 CHECK(!thread->GetIsGcMarking());
1019 }
1020 }
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001021 VerifyNoFromSpaceRefsObjectVisitor visitor(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001022 // Roots.
1023 {
1024 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001025 VerifyNoFromSpaceRefsVisitor ref_visitor(this);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001026 Runtime::Current()->VisitRoots(&ref_visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001027 }
1028 // The to-space.
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001029 region_space_->WalkToSpace(VerifyNoFromSpaceRefsObjectVisitor::ObjectCallback, this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001030 // Non-moving spaces.
1031 {
1032 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1033 heap_->GetMarkBitmap()->Visit(visitor);
1034 }
1035 // The alloc stack.
1036 {
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001037 VerifyNoFromSpaceRefsVisitor ref_visitor(this);
Mathieu Chartiercb535da2015-01-23 13:50:03 -08001038 for (auto* it = heap_->allocation_stack_->Begin(), *end = heap_->allocation_stack_->End();
1039 it < end; ++it) {
1040 mirror::Object* const obj = it->AsMirrorPtr();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001041 if (obj != nullptr && obj->GetClass() != nullptr) {
1042 // TODO: need to call this only if obj is alive?
1043 ref_visitor(obj);
1044 visitor(obj);
1045 }
1046 }
1047 }
1048 // TODO: LOS. But only refs in LOS are classes.
1049}
1050
1051// The following visitors are used to assert the to-space invariant.
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001052class ConcurrentCopying::AssertToSpaceInvariantRefsVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001053 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001054 explicit AssertToSpaceInvariantRefsVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001055 : collector_(collector) {}
1056
1057 void operator()(mirror::Object* ref) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001058 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001059 if (ref == nullptr) {
1060 // OK.
1061 return;
1062 }
1063 collector_->AssertToSpaceInvariant(nullptr, MemberOffset(0), ref);
1064 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001065
1066 private:
Mathieu Chartier97509952015-07-13 14:35:43 -07001067 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001068};
1069
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001070class ConcurrentCopying::AssertToSpaceInvariantFieldVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001071 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001072 explicit AssertToSpaceInvariantFieldVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001073 : collector_(collector) {}
1074
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001075 void operator()(mirror::Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001076 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001077 mirror::Object* ref =
1078 obj->GetFieldObject<mirror::Object, kDefaultVerifyFlags, kWithoutReadBarrier>(offset);
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001079 AssertToSpaceInvariantRefsVisitor visitor(collector_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001080 visitor(ref);
1081 }
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001082 void operator()(mirror::Class* klass, mirror::Reference* ref ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001083 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001084 CHECK(klass->IsTypeOfReferenceClass());
1085 }
1086
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001087 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
1088 SHARED_REQUIRES(Locks::mutator_lock_) {
1089 if (!root->IsNull()) {
1090 VisitRoot(root);
1091 }
1092 }
1093
1094 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
1095 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001096 AssertToSpaceInvariantRefsVisitor visitor(collector_);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001097 visitor(root->AsMirrorPtr());
1098 }
1099
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001100 private:
Mathieu Chartier97509952015-07-13 14:35:43 -07001101 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001102};
1103
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001104class ConcurrentCopying::AssertToSpaceInvariantObjectVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001105 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001106 explicit AssertToSpaceInvariantObjectVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001107 : collector_(collector) {}
1108 void operator()(mirror::Object* obj) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001109 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001110 ObjectCallback(obj, collector_);
1111 }
1112 static void ObjectCallback(mirror::Object* obj, void *arg)
Mathieu Chartier90443472015-07-16 20:32:27 -07001113 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001114 CHECK(obj != nullptr);
1115 ConcurrentCopying* collector = reinterpret_cast<ConcurrentCopying*>(arg);
1116 space::RegionSpace* region_space = collector->RegionSpace();
1117 CHECK(!region_space->IsInFromSpace(obj)) << "Scanning object " << obj << " in from space";
1118 collector->AssertToSpaceInvariant(nullptr, MemberOffset(0), obj);
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001119 AssertToSpaceInvariantFieldVisitor visitor(collector);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07001120 obj->VisitReferences(visitor, visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001121 }
1122
1123 private:
Mathieu Chartier97509952015-07-13 14:35:43 -07001124 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001125};
1126
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001127class ConcurrentCopying::RevokeThreadLocalMarkStackCheckpoint : public Closure {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001128 public:
Roland Levillain3887c462015-08-12 18:15:42 +01001129 RevokeThreadLocalMarkStackCheckpoint(ConcurrentCopying* concurrent_copying,
1130 bool disable_weak_ref_access)
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001131 : concurrent_copying_(concurrent_copying),
1132 disable_weak_ref_access_(disable_weak_ref_access) {
1133 }
1134
1135 virtual void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
1136 // Note: self is not necessarily equal to thread since thread may be suspended.
1137 Thread* self = Thread::Current();
1138 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
1139 << thread->GetState() << " thread " << thread << " self " << self;
1140 // Revoke thread local mark stacks.
1141 accounting::AtomicStack<mirror::Object>* tl_mark_stack = thread->GetThreadLocalMarkStack();
1142 if (tl_mark_stack != nullptr) {
1143 MutexLock mu(self, concurrent_copying_->mark_stack_lock_);
1144 concurrent_copying_->revoked_mark_stacks_.push_back(tl_mark_stack);
1145 thread->SetThreadLocalMarkStack(nullptr);
1146 }
1147 // Disable weak ref access.
1148 if (disable_weak_ref_access_) {
1149 thread->SetWeakRefAccessEnabled(false);
1150 }
1151 // If thread is a running mutator, then act on behalf of the garbage collector.
1152 // See the code in ThreadList::RunCheckpoint.
Mathieu Chartier10d25082015-10-28 18:36:09 -07001153 concurrent_copying_->GetBarrier().Pass(self);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001154 }
1155
1156 private:
1157 ConcurrentCopying* const concurrent_copying_;
1158 const bool disable_weak_ref_access_;
1159};
1160
1161void ConcurrentCopying::RevokeThreadLocalMarkStacks(bool disable_weak_ref_access) {
1162 Thread* self = Thread::Current();
1163 RevokeThreadLocalMarkStackCheckpoint check_point(this, disable_weak_ref_access);
1164 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1165 gc_barrier_->Init(self, 0);
1166 size_t barrier_count = thread_list->RunCheckpoint(&check_point);
1167 // If there are no threads to wait which implys that all the checkpoint functions are finished,
1168 // then no need to release the mutator lock.
1169 if (barrier_count == 0) {
1170 return;
1171 }
1172 Locks::mutator_lock_->SharedUnlock(self);
1173 {
1174 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
1175 gc_barrier_->Increment(self, barrier_count);
1176 }
1177 Locks::mutator_lock_->SharedLock(self);
1178}
1179
1180void ConcurrentCopying::RevokeThreadLocalMarkStack(Thread* thread) {
1181 Thread* self = Thread::Current();
1182 CHECK_EQ(self, thread);
1183 accounting::AtomicStack<mirror::Object>* tl_mark_stack = thread->GetThreadLocalMarkStack();
1184 if (tl_mark_stack != nullptr) {
1185 CHECK(is_marking_);
1186 MutexLock mu(self, mark_stack_lock_);
1187 revoked_mark_stacks_.push_back(tl_mark_stack);
1188 thread->SetThreadLocalMarkStack(nullptr);
1189 }
1190}
1191
1192void ConcurrentCopying::ProcessMarkStack() {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001193 if (kVerboseMode) {
1194 LOG(INFO) << "ProcessMarkStack. ";
1195 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001196 bool empty_prev = false;
1197 while (true) {
1198 bool empty = ProcessMarkStackOnce();
1199 if (empty_prev && empty) {
1200 // Saw empty mark stack for a second time, done.
1201 break;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001202 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001203 empty_prev = empty;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001204 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001205}
1206
1207bool ConcurrentCopying::ProcessMarkStackOnce() {
1208 Thread* self = Thread::Current();
1209 CHECK(thread_running_gc_ != nullptr);
1210 CHECK(self == thread_running_gc_);
1211 CHECK(self->GetThreadLocalMarkStack() == nullptr);
1212 size_t count = 0;
1213 MarkStackMode mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1214 if (mark_stack_mode == kMarkStackModeThreadLocal) {
1215 // Process the thread-local mark stacks and the GC mark stack.
1216 count += ProcessThreadLocalMarkStacks(false);
1217 while (!gc_mark_stack_->IsEmpty()) {
1218 mirror::Object* to_ref = gc_mark_stack_->PopBack();
1219 ProcessMarkStackRef(to_ref);
1220 ++count;
1221 }
1222 gc_mark_stack_->Reset();
1223 } else if (mark_stack_mode == kMarkStackModeShared) {
1224 // Process the shared GC mark stack with a lock.
1225 {
1226 MutexLock mu(self, mark_stack_lock_);
1227 CHECK(revoked_mark_stacks_.empty());
1228 }
1229 while (true) {
1230 std::vector<mirror::Object*> refs;
1231 {
1232 // Copy refs with lock. Note the number of refs should be small.
1233 MutexLock mu(self, mark_stack_lock_);
1234 if (gc_mark_stack_->IsEmpty()) {
1235 break;
1236 }
1237 for (StackReference<mirror::Object>* p = gc_mark_stack_->Begin();
1238 p != gc_mark_stack_->End(); ++p) {
1239 refs.push_back(p->AsMirrorPtr());
1240 }
1241 gc_mark_stack_->Reset();
1242 }
1243 for (mirror::Object* ref : refs) {
1244 ProcessMarkStackRef(ref);
1245 ++count;
1246 }
1247 }
1248 } else {
1249 CHECK_EQ(static_cast<uint32_t>(mark_stack_mode),
1250 static_cast<uint32_t>(kMarkStackModeGcExclusive));
1251 {
1252 MutexLock mu(self, mark_stack_lock_);
1253 CHECK(revoked_mark_stacks_.empty());
1254 }
1255 // Process the GC mark stack in the exclusive mode. No need to take the lock.
1256 while (!gc_mark_stack_->IsEmpty()) {
1257 mirror::Object* to_ref = gc_mark_stack_->PopBack();
1258 ProcessMarkStackRef(to_ref);
1259 ++count;
1260 }
1261 gc_mark_stack_->Reset();
1262 }
1263
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001264 // Return true if the stack was empty.
1265 return count == 0;
1266}
1267
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001268size_t ConcurrentCopying::ProcessThreadLocalMarkStacks(bool disable_weak_ref_access) {
1269 // Run a checkpoint to collect all thread local mark stacks and iterate over them all.
1270 RevokeThreadLocalMarkStacks(disable_weak_ref_access);
1271 size_t count = 0;
1272 std::vector<accounting::AtomicStack<mirror::Object>*> mark_stacks;
1273 {
1274 MutexLock mu(Thread::Current(), mark_stack_lock_);
1275 // Make a copy of the mark stack vector.
1276 mark_stacks = revoked_mark_stacks_;
1277 revoked_mark_stacks_.clear();
1278 }
1279 for (accounting::AtomicStack<mirror::Object>* mark_stack : mark_stacks) {
1280 for (StackReference<mirror::Object>* p = mark_stack->Begin(); p != mark_stack->End(); ++p) {
1281 mirror::Object* to_ref = p->AsMirrorPtr();
1282 ProcessMarkStackRef(to_ref);
1283 ++count;
1284 }
1285 {
1286 MutexLock mu(Thread::Current(), mark_stack_lock_);
1287 if (pooled_mark_stacks_.size() >= kMarkStackPoolSize) {
1288 // The pool has enough. Delete it.
1289 delete mark_stack;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001290 } else {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001291 // Otherwise, put it into the pool for later reuse.
1292 mark_stack->Reset();
1293 pooled_mark_stacks_.push_back(mark_stack);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001294 }
1295 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001296 }
1297 return count;
1298}
1299
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001300inline void ConcurrentCopying::ProcessMarkStackRef(mirror::Object* to_ref) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001301 DCHECK(!region_space_->IsInFromSpace(to_ref));
1302 if (kUseBakerReadBarrier) {
1303 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr())
1304 << " " << to_ref << " " << to_ref->GetReadBarrierPointer()
1305 << " is_marked=" << IsMarked(to_ref);
1306 }
1307 // Scan ref fields.
1308 Scan(to_ref);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001309 if (kUseBakerReadBarrier) {
1310 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr())
1311 << " " << to_ref << " " << to_ref->GetReadBarrierPointer()
1312 << " is_marked=" << IsMarked(to_ref);
1313 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001314#ifdef USE_BAKER_OR_BROOKS_READ_BARRIER
1315 if (UNLIKELY((to_ref->GetClass<kVerifyNone, kWithoutReadBarrier>()->IsTypeOfReferenceClass() &&
1316 to_ref->AsReference()->GetReferent<kWithoutReadBarrier>() != nullptr &&
1317 !IsInToSpace(to_ref->AsReference()->GetReferent<kWithoutReadBarrier>())))) {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001318 // Leave this reference gray in the queue so that GetReferent() will trigger a read barrier. We
1319 // will change it to white later in ReferenceQueue::DequeuePendingReference().
Richard Uhlere3627402016-02-02 13:36:55 -08001320 DCHECK(to_ref->AsReference()->GetPendingNext() != nullptr) << "Left unenqueued ref gray " << to_ref;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001321 } else {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001322 // We may occasionally leave a reference white in the queue if its referent happens to be
1323 // concurrently marked after the Scan() call above has enqueued the Reference, in which case the
1324 // above IsInToSpace() evaluates to true and we change the color from gray to white here in this
1325 // else block.
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001326 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001327 bool success = to_ref->AtomicSetReadBarrierPointer</*kCasRelease*/true>(
1328 ReadBarrier::GrayPtr(),
1329 ReadBarrier::WhitePtr());
1330 DCHECK(success) << "Must succeed as we won the race.";
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001331 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001332 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001333#else
1334 DCHECK(!kUseBakerReadBarrier);
1335#endif
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001336
1337 if (region_space_->IsInUnevacFromSpace(to_ref)) {
1338 // Add to the live bytes per unevacuated from space. Note this code is always run by the
1339 // GC-running thread (no synchronization required).
1340 DCHECK(region_space_bitmap_->Test(to_ref));
1341 // Disable the read barrier in SizeOf for performance, which is safe.
1342 size_t obj_size = to_ref->SizeOf<kDefaultVerifyFlags, kWithoutReadBarrier>();
1343 size_t alloc_size = RoundUp(obj_size, space::RegionSpace::kAlignment);
1344 region_space_->AddLiveBytes(to_ref, alloc_size);
1345 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001346 if (ReadBarrier::kEnableToSpaceInvariantChecks || kIsDebugBuild) {
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001347 AssertToSpaceInvariantObjectVisitor visitor(this);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001348 visitor(to_ref);
1349 }
1350}
1351
1352void ConcurrentCopying::SwitchToSharedMarkStackMode() {
1353 Thread* self = Thread::Current();
1354 CHECK(thread_running_gc_ != nullptr);
1355 CHECK_EQ(self, thread_running_gc_);
1356 CHECK(self->GetThreadLocalMarkStack() == nullptr);
1357 MarkStackMode before_mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1358 CHECK_EQ(static_cast<uint32_t>(before_mark_stack_mode),
1359 static_cast<uint32_t>(kMarkStackModeThreadLocal));
1360 mark_stack_mode_.StoreRelaxed(kMarkStackModeShared);
1361 CHECK(weak_ref_access_enabled_.LoadRelaxed());
1362 weak_ref_access_enabled_.StoreRelaxed(false);
1363 QuasiAtomic::ThreadFenceForConstructor();
1364 // Process the thread local mark stacks one last time after switching to the shared mark stack
1365 // mode and disable weak ref accesses.
1366 ProcessThreadLocalMarkStacks(true);
1367 if (kVerboseMode) {
1368 LOG(INFO) << "Switched to shared mark stack mode and disabled weak ref access";
1369 }
1370}
1371
1372void ConcurrentCopying::SwitchToGcExclusiveMarkStackMode() {
1373 Thread* self = Thread::Current();
1374 CHECK(thread_running_gc_ != nullptr);
1375 CHECK_EQ(self, thread_running_gc_);
1376 CHECK(self->GetThreadLocalMarkStack() == nullptr);
1377 MarkStackMode before_mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1378 CHECK_EQ(static_cast<uint32_t>(before_mark_stack_mode),
1379 static_cast<uint32_t>(kMarkStackModeShared));
1380 mark_stack_mode_.StoreRelaxed(kMarkStackModeGcExclusive);
1381 QuasiAtomic::ThreadFenceForConstructor();
1382 if (kVerboseMode) {
1383 LOG(INFO) << "Switched to GC exclusive mark stack mode";
1384 }
1385}
1386
1387void ConcurrentCopying::CheckEmptyMarkStack() {
1388 Thread* self = Thread::Current();
1389 CHECK(thread_running_gc_ != nullptr);
1390 CHECK_EQ(self, thread_running_gc_);
1391 CHECK(self->GetThreadLocalMarkStack() == nullptr);
1392 MarkStackMode mark_stack_mode = mark_stack_mode_.LoadRelaxed();
1393 if (mark_stack_mode == kMarkStackModeThreadLocal) {
1394 // Thread-local mark stack mode.
1395 RevokeThreadLocalMarkStacks(false);
1396 MutexLock mu(Thread::Current(), mark_stack_lock_);
1397 if (!revoked_mark_stacks_.empty()) {
1398 for (accounting::AtomicStack<mirror::Object>* mark_stack : revoked_mark_stacks_) {
1399 while (!mark_stack->IsEmpty()) {
1400 mirror::Object* obj = mark_stack->PopBack();
1401 if (kUseBakerReadBarrier) {
1402 mirror::Object* rb_ptr = obj->GetReadBarrierPointer();
1403 LOG(INFO) << "On mark queue : " << obj << " " << PrettyTypeOf(obj) << " rb_ptr=" << rb_ptr
1404 << " is_marked=" << IsMarked(obj);
1405 } else {
1406 LOG(INFO) << "On mark queue : " << obj << " " << PrettyTypeOf(obj)
1407 << " is_marked=" << IsMarked(obj);
1408 }
1409 }
1410 }
1411 LOG(FATAL) << "mark stack is not empty";
1412 }
1413 } else {
1414 // Shared, GC-exclusive, or off.
1415 MutexLock mu(Thread::Current(), mark_stack_lock_);
1416 CHECK(gc_mark_stack_->IsEmpty());
1417 CHECK(revoked_mark_stacks_.empty());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001418 }
1419}
1420
1421void ConcurrentCopying::SweepSystemWeaks(Thread* self) {
1422 TimingLogger::ScopedTiming split("SweepSystemWeaks", GetTimings());
1423 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier97509952015-07-13 14:35:43 -07001424 Runtime::Current()->SweepSystemWeaks(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001425}
1426
1427void ConcurrentCopying::Sweep(bool swap_bitmaps) {
1428 {
1429 TimingLogger::ScopedTiming t("MarkStackAsLive", GetTimings());
1430 accounting::ObjectStack* live_stack = heap_->GetLiveStack();
1431 if (kEnableFromSpaceAccountingCheck) {
1432 CHECK_GE(live_stack_freeze_size_, live_stack->Size());
1433 }
1434 heap_->MarkAllocStackAsLive(live_stack);
1435 live_stack->Reset();
1436 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001437 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001438 TimingLogger::ScopedTiming split("Sweep", GetTimings());
1439 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
1440 if (space->IsContinuousMemMapAllocSpace()) {
1441 space::ContinuousMemMapAllocSpace* alloc_space = space->AsContinuousMemMapAllocSpace();
Mathieu Chartier763a31e2015-11-16 16:05:55 -08001442 if (space == region_space_ || immune_spaces_.ContainsSpace(space)) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001443 continue;
1444 }
1445 TimingLogger::ScopedTiming split2(
1446 alloc_space->IsZygoteSpace() ? "SweepZygoteSpace" : "SweepAllocSpace", GetTimings());
1447 RecordFree(alloc_space->Sweep(swap_bitmaps));
1448 }
1449 }
1450 SweepLargeObjects(swap_bitmaps);
1451}
1452
Mathieu Chartier962cd7a2016-08-16 12:15:59 -07001453void ConcurrentCopying::MarkZygoteLargeObjects() {
1454 TimingLogger::ScopedTiming split(__FUNCTION__, GetTimings());
1455 Thread* const self = Thread::Current();
1456 WriterMutexLock rmu(self, *Locks::heap_bitmap_lock_);
1457 space::LargeObjectSpace* const los = heap_->GetLargeObjectsSpace();
1458 // Pick the current live bitmap (mark bitmap if swapped).
1459 accounting::LargeObjectBitmap* const live_bitmap = los->GetLiveBitmap();
1460 accounting::LargeObjectBitmap* const mark_bitmap = los->GetMarkBitmap();
1461 // Walk through all of the objects and explicitly mark the zygote ones so they don't get swept.
1462 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(los->Begin()),
1463 reinterpret_cast<uintptr_t>(los->End()),
1464 [mark_bitmap, los, self](mirror::Object* obj)
1465 REQUIRES(Locks::heap_bitmap_lock_)
1466 SHARED_REQUIRES(Locks::mutator_lock_) {
1467 if (los->IsZygoteLargeObject(self, obj)) {
1468 mark_bitmap->Set(obj);
1469 }
1470 });
1471}
1472
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001473void ConcurrentCopying::SweepLargeObjects(bool swap_bitmaps) {
1474 TimingLogger::ScopedTiming split("SweepLargeObjects", GetTimings());
1475 RecordFreeLOS(heap_->GetLargeObjectsSpace()->Sweep(swap_bitmaps));
1476}
1477
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001478void ConcurrentCopying::ReclaimPhase() {
1479 TimingLogger::ScopedTiming split("ReclaimPhase", GetTimings());
1480 if (kVerboseMode) {
1481 LOG(INFO) << "GC ReclaimPhase";
1482 }
1483 Thread* self = Thread::Current();
1484
1485 {
1486 // Double-check that the mark stack is empty.
1487 // Note: need to set this after VerifyNoFromSpaceRef().
1488 is_asserting_to_space_invariant_ = false;
1489 QuasiAtomic::ThreadFenceForConstructor();
1490 if (kVerboseMode) {
1491 LOG(INFO) << "Issue an empty check point. ";
1492 }
1493 IssueEmptyCheckpoint();
1494 // Disable the check.
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001495 is_mark_stack_push_disallowed_.StoreSequentiallyConsistent(0);
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001496 if (kUseBakerReadBarrier) {
1497 updated_all_immune_objects_.StoreSequentiallyConsistent(false);
1498 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001499 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001500 }
1501
1502 {
1503 // Record freed objects.
1504 TimingLogger::ScopedTiming split2("RecordFree", GetTimings());
1505 // Don't include thread-locals that are in the to-space.
1506 uint64_t from_bytes = region_space_->GetBytesAllocatedInFromSpace();
1507 uint64_t from_objects = region_space_->GetObjectsAllocatedInFromSpace();
1508 uint64_t unevac_from_bytes = region_space_->GetBytesAllocatedInUnevacFromSpace();
1509 uint64_t unevac_from_objects = region_space_->GetObjectsAllocatedInUnevacFromSpace();
1510 uint64_t to_bytes = bytes_moved_.LoadSequentiallyConsistent();
Mathieu Chartiercca44a02016-08-17 10:07:29 -07001511 cumulative_bytes_moved_.FetchAndAddRelaxed(to_bytes);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001512 uint64_t to_objects = objects_moved_.LoadSequentiallyConsistent();
Mathieu Chartiercca44a02016-08-17 10:07:29 -07001513 cumulative_objects_moved_.FetchAndAddRelaxed(to_objects);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001514 if (kEnableFromSpaceAccountingCheck) {
1515 CHECK_EQ(from_space_num_objects_at_first_pause_, from_objects + unevac_from_objects);
1516 CHECK_EQ(from_space_num_bytes_at_first_pause_, from_bytes + unevac_from_bytes);
1517 }
1518 CHECK_LE(to_objects, from_objects);
1519 CHECK_LE(to_bytes, from_bytes);
1520 int64_t freed_bytes = from_bytes - to_bytes;
1521 int64_t freed_objects = from_objects - to_objects;
1522 if (kVerboseMode) {
1523 LOG(INFO) << "RecordFree:"
1524 << " from_bytes=" << from_bytes << " from_objects=" << from_objects
1525 << " unevac_from_bytes=" << unevac_from_bytes << " unevac_from_objects=" << unevac_from_objects
1526 << " to_bytes=" << to_bytes << " to_objects=" << to_objects
1527 << " freed_bytes=" << freed_bytes << " freed_objects=" << freed_objects
1528 << " from_space size=" << region_space_->FromSpaceSize()
1529 << " unevac_from_space size=" << region_space_->UnevacFromSpaceSize()
1530 << " to_space size=" << region_space_->ToSpaceSize();
1531 LOG(INFO) << "(before) num_bytes_allocated=" << heap_->num_bytes_allocated_.LoadSequentiallyConsistent();
1532 }
1533 RecordFree(ObjectBytePair(freed_objects, freed_bytes));
1534 if (kVerboseMode) {
1535 LOG(INFO) << "(after) num_bytes_allocated=" << heap_->num_bytes_allocated_.LoadSequentiallyConsistent();
1536 }
1537 }
1538
1539 {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001540 TimingLogger::ScopedTiming split4("ClearFromSpace", GetTimings());
1541 region_space_->ClearFromSpace();
1542 }
1543
1544 {
1545 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001546 Sweep(false);
1547 SwapBitmaps();
1548 heap_->UnBindBitmaps();
1549
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001550 // Delete the region bitmap.
1551 DCHECK(region_space_bitmap_ != nullptr);
1552 delete region_space_bitmap_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001553 region_space_bitmap_ = nullptr;
1554 }
1555
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001556 CheckEmptyMarkStack();
1557
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001558 if (kVerboseMode) {
1559 LOG(INFO) << "GC end of ReclaimPhase";
1560 }
1561}
1562
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001563// Assert the to-space invariant.
1564void ConcurrentCopying::AssertToSpaceInvariant(mirror::Object* obj, MemberOffset offset,
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 (obj != nullptr) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001576 LogFromSpaceRefHolder(obj, offset);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001577 }
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001578 ref->GetLockWord(false).Dump(LOG(INTERNAL_FATAL));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001579 CHECK(false) << "Found from-space ref " << ref << " " << PrettyTypeOf(ref);
1580 } else {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001581 AssertToSpaceInvariantInNonMovingSpace(obj, ref);
1582 }
1583 }
1584}
1585
1586class RootPrinter {
1587 public:
1588 RootPrinter() { }
1589
1590 template <class MirrorType>
1591 ALWAYS_INLINE void VisitRootIfNonNull(mirror::CompressedReference<MirrorType>* root)
Mathieu Chartier90443472015-07-16 20:32:27 -07001592 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001593 if (!root->IsNull()) {
1594 VisitRoot(root);
1595 }
1596 }
1597
1598 template <class MirrorType>
1599 void VisitRoot(mirror::Object** root)
Mathieu Chartier90443472015-07-16 20:32:27 -07001600 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001601 LOG(INTERNAL_FATAL) << "root=" << root << " ref=" << *root;
1602 }
1603
1604 template <class MirrorType>
1605 void VisitRoot(mirror::CompressedReference<MirrorType>* root)
Mathieu Chartier90443472015-07-16 20:32:27 -07001606 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001607 LOG(INTERNAL_FATAL) << "root=" << root << " ref=" << root->AsMirrorPtr();
1608 }
1609};
1610
1611void ConcurrentCopying::AssertToSpaceInvariant(GcRootSource* gc_root_source,
1612 mirror::Object* ref) {
1613 CHECK(heap_->collector_type_ == kCollectorTypeCC) << static_cast<size_t>(heap_->collector_type_);
1614 if (is_asserting_to_space_invariant_) {
1615 if (region_space_->IsInToSpace(ref)) {
1616 // OK.
1617 return;
1618 } else if (region_space_->IsInUnevacFromSpace(ref)) {
1619 CHECK(region_space_bitmap_->Test(ref)) << ref;
1620 } else if (region_space_->IsInFromSpace(ref)) {
1621 // Not OK. Do extra logging.
1622 if (gc_root_source == nullptr) {
1623 // No info.
1624 } else if (gc_root_source->HasArtField()) {
1625 ArtField* field = gc_root_source->GetArtField();
1626 LOG(INTERNAL_FATAL) << "gc root in field " << field << " " << PrettyField(field);
1627 RootPrinter root_printer;
1628 field->VisitRoots(root_printer);
1629 } else if (gc_root_source->HasArtMethod()) {
1630 ArtMethod* method = gc_root_source->GetArtMethod();
1631 LOG(INTERNAL_FATAL) << "gc root in method " << method << " " << PrettyMethod(method);
1632 RootPrinter root_printer;
Andreas Gampe542451c2016-07-26 09:02:02 -07001633 method->VisitRoots(root_printer, kRuntimePointerSize);
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001634 }
1635 ref->GetLockWord(false).Dump(LOG(INTERNAL_FATAL));
1636 region_space_->DumpNonFreeRegions(LOG(INTERNAL_FATAL));
1637 PrintFileToLog("/proc/self/maps", LogSeverity::INTERNAL_FATAL);
1638 MemMap::DumpMaps(LOG(INTERNAL_FATAL), true);
1639 CHECK(false) << "Found from-space ref " << ref << " " << PrettyTypeOf(ref);
1640 } else {
1641 AssertToSpaceInvariantInNonMovingSpace(nullptr, ref);
1642 }
1643 }
1644}
1645
1646void ConcurrentCopying::LogFromSpaceRefHolder(mirror::Object* obj, MemberOffset offset) {
1647 if (kUseBakerReadBarrier) {
1648 LOG(INFO) << "holder=" << obj << " " << PrettyTypeOf(obj)
1649 << " holder rb_ptr=" << obj->GetReadBarrierPointer();
1650 } else {
1651 LOG(INFO) << "holder=" << obj << " " << PrettyTypeOf(obj);
1652 }
1653 if (region_space_->IsInFromSpace(obj)) {
1654 LOG(INFO) << "holder is in the from-space.";
1655 } else if (region_space_->IsInToSpace(obj)) {
1656 LOG(INFO) << "holder is in the to-space.";
1657 } else if (region_space_->IsInUnevacFromSpace(obj)) {
1658 LOG(INFO) << "holder is in the unevac from-space.";
1659 if (region_space_bitmap_->Test(obj)) {
1660 LOG(INFO) << "holder is marked in the region space bitmap.";
1661 } else {
1662 LOG(INFO) << "holder is not marked in the region space bitmap.";
1663 }
1664 } else {
1665 // In a non-moving space.
Mathieu Chartier763a31e2015-11-16 16:05:55 -08001666 if (immune_spaces_.ContainsObject(obj)) {
1667 LOG(INFO) << "holder is in an immune image or the zygote space.";
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001668 } else {
Mathieu Chartier763a31e2015-11-16 16:05:55 -08001669 LOG(INFO) << "holder is in a non-immune, non-moving (or main) space.";
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001670 accounting::ContinuousSpaceBitmap* mark_bitmap =
1671 heap_mark_bitmap_->GetContinuousSpaceBitmap(obj);
1672 accounting::LargeObjectBitmap* los_bitmap =
1673 heap_mark_bitmap_->GetLargeObjectBitmap(obj);
1674 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
1675 bool is_los = mark_bitmap == nullptr;
1676 if (!is_los && mark_bitmap->Test(obj)) {
1677 LOG(INFO) << "holder is marked in the mark bit map.";
1678 } else if (is_los && los_bitmap->Test(obj)) {
1679 LOG(INFO) << "holder is marked in the los bit map.";
1680 } else {
1681 // If ref is on the allocation stack, then it is considered
1682 // mark/alive (but not necessarily on the live stack.)
1683 if (IsOnAllocStack(obj)) {
1684 LOG(INFO) << "holder is on the alloc stack.";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001685 } else {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001686 LOG(INFO) << "holder is not marked or on the alloc stack.";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001687 }
1688 }
1689 }
1690 }
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001691 LOG(INFO) << "offset=" << offset.SizeValue();
1692}
1693
1694void ConcurrentCopying::AssertToSpaceInvariantInNonMovingSpace(mirror::Object* obj,
1695 mirror::Object* ref) {
1696 // In a non-moving spaces. Check that the ref is marked.
Mathieu Chartier763a31e2015-11-16 16:05:55 -08001697 if (immune_spaces_.ContainsObject(ref)) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001698 if (kUseBakerReadBarrier) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001699 // Immune object may not be gray if called from the GC.
1700 if (Thread::Current() == thread_running_gc_ && !gc_grays_immune_objects_) {
1701 return;
1702 }
1703 bool updated_all_immune_objects = updated_all_immune_objects_.LoadSequentiallyConsistent();
1704 CHECK(updated_all_immune_objects || ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr())
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001705 << "Unmarked immune space ref. obj=" << obj << " rb_ptr="
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001706 << (obj != nullptr ? obj->GetReadBarrierPointer() : nullptr)
1707 << " ref=" << ref << " ref rb_ptr=" << ref->GetReadBarrierPointer()
1708 << " updated_all_immune_objects=" << updated_all_immune_objects;
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001709 }
1710 } else {
1711 accounting::ContinuousSpaceBitmap* mark_bitmap =
1712 heap_mark_bitmap_->GetContinuousSpaceBitmap(ref);
1713 accounting::LargeObjectBitmap* los_bitmap =
1714 heap_mark_bitmap_->GetLargeObjectBitmap(ref);
1715 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
1716 bool is_los = mark_bitmap == nullptr;
1717 if ((!is_los && mark_bitmap->Test(ref)) ||
1718 (is_los && los_bitmap->Test(ref))) {
1719 // OK.
1720 } else {
1721 // If ref is on the allocation stack, then it may not be
1722 // marked live, but considered marked/alive (but not
1723 // necessarily on the live stack).
1724 CHECK(IsOnAllocStack(ref)) << "Unmarked ref that's not on the allocation stack. "
1725 << "obj=" << obj << " ref=" << ref;
1726 }
1727 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001728}
1729
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001730// Used to scan ref fields of an object.
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001731class ConcurrentCopying::RefFieldsVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001732 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001733 explicit RefFieldsVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001734 : collector_(collector) {}
1735
1736 void operator()(mirror::Object* obj, MemberOffset offset, bool /* is_static */)
Mathieu Chartier90443472015-07-16 20:32:27 -07001737 const ALWAYS_INLINE SHARED_REQUIRES(Locks::mutator_lock_)
1738 SHARED_REQUIRES(Locks::heap_bitmap_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001739 collector_->Process(obj, offset);
1740 }
1741
1742 void operator()(mirror::Class* klass, mirror::Reference* ref) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001743 SHARED_REQUIRES(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001744 CHECK(klass->IsTypeOfReferenceClass());
1745 collector_->DelayReferenceReferent(klass, ref);
1746 }
1747
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001748 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001749 ALWAYS_INLINE
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001750 SHARED_REQUIRES(Locks::mutator_lock_) {
1751 if (!root->IsNull()) {
1752 VisitRoot(root);
1753 }
1754 }
1755
1756 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001757 ALWAYS_INLINE
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001758 SHARED_REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001759 collector_->MarkRoot</*kGrayImmuneObject*/false>(root);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001760 }
1761
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001762 private:
1763 ConcurrentCopying* const collector_;
1764};
1765
1766// Scan ref fields of an object.
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001767inline void ConcurrentCopying::Scan(mirror::Object* to_ref) {
Mathieu Chartierd6636d32016-07-28 11:02:38 -07001768 if (kDisallowReadBarrierDuringScan) {
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07001769 // Avoid all read barriers during visit references to help performance.
1770 Thread::Current()->ModifyDebugDisallowReadBarrier(1);
1771 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001772 DCHECK(!region_space_->IsInFromSpace(to_ref));
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001773 DCHECK_EQ(Thread::Current(), thread_running_gc_);
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001774 RefFieldsVisitor visitor(this);
Hiroshi Yamauchi5496f692016-02-17 13:29:59 -08001775 // Disable the read barrier for a performance reason.
1776 to_ref->VisitReferences</*kVisitNativeRoots*/true, kDefaultVerifyFlags, kWithoutReadBarrier>(
1777 visitor, visitor);
Mathieu Chartierd6636d32016-07-28 11:02:38 -07001778 if (kDisallowReadBarrierDuringScan) {
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07001779 Thread::Current()->ModifyDebugDisallowReadBarrier(-1);
1780 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001781}
1782
1783// Process a field.
1784inline void ConcurrentCopying::Process(mirror::Object* obj, MemberOffset offset) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001785 DCHECK_EQ(Thread::Current(), thread_running_gc_);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001786 mirror::Object* ref = obj->GetFieldObject<
1787 mirror::Object, kVerifyNone, kWithoutReadBarrier, false>(offset);
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001788 mirror::Object* to_ref = Mark</*kGrayImmuneObject*/false>(ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001789 if (to_ref == ref) {
1790 return;
1791 }
1792 // This may fail if the mutator writes to the field at the same time. But it's ok.
1793 mirror::Object* expected_ref = ref;
1794 mirror::Object* new_ref = to_ref;
1795 do {
1796 if (expected_ref !=
1797 obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier, false>(offset)) {
1798 // It was updated by the mutator.
1799 break;
1800 }
Hiroshi Yamauchifed3e2f2015-10-20 11:11:56 -07001801 } while (!obj->CasFieldWeakRelaxedObjectWithoutWriteBarrier<
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001802 false, false, kVerifyNone>(offset, expected_ref, new_ref));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001803}
1804
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001805// Process some roots.
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001806inline void ConcurrentCopying::VisitRoots(
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001807 mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED) {
1808 for (size_t i = 0; i < count; ++i) {
1809 mirror::Object** root = roots[i];
1810 mirror::Object* ref = *root;
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001811 mirror::Object* to_ref = Mark(ref);
1812 if (to_ref == ref) {
Mathieu Chartier4809d0a2015-04-07 10:39:04 -07001813 continue;
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001814 }
1815 Atomic<mirror::Object*>* addr = reinterpret_cast<Atomic<mirror::Object*>*>(root);
1816 mirror::Object* expected_ref = ref;
1817 mirror::Object* new_ref = to_ref;
1818 do {
1819 if (expected_ref != addr->LoadRelaxed()) {
1820 // It was updated by the mutator.
1821 break;
1822 }
Hiroshi Yamauchifed3e2f2015-10-20 11:11:56 -07001823 } while (!addr->CompareExchangeWeakRelaxed(expected_ref, new_ref));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001824 }
1825}
1826
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001827template<bool kGrayImmuneObject>
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001828inline void ConcurrentCopying::MarkRoot(mirror::CompressedReference<mirror::Object>* root) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001829 DCHECK(!root->IsNull());
1830 mirror::Object* const ref = root->AsMirrorPtr();
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001831 mirror::Object* to_ref = Mark<kGrayImmuneObject>(ref);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001832 if (to_ref != ref) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001833 auto* addr = reinterpret_cast<Atomic<mirror::CompressedReference<mirror::Object>>*>(root);
1834 auto expected_ref = mirror::CompressedReference<mirror::Object>::FromMirrorPtr(ref);
1835 auto new_ref = mirror::CompressedReference<mirror::Object>::FromMirrorPtr(to_ref);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001836 // If the cas fails, then it was updated by the mutator.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001837 do {
1838 if (ref != addr->LoadRelaxed().AsMirrorPtr()) {
1839 // It was updated by the mutator.
1840 break;
1841 }
Hiroshi Yamauchifed3e2f2015-10-20 11:11:56 -07001842 } while (!addr->CompareExchangeWeakRelaxed(expected_ref, new_ref));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001843 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001844}
1845
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001846inline void ConcurrentCopying::VisitRoots(
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001847 mirror::CompressedReference<mirror::Object>** roots, size_t count,
1848 const RootInfo& info ATTRIBUTE_UNUSED) {
1849 for (size_t i = 0; i < count; ++i) {
1850 mirror::CompressedReference<mirror::Object>* const root = roots[i];
1851 if (!root->IsNull()) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001852 // kGrayImmuneObject is true because this is used for the thread flip.
1853 MarkRoot</*kGrayImmuneObject*/true>(root);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001854 }
1855 }
1856}
1857
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001858// Temporary set gc_grays_immune_objects_ to true in a scope if the current thread is GC.
1859class ConcurrentCopying::ScopedGcGraysImmuneObjects {
1860 public:
1861 explicit ScopedGcGraysImmuneObjects(ConcurrentCopying* collector)
1862 : collector_(collector), enabled_(false) {
1863 if (kUseBakerReadBarrier &&
1864 collector_->thread_running_gc_ == Thread::Current() &&
1865 !collector_->gc_grays_immune_objects_) {
1866 collector_->gc_grays_immune_objects_ = true;
1867 enabled_ = true;
1868 }
1869 }
1870
1871 ~ScopedGcGraysImmuneObjects() {
1872 if (kUseBakerReadBarrier &&
1873 collector_->thread_running_gc_ == Thread::Current() &&
1874 enabled_) {
1875 DCHECK(collector_->gc_grays_immune_objects_);
1876 collector_->gc_grays_immune_objects_ = false;
1877 }
1878 }
1879
1880 private:
1881 ConcurrentCopying* const collector_;
1882 bool enabled_;
1883};
1884
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001885// Fill the given memory block with a dummy object. Used to fill in a
1886// copy of objects that was lost in race.
1887void ConcurrentCopying::FillWithDummyObject(mirror::Object* dummy_obj, size_t byte_size) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001888 // GC doesn't gray immune objects while scanning immune objects. But we need to trigger the read
1889 // barriers here because we need the updated reference to the int array class, etc. Temporary set
1890 // gc_grays_immune_objects_ to true so that we won't cause a DCHECK failure in MarkImmuneSpace().
1891 ScopedGcGraysImmuneObjects scoped_gc_gray_immune_objects(this);
Roland Levillain14d90572015-07-16 10:52:26 +01001892 CHECK_ALIGNED(byte_size, kObjectAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001893 memset(dummy_obj, 0, byte_size);
Mathieu Chartierd6636d32016-07-28 11:02:38 -07001894 // Avoid going through read barrier for since kDisallowReadBarrierDuringScan may be enabled.
1895 // Explicitly mark to make sure to get an object in the to-space.
1896 mirror::Class* int_array_class = down_cast<mirror::Class*>(
1897 Mark(mirror::IntArray::GetArrayClass<kWithoutReadBarrier>()));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001898 CHECK(int_array_class != nullptr);
1899 AssertToSpaceInvariant(nullptr, MemberOffset(0), int_array_class);
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07001900 size_t component_size = int_array_class->GetComponentSize<kWithoutReadBarrier>();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001901 CHECK_EQ(component_size, sizeof(int32_t));
1902 size_t data_offset = mirror::Array::DataOffset(component_size).SizeValue();
1903 if (data_offset > byte_size) {
1904 // An int array is too big. Use java.lang.Object.
1905 mirror::Class* java_lang_Object = WellKnownClasses::ToClass(WellKnownClasses::java_lang_Object);
1906 AssertToSpaceInvariant(nullptr, MemberOffset(0), java_lang_Object);
Mathieu Chartierd6636d32016-07-28 11:02:38 -07001907 CHECK_EQ(byte_size, (java_lang_Object->GetObjectSize<kVerifyNone, kWithoutReadBarrier>()));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001908 dummy_obj->SetClass(java_lang_Object);
Mathieu Chartierd6636d32016-07-28 11:02:38 -07001909 CHECK_EQ(byte_size, (dummy_obj->SizeOf<kVerifyNone, kWithoutReadBarrier>()));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001910 } else {
1911 // Use an int array.
1912 dummy_obj->SetClass(int_array_class);
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07001913 CHECK((dummy_obj->IsArrayInstance<kVerifyNone, kWithoutReadBarrier>()));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001914 int32_t length = (byte_size - data_offset) / component_size;
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07001915 mirror::Array* dummy_arr = dummy_obj->AsArray<kVerifyNone, kWithoutReadBarrier>();
1916 dummy_arr->SetLength(length);
1917 CHECK_EQ(dummy_arr->GetLength(), length)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001918 << "byte_size=" << byte_size << " length=" << length
1919 << " component_size=" << component_size << " data_offset=" << data_offset;
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07001920 CHECK_EQ(byte_size, (dummy_obj->SizeOf<kVerifyNone, kWithoutReadBarrier>()))
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001921 << "byte_size=" << byte_size << " length=" << length
1922 << " component_size=" << component_size << " data_offset=" << data_offset;
1923 }
1924}
1925
1926// Reuse the memory blocks that were copy of objects that were lost in race.
1927mirror::Object* ConcurrentCopying::AllocateInSkippedBlock(size_t alloc_size) {
1928 // Try to reuse the blocks that were unused due to CAS failures.
Roland Levillain14d90572015-07-16 10:52:26 +01001929 CHECK_ALIGNED(alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001930 Thread* self = Thread::Current();
1931 size_t min_object_size = RoundUp(sizeof(mirror::Object), space::RegionSpace::kAlignment);
Mathieu Chartierd6636d32016-07-28 11:02:38 -07001932 size_t byte_size;
1933 uint8_t* addr;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001934 {
Mathieu Chartierd6636d32016-07-28 11:02:38 -07001935 MutexLock mu(self, skipped_blocks_lock_);
1936 auto it = skipped_blocks_map_.lower_bound(alloc_size);
1937 if (it == skipped_blocks_map_.end()) {
1938 // Not found.
1939 return nullptr;
1940 }
1941 byte_size = it->first;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001942 CHECK_GE(byte_size, alloc_size);
1943 if (byte_size > alloc_size && byte_size - alloc_size < min_object_size) {
1944 // If remainder would be too small for a dummy object, retry with a larger request size.
1945 it = skipped_blocks_map_.lower_bound(alloc_size + min_object_size);
1946 if (it == skipped_blocks_map_.end()) {
1947 // Not found.
1948 return nullptr;
1949 }
Roland Levillain14d90572015-07-16 10:52:26 +01001950 CHECK_ALIGNED(it->first - alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001951 CHECK_GE(it->first - alloc_size, min_object_size)
1952 << "byte_size=" << byte_size << " it->first=" << it->first << " alloc_size=" << alloc_size;
1953 }
Mathieu Chartierd6636d32016-07-28 11:02:38 -07001954 // Found a block.
1955 CHECK(it != skipped_blocks_map_.end());
1956 byte_size = it->first;
1957 addr = it->second;
1958 CHECK_GE(byte_size, alloc_size);
1959 CHECK(region_space_->IsInToSpace(reinterpret_cast<mirror::Object*>(addr)));
1960 CHECK_ALIGNED(byte_size, space::RegionSpace::kAlignment);
1961 if (kVerboseMode) {
1962 LOG(INFO) << "Reusing skipped bytes : " << reinterpret_cast<void*>(addr) << ", " << byte_size;
1963 }
1964 skipped_blocks_map_.erase(it);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001965 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001966 memset(addr, 0, byte_size);
1967 if (byte_size > alloc_size) {
1968 // Return the remainder to the map.
Roland Levillain14d90572015-07-16 10:52:26 +01001969 CHECK_ALIGNED(byte_size - alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001970 CHECK_GE(byte_size - alloc_size, min_object_size);
Mathieu Chartierd6636d32016-07-28 11:02:38 -07001971 // FillWithDummyObject may mark an object, avoid holding skipped_blocks_lock_ to prevent lock
1972 // violation and possible deadlock. The deadlock case is a recursive case:
1973 // FillWithDummyObject -> IntArray::GetArrayClass -> Mark -> Copy -> AllocateInSkippedBlock.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001974 FillWithDummyObject(reinterpret_cast<mirror::Object*>(addr + alloc_size),
1975 byte_size - alloc_size);
1976 CHECK(region_space_->IsInToSpace(reinterpret_cast<mirror::Object*>(addr + alloc_size)));
Mathieu Chartierd6636d32016-07-28 11:02:38 -07001977 {
1978 MutexLock mu(self, skipped_blocks_lock_);
1979 skipped_blocks_map_.insert(std::make_pair(byte_size - alloc_size, addr + alloc_size));
1980 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001981 }
1982 return reinterpret_cast<mirror::Object*>(addr);
1983}
1984
1985mirror::Object* ConcurrentCopying::Copy(mirror::Object* from_ref) {
1986 DCHECK(region_space_->IsInFromSpace(from_ref));
1987 // No read barrier to avoid nested RB that might violate the to-space
1988 // invariant. Note that from_ref is a from space ref so the SizeOf()
1989 // call will access the from-space meta objects, but it's ok and necessary.
1990 size_t obj_size = from_ref->SizeOf<kDefaultVerifyFlags, kWithoutReadBarrier>();
1991 size_t region_space_alloc_size = RoundUp(obj_size, space::RegionSpace::kAlignment);
1992 size_t region_space_bytes_allocated = 0U;
1993 size_t non_moving_space_bytes_allocated = 0U;
1994 size_t bytes_allocated = 0U;
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001995 size_t dummy;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001996 mirror::Object* to_ref = region_space_->AllocNonvirtual<true>(
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001997 region_space_alloc_size, &region_space_bytes_allocated, nullptr, &dummy);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001998 bytes_allocated = region_space_bytes_allocated;
1999 if (to_ref != nullptr) {
2000 DCHECK_EQ(region_space_alloc_size, region_space_bytes_allocated);
2001 }
2002 bool fall_back_to_non_moving = false;
2003 if (UNLIKELY(to_ref == nullptr)) {
2004 // Failed to allocate in the region space. Try the skipped blocks.
2005 to_ref = AllocateInSkippedBlock(region_space_alloc_size);
2006 if (to_ref != nullptr) {
2007 // Succeeded to allocate in a skipped block.
2008 if (heap_->use_tlab_) {
2009 // This is necessary for the tlab case as it's not accounted in the space.
2010 region_space_->RecordAlloc(to_ref);
2011 }
2012 bytes_allocated = region_space_alloc_size;
2013 } else {
2014 // Fall back to the non-moving space.
2015 fall_back_to_non_moving = true;
2016 if (kVerboseMode) {
2017 LOG(INFO) << "Out of memory in the to-space. Fall back to non-moving. skipped_bytes="
2018 << to_space_bytes_skipped_.LoadSequentiallyConsistent()
2019 << " skipped_objects=" << to_space_objects_skipped_.LoadSequentiallyConsistent();
2020 }
2021 fall_back_to_non_moving = true;
2022 to_ref = heap_->non_moving_space_->Alloc(Thread::Current(), obj_size,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07002023 &non_moving_space_bytes_allocated, nullptr, &dummy);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002024 CHECK(to_ref != nullptr) << "Fall-back non-moving space allocation failed";
2025 bytes_allocated = non_moving_space_bytes_allocated;
2026 // Mark it in the mark bitmap.
2027 accounting::ContinuousSpaceBitmap* mark_bitmap =
2028 heap_mark_bitmap_->GetContinuousSpaceBitmap(to_ref);
2029 CHECK(mark_bitmap != nullptr);
2030 CHECK(!mark_bitmap->AtomicTestAndSet(to_ref));
2031 }
2032 }
2033 DCHECK(to_ref != nullptr);
2034
2035 // Attempt to install the forward pointer. This is in a loop as the
2036 // lock word atomic write can fail.
2037 while (true) {
2038 // Copy the object. TODO: copy only the lockword in the second iteration and on?
2039 memcpy(to_ref, from_ref, obj_size);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002040
2041 LockWord old_lock_word = to_ref->GetLockWord(false);
2042
2043 if (old_lock_word.GetState() == LockWord::kForwardingAddress) {
2044 // Lost the race. Another thread (either GC or mutator) stored
2045 // the forwarding pointer first. Make the lost copy (to_ref)
2046 // look like a valid but dead (dummy) object and keep it for
2047 // future reuse.
2048 FillWithDummyObject(to_ref, bytes_allocated);
2049 if (!fall_back_to_non_moving) {
2050 DCHECK(region_space_->IsInToSpace(to_ref));
2051 if (bytes_allocated > space::RegionSpace::kRegionSize) {
2052 // Free the large alloc.
2053 region_space_->FreeLarge(to_ref, bytes_allocated);
2054 } else {
2055 // Record the lost copy for later reuse.
2056 heap_->num_bytes_allocated_.FetchAndAddSequentiallyConsistent(bytes_allocated);
2057 to_space_bytes_skipped_.FetchAndAddSequentiallyConsistent(bytes_allocated);
2058 to_space_objects_skipped_.FetchAndAddSequentiallyConsistent(1);
2059 MutexLock mu(Thread::Current(), skipped_blocks_lock_);
2060 skipped_blocks_map_.insert(std::make_pair(bytes_allocated,
2061 reinterpret_cast<uint8_t*>(to_ref)));
2062 }
2063 } else {
2064 DCHECK(heap_->non_moving_space_->HasAddress(to_ref));
2065 DCHECK_EQ(bytes_allocated, non_moving_space_bytes_allocated);
2066 // Free the non-moving-space chunk.
2067 accounting::ContinuousSpaceBitmap* mark_bitmap =
2068 heap_mark_bitmap_->GetContinuousSpaceBitmap(to_ref);
2069 CHECK(mark_bitmap != nullptr);
2070 CHECK(mark_bitmap->Clear(to_ref));
2071 heap_->non_moving_space_->Free(Thread::Current(), to_ref);
2072 }
2073
2074 // Get the winner's forward ptr.
2075 mirror::Object* lost_fwd_ptr = to_ref;
2076 to_ref = reinterpret_cast<mirror::Object*>(old_lock_word.ForwardingAddress());
2077 CHECK(to_ref != nullptr);
2078 CHECK_NE(to_ref, lost_fwd_ptr);
2079 CHECK(region_space_->IsInToSpace(to_ref) || heap_->non_moving_space_->HasAddress(to_ref));
2080 CHECK_NE(to_ref->GetLockWord(false).GetState(), LockWord::kForwardingAddress);
2081 return to_ref;
2082 }
2083
Hiroshi Yamauchi60f63f52015-04-23 16:12:40 -07002084 // Set the gray ptr.
2085 if (kUseBakerReadBarrier) {
2086 to_ref->SetReadBarrierPointer(ReadBarrier::GrayPtr());
2087 }
2088
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002089 LockWord new_lock_word = LockWord::FromForwardingAddress(reinterpret_cast<size_t>(to_ref));
2090
2091 // Try to atomically write the fwd ptr.
2092 bool success = from_ref->CasLockWordWeakSequentiallyConsistent(old_lock_word, new_lock_word);
2093 if (LIKELY(success)) {
2094 // The CAS succeeded.
2095 objects_moved_.FetchAndAddSequentiallyConsistent(1);
2096 bytes_moved_.FetchAndAddSequentiallyConsistent(region_space_alloc_size);
2097 if (LIKELY(!fall_back_to_non_moving)) {
2098 DCHECK(region_space_->IsInToSpace(to_ref));
2099 } else {
2100 DCHECK(heap_->non_moving_space_->HasAddress(to_ref));
2101 DCHECK_EQ(bytes_allocated, non_moving_space_bytes_allocated);
2102 }
2103 if (kUseBakerReadBarrier) {
2104 DCHECK(to_ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr());
2105 }
2106 DCHECK(GetFwdPtr(from_ref) == to_ref);
2107 CHECK_NE(to_ref->GetLockWord(false).GetState(), LockWord::kForwardingAddress);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002108 PushOntoMarkStack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002109 return to_ref;
2110 } else {
2111 // The CAS failed. It may have lost the race or may have failed
2112 // due to monitor/hashcode ops. Either way, retry.
2113 }
2114 }
2115}
2116
2117mirror::Object* ConcurrentCopying::IsMarked(mirror::Object* from_ref) {
2118 DCHECK(from_ref != nullptr);
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08002119 space::RegionSpace::RegionType rtype = region_space_->GetRegionType(from_ref);
2120 if (rtype == space::RegionSpace::RegionType::kRegionTypeToSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002121 // It's already marked.
2122 return from_ref;
2123 }
2124 mirror::Object* to_ref;
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08002125 if (rtype == space::RegionSpace::RegionType::kRegionTypeFromSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002126 to_ref = GetFwdPtr(from_ref);
2127 DCHECK(to_ref == nullptr || region_space_->IsInToSpace(to_ref) ||
2128 heap_->non_moving_space_->HasAddress(to_ref))
2129 << "from_ref=" << from_ref << " to_ref=" << to_ref;
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08002130 } else if (rtype == space::RegionSpace::RegionType::kRegionTypeUnevacFromSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002131 if (region_space_bitmap_->Test(from_ref)) {
2132 to_ref = from_ref;
2133 } else {
2134 to_ref = nullptr;
2135 }
2136 } else {
2137 // from_ref is in a non-moving space.
Mathieu Chartier763a31e2015-11-16 16:05:55 -08002138 if (immune_spaces_.ContainsObject(from_ref)) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002139 // An immune object is alive.
2140 to_ref = from_ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002141 } else {
2142 // Non-immune non-moving space. Use the mark bitmap.
2143 accounting::ContinuousSpaceBitmap* mark_bitmap =
2144 heap_mark_bitmap_->GetContinuousSpaceBitmap(from_ref);
2145 accounting::LargeObjectBitmap* los_bitmap =
2146 heap_mark_bitmap_->GetLargeObjectBitmap(from_ref);
2147 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
2148 bool is_los = mark_bitmap == nullptr;
2149 if (!is_los && mark_bitmap->Test(from_ref)) {
2150 // Already marked.
2151 to_ref = from_ref;
2152 } else if (is_los && los_bitmap->Test(from_ref)) {
2153 // Already marked in LOS.
2154 to_ref = from_ref;
2155 } else {
2156 // Not marked.
2157 if (IsOnAllocStack(from_ref)) {
2158 // If on the allocation stack, it's considered marked.
2159 to_ref = from_ref;
2160 } else {
2161 // Not marked.
2162 to_ref = nullptr;
2163 }
2164 }
2165 }
2166 }
2167 return to_ref;
2168}
2169
2170bool ConcurrentCopying::IsOnAllocStack(mirror::Object* ref) {
2171 QuasiAtomic::ThreadFenceAcquire();
2172 accounting::ObjectStack* alloc_stack = GetAllocationStack();
Mathieu Chartiercb535da2015-01-23 13:50:03 -08002173 return alloc_stack->Contains(ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002174}
2175
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002176mirror::Object* ConcurrentCopying::MarkNonMoving(mirror::Object* ref) {
2177 // ref is in a non-moving space (from_ref == to_ref).
2178 DCHECK(!region_space_->HasAddress(ref)) << ref;
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002179 DCHECK(!immune_spaces_.ContainsObject(ref));
2180 // Use the mark bitmap.
2181 accounting::ContinuousSpaceBitmap* mark_bitmap =
2182 heap_mark_bitmap_->GetContinuousSpaceBitmap(ref);
2183 accounting::LargeObjectBitmap* los_bitmap =
2184 heap_mark_bitmap_->GetLargeObjectBitmap(ref);
2185 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
2186 bool is_los = mark_bitmap == nullptr;
2187 if (!is_los && mark_bitmap->Test(ref)) {
2188 // Already marked.
2189 if (kUseBakerReadBarrier) {
2190 DCHECK(ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr() ||
2191 ref->GetReadBarrierPointer() == ReadBarrier::WhitePtr());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002192 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002193 } else if (is_los && los_bitmap->Test(ref)) {
2194 // Already marked in LOS.
2195 if (kUseBakerReadBarrier) {
2196 DCHECK(ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr() ||
2197 ref->GetReadBarrierPointer() == ReadBarrier::WhitePtr());
2198 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002199 } else {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002200 // Not marked.
2201 if (IsOnAllocStack(ref)) {
2202 // If it's on the allocation stack, it's considered marked. Keep it white.
2203 // Objects on the allocation stack need not be marked.
2204 if (!is_los) {
2205 DCHECK(!mark_bitmap->Test(ref));
2206 } else {
2207 DCHECK(!los_bitmap->Test(ref));
Nicolas Geoffrayddeb1722016-06-28 08:25:59 +00002208 }
Nicolas Geoffrayddeb1722016-06-28 08:25:59 +00002209 if (kUseBakerReadBarrier) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002210 DCHECK_EQ(ref->GetReadBarrierPointer(), ReadBarrier::WhitePtr());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002211 }
2212 } else {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002213 // For the baker-style RB, we need to handle 'false-gray' cases. See the
2214 // kRegionTypeUnevacFromSpace-case comment in Mark().
2215 if (kUseBakerReadBarrier) {
2216 // Test the bitmap first to reduce the chance of false gray cases.
2217 if ((!is_los && mark_bitmap->Test(ref)) ||
2218 (is_los && los_bitmap->Test(ref))) {
2219 return ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002220 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002221 }
2222 // Not marked or on the allocation stack. Try to mark it.
2223 // This may or may not succeed, which is ok.
2224 bool cas_success = false;
2225 if (kUseBakerReadBarrier) {
2226 cas_success = ref->AtomicSetReadBarrierPointer(ReadBarrier::WhitePtr(),
2227 ReadBarrier::GrayPtr());
2228 }
2229 if (!is_los && mark_bitmap->AtomicTestAndSet(ref)) {
2230 // Already marked.
2231 if (kUseBakerReadBarrier && cas_success &&
2232 ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr()) {
2233 PushOntoFalseGrayStack(ref);
2234 }
2235 } else if (is_los && los_bitmap->AtomicTestAndSet(ref)) {
2236 // Already marked in LOS.
2237 if (kUseBakerReadBarrier && cas_success &&
2238 ref->GetReadBarrierPointer() == ReadBarrier::GrayPtr()) {
2239 PushOntoFalseGrayStack(ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002240 }
2241 } else {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002242 // Newly marked.
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08002243 if (kUseBakerReadBarrier) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002244 DCHECK_EQ(ref->GetReadBarrierPointer(), ReadBarrier::GrayPtr());
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08002245 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002246 PushOntoMarkStack(ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002247 }
2248 }
2249 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002250 return ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002251}
2252
2253void ConcurrentCopying::FinishPhase() {
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -08002254 Thread* const self = Thread::Current();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002255 {
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -08002256 MutexLock mu(self, mark_stack_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002257 CHECK_EQ(pooled_mark_stacks_.size(), kMarkStackPoolSize);
2258 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002259 region_space_ = nullptr;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002260 {
2261 MutexLock mu(Thread::Current(), skipped_blocks_lock_);
2262 skipped_blocks_map_.clear();
2263 }
Mathieu Chartier56fe2582016-07-14 13:30:03 -07002264 {
2265 ReaderMutexLock mu(self, *Locks::mutator_lock_);
Mathieu Chartier21328a12016-07-22 10:47:45 -07002266 {
2267 WriterMutexLock mu2(self, *Locks::heap_bitmap_lock_);
2268 heap_->ClearMarkedObjects();
2269 }
2270 if (kUseBakerReadBarrier && kFilterModUnionCards) {
2271 TimingLogger::ScopedTiming split("FilterModUnionCards", GetTimings());
2272 ReaderMutexLock mu2(self, *Locks::heap_bitmap_lock_);
2273 gc::Heap* const heap = Runtime::Current()->GetHeap();
2274 for (space::ContinuousSpace* space : immune_spaces_.GetSpaces()) {
2275 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
2276 accounting::ModUnionTable* table = heap->FindModUnionTableFromSpace(space);
2277 // Filter out cards that don't need to be set.
2278 if (table != nullptr) {
2279 table->FilterCards();
2280 }
2281 }
2282 }
Mathieu Chartier36a270a2016-07-28 18:08:51 -07002283 if (kUseBakerReadBarrier) {
2284 TimingLogger::ScopedTiming split("EmptyRBMarkBitStack", GetTimings());
2285 DCHECK(rb_mark_bit_stack_.get() != nullptr);
2286 const auto* limit = rb_mark_bit_stack_->End();
2287 for (StackReference<mirror::Object>* it = rb_mark_bit_stack_->Begin(); it != limit; ++it) {
2288 CHECK(it->AsMirrorPtr()->AtomicSetMarkBit(1, 0));
2289 }
2290 rb_mark_bit_stack_->Reset();
2291 }
Mathieu Chartier56fe2582016-07-14 13:30:03 -07002292 }
2293 if (measure_read_barrier_slow_path_) {
2294 MutexLock mu(self, rb_slow_path_histogram_lock_);
2295 rb_slow_path_time_histogram_.AdjustAndAddValue(rb_slow_path_ns_.LoadRelaxed());
2296 rb_slow_path_count_total_ += rb_slow_path_count_.LoadRelaxed();
2297 rb_slow_path_count_gc_total_ += rb_slow_path_count_gc_.LoadRelaxed();
2298 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002299}
2300
Mathieu Chartier97509952015-07-13 14:35:43 -07002301bool ConcurrentCopying::IsMarkedHeapReference(mirror::HeapReference<mirror::Object>* field) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002302 mirror::Object* from_ref = field->AsMirrorPtr();
Mathieu Chartier97509952015-07-13 14:35:43 -07002303 mirror::Object* to_ref = IsMarked(from_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002304 if (to_ref == nullptr) {
2305 return false;
2306 }
2307 if (from_ref != to_ref) {
2308 QuasiAtomic::ThreadFenceRelease();
2309 field->Assign(to_ref);
2310 QuasiAtomic::ThreadFenceSequentiallyConsistent();
2311 }
2312 return true;
2313}
2314
Mathieu Chartier97509952015-07-13 14:35:43 -07002315mirror::Object* ConcurrentCopying::MarkObject(mirror::Object* from_ref) {
2316 return Mark(from_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002317}
2318
2319void ConcurrentCopying::DelayReferenceReferent(mirror::Class* klass, mirror::Reference* reference) {
Mathieu Chartier97509952015-07-13 14:35:43 -07002320 heap_->GetReferenceProcessor()->DelayReferenceReferent(klass, reference, this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002321}
2322
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002323void ConcurrentCopying::ProcessReferences(Thread* self) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002324 TimingLogger::ScopedTiming split("ProcessReferences", GetTimings());
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002325 // 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 -08002326 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
2327 GetHeap()->GetReferenceProcessor()->ProcessReferences(
Mathieu Chartier97509952015-07-13 14:35:43 -07002328 true /*concurrent*/, GetTimings(), GetCurrentIteration()->GetClearSoftReferences(), this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002329}
2330
2331void ConcurrentCopying::RevokeAllThreadLocalBuffers() {
2332 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
2333 region_space_->RevokeAllThreadLocalBuffers();
2334}
2335
Mathieu Chartier56fe2582016-07-14 13:30:03 -07002336mirror::Object* ConcurrentCopying::MarkFromReadBarrierWithMeasurements(mirror::Object* from_ref) {
2337 if (Thread::Current() != thread_running_gc_) {
2338 rb_slow_path_count_.FetchAndAddRelaxed(1u);
2339 } else {
2340 rb_slow_path_count_gc_.FetchAndAddRelaxed(1u);
2341 }
2342 ScopedTrace tr(__FUNCTION__);
2343 const uint64_t start_time = measure_read_barrier_slow_path_ ? NanoTime() : 0u;
2344 mirror::Object* ret = Mark(from_ref);
2345 if (measure_read_barrier_slow_path_) {
2346 rb_slow_path_ns_.FetchAndAddRelaxed(NanoTime() - start_time);
2347 }
2348 return ret;
2349}
2350
2351void ConcurrentCopying::DumpPerformanceInfo(std::ostream& os) {
2352 GarbageCollector::DumpPerformanceInfo(os);
2353 MutexLock mu(Thread::Current(), rb_slow_path_histogram_lock_);
2354 if (rb_slow_path_time_histogram_.SampleSize() > 0) {
2355 Histogram<uint64_t>::CumulativeData cumulative_data;
2356 rb_slow_path_time_histogram_.CreateHistogram(&cumulative_data);
2357 rb_slow_path_time_histogram_.PrintConfidenceIntervals(os, 0.99, cumulative_data);
2358 }
2359 if (rb_slow_path_count_total_ > 0) {
2360 os << "Slow path count " << rb_slow_path_count_total_ << "\n";
2361 }
2362 if (rb_slow_path_count_gc_total_ > 0) {
2363 os << "GC slow path count " << rb_slow_path_count_gc_total_ << "\n";
2364 }
Mathieu Chartiercca44a02016-08-17 10:07:29 -07002365 os << "Cumulative bytes moved " << cumulative_bytes_moved_.LoadRelaxed() << "\n";
2366 os << "Cumulative objects moved " << cumulative_objects_moved_.LoadRelaxed() << "\n";
Mathieu Chartier56fe2582016-07-14 13:30:03 -07002367}
2368
Hiroshi Yamauchid5307ec2014-03-27 21:07:51 -07002369} // namespace collector
2370} // namespace gc
2371} // namespace art