blob: b03f67152b4ba051b667329a048e9a0ccb944ca0 [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"
David Sehr891a50e2017-10-27 17:01:07 -070021#include "base/file_utils.h"
Mathieu Chartier56fe2582016-07-14 13:30:03 -070022#include "base/histogram-inl.h"
David Sehrc431b9d2018-03-02 12:01:51 -080023#include "base/quasi_atomic.h"
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070024#include "base/stl_util.h"
Mathieu Chartier56fe2582016-07-14 13:30:03 -070025#include "base/systrace.h"
Vladimir Markob4eb1b12018-05-24 11:09:38 +010026#include "class_root.h"
Mathieu Chartiera6b1ead2015-10-06 10:32:38 -070027#include "debugger.h"
Andreas Gampe291ce172017-04-24 13:22:18 -070028#include "gc/accounting/atomic_stack.h"
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080029#include "gc/accounting/heap_bitmap-inl.h"
Mathieu Chartier21328a12016-07-22 10:47:45 -070030#include "gc/accounting/mod_union_table-inl.h"
Andreas Gampe291ce172017-04-24 13:22:18 -070031#include "gc/accounting/read_barrier_table.h"
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080032#include "gc/accounting/space_bitmap-inl.h"
Andreas Gampe4934eb12017-01-30 13:15:26 -080033#include "gc/gc_pause_listener.h"
Mathieu Chartier3cf22532015-07-09 15:15:09 -070034#include "gc/reference_processor.h"
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080035#include "gc/space/image_space.h"
Mathieu Chartier073b16c2015-11-10 14:13:23 -080036#include "gc/space/space-inl.h"
Mathieu Chartier1ca68902017-04-18 11:26:22 -070037#include "gc/verification.h"
Mathieu Chartier4a26f172016-01-26 14:26:18 -080038#include "image-inl.h"
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080039#include "intern_table.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070040#include "mirror/class-inl.h"
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080041#include "mirror/object-inl.h"
Andreas Gampec6ea7d02017-02-01 16:46:28 -080042#include "mirror/object-refvisitor-inl.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070043#include "scoped_thread_state_change-inl.h"
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080044#include "thread-inl.h"
45#include "thread_list.h"
46#include "well_known_classes.h"
47
Hiroshi Yamauchid5307ec2014-03-27 21:07:51 -070048namespace art {
49namespace gc {
50namespace collector {
51
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -070052static constexpr size_t kDefaultGcMarkStackSize = 2 * MB;
Mathieu Chartier21328a12016-07-22 10:47:45 -070053// If kFilterModUnionCards then we attempt to filter cards that don't need to be dirty in the mod
54// union table. Disabled since it does not seem to help the pause much.
55static constexpr bool kFilterModUnionCards = kIsDebugBuild;
Roland Levillain72b7bf82018-08-07 18:39:27 +010056// If kDisallowReadBarrierDuringScan is true then the GC aborts if there are any read barrier that
57// occur during ConcurrentCopying::Scan in GC thread. May be used to diagnose possibly unnecessary
58// read barriers. Only enabled for kIsDebugBuild to avoid performance hit.
Mathieu Chartierd6636d32016-07-28 11:02:38 -070059static constexpr bool kDisallowReadBarrierDuringScan = kIsDebugBuild;
Mathieu Chartier36a270a2016-07-28 18:08:51 -070060// Slow path mark stack size, increase this if the stack is getting full and it is causing
61// performance problems.
62static constexpr size_t kReadBarrierMarkStackSize = 512 * KB;
Mathieu Chartiera1467d02017-02-22 09:22:50 -080063// Verify that there are no missing card marks.
64static constexpr bool kVerifyNoMissingCardMarks = kIsDebugBuild;
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -070065
Mathieu Chartier56fe2582016-07-14 13:30:03 -070066ConcurrentCopying::ConcurrentCopying(Heap* heap,
67 const std::string& name_prefix,
68 bool measure_read_barrier_slow_path)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080069 : GarbageCollector(heap,
70 name_prefix + (name_prefix.empty() ? "" : " ") +
Hiroshi Yamauchi88e08162017-01-06 15:03:26 -080071 "concurrent copying"),
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070072 region_space_(nullptr), gc_barrier_(new Barrier(0)),
73 gc_mark_stack_(accounting::ObjectStack::Create("concurrent copying gc mark stack",
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -070074 kDefaultGcMarkStackSize,
75 kDefaultGcMarkStackSize)),
Mathieu Chartier36a270a2016-07-28 18:08:51 -070076 rb_mark_bit_stack_(accounting::ObjectStack::Create("rb copying gc mark stack",
77 kReadBarrierMarkStackSize,
78 kReadBarrierMarkStackSize)),
79 rb_mark_bit_stack_full_(false),
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070080 mark_stack_lock_("concurrent copying mark stack lock", kMarkSweepMarkStackLock),
81 thread_running_gc_(nullptr),
Andreas Gamped9911ee2017-03-27 13:27:24 -070082 is_marking_(false),
Mathieu Chartier3768ade2017-05-02 14:04:39 -070083 is_using_read_barrier_entrypoints_(false),
Andreas Gamped9911ee2017-03-27 13:27:24 -070084 is_active_(false),
85 is_asserting_to_space_invariant_(false),
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -070086 region_space_bitmap_(nullptr),
Andreas Gamped9911ee2017-03-27 13:27:24 -070087 heap_mark_bitmap_(nullptr),
88 live_stack_freeze_size_(0),
89 from_space_num_objects_at_first_pause_(0),
90 from_space_num_bytes_at_first_pause_(0),
91 mark_stack_mode_(kMarkStackModeOff),
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070092 weak_ref_access_enabled_(true),
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080093 skipped_blocks_lock_("concurrent copying bytes blocks lock", kMarkSweepMarkStackLock),
Mathieu Chartier56fe2582016-07-14 13:30:03 -070094 measure_read_barrier_slow_path_(measure_read_barrier_slow_path),
Andreas Gamped9911ee2017-03-27 13:27:24 -070095 mark_from_read_barrier_measurements_(false),
Mathieu Chartier56fe2582016-07-14 13:30:03 -070096 rb_slow_path_ns_(0),
97 rb_slow_path_count_(0),
98 rb_slow_path_count_gc_(0),
99 rb_slow_path_histogram_lock_("Read barrier histogram lock"),
100 rb_slow_path_time_histogram_("Mutator time in read barrier slow path", 500, 32),
101 rb_slow_path_count_total_(0),
102 rb_slow_path_count_gc_total_(0),
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800103 rb_table_(heap_->GetReadBarrierTable()),
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700104 force_evacuate_all_(false),
Andreas Gamped9911ee2017-03-27 13:27:24 -0700105 gc_grays_immune_objects_(false),
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700106 immune_gray_stack_lock_("concurrent copying immune gray stack lock",
107 kMarkSweepMarkStackLock) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800108 static_assert(space::RegionSpace::kRegionSize == accounting::ReadBarrierTable::kRegionSize,
109 "The region space size and the read barrier table region size must match");
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700110 Thread* self = Thread::Current();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800111 {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800112 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
113 // Cache this so that we won't have to lock heap_bitmap_lock_ in
114 // Mark() which could cause a nested lock on heap_bitmap_lock_
115 // when GC causes a RB while doing GC or a lock order violation
116 // (class_linker_lock_ and heap_bitmap_lock_).
117 heap_mark_bitmap_ = heap->GetMarkBitmap();
118 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700119 {
120 MutexLock mu(self, mark_stack_lock_);
121 for (size_t i = 0; i < kMarkStackPoolSize; ++i) {
122 accounting::AtomicStack<mirror::Object>* mark_stack =
123 accounting::AtomicStack<mirror::Object>::Create(
124 "thread local mark stack", kMarkStackSize, kMarkStackSize);
125 pooled_mark_stacks_.push_back(mark_stack);
126 }
127 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800128}
129
Hiroshi Yamauchi057d9772017-02-17 15:33:23 -0800130void ConcurrentCopying::MarkHeapReference(mirror::HeapReference<mirror::Object>* field,
131 bool do_atomic_update) {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -0800132 Thread* const self = Thread::Current();
Hiroshi Yamauchi057d9772017-02-17 15:33:23 -0800133 if (UNLIKELY(do_atomic_update)) {
134 // Used to mark the referent in DelayReferenceReferent in transaction mode.
135 mirror::Object* from_ref = field->AsMirrorPtr();
136 if (from_ref == nullptr) {
137 return;
138 }
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -0800139 mirror::Object* to_ref = Mark(self, from_ref);
Hiroshi Yamauchi057d9772017-02-17 15:33:23 -0800140 if (from_ref != to_ref) {
141 do {
142 if (field->AsMirrorPtr() != from_ref) {
143 // Concurrently overwritten by a mutator.
144 break;
145 }
146 } while (!field->CasWeakRelaxed(from_ref, to_ref));
147 }
148 } else {
149 // Used for preserving soft references, should be OK to not have a CAS here since there should be
150 // no other threads which can trigger read barriers on the same referent during reference
151 // processing.
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -0800152 field->Assign(Mark(self, field->AsMirrorPtr()));
Hiroshi Yamauchi057d9772017-02-17 15:33:23 -0800153 }
Mathieu Chartier97509952015-07-13 14:35:43 -0700154}
155
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800156ConcurrentCopying::~ConcurrentCopying() {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700157 STLDeleteElements(&pooled_mark_stacks_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800158}
159
160void ConcurrentCopying::RunPhases() {
161 CHECK(kUseBakerReadBarrier || kUseTableLookupReadBarrier);
162 CHECK(!is_active_);
163 is_active_ = true;
164 Thread* self = Thread::Current();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700165 thread_running_gc_ = self;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800166 Locks::mutator_lock_->AssertNotHeld(self);
167 {
168 ReaderMutexLock mu(self, *Locks::mutator_lock_);
169 InitializePhase();
170 }
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700171 if (kUseBakerReadBarrier && kGrayDirtyImmuneObjects) {
172 // Switch to read barrier mark entrypoints before we gray the objects. This is required in case
Roland Levillain97c46462017-05-11 14:04:03 +0100173 // a mutator sees a gray bit and dispatches on the entrypoint. (b/37876887).
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700174 ActivateReadBarrierEntrypoints();
175 // Gray dirty immune objects concurrently to reduce GC pause times. We re-process gray cards in
176 // the pause.
177 ReaderMutexLock mu(self, *Locks::mutator_lock_);
178 GrayAllDirtyImmuneObjects();
179 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800180 FlipThreadRoots();
181 {
182 ReaderMutexLock mu(self, *Locks::mutator_lock_);
183 MarkingPhase();
184 }
185 // Verify no from space refs. This causes a pause.
Andreas Gampee3ce7872017-02-22 13:36:21 -0800186 if (kEnableNoFromSpaceRefsVerification) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800187 TimingLogger::ScopedTiming split("(Paused)VerifyNoFromSpaceReferences", GetTimings());
Andreas Gampe4934eb12017-01-30 13:15:26 -0800188 ScopedPause pause(this, false);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700189 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800190 if (kVerboseMode) {
191 LOG(INFO) << "Verifying no from-space refs";
192 }
193 VerifyNoFromSpaceReferences();
Mathieu Chartier720e71a2015-04-06 17:10:58 -0700194 if (kVerboseMode) {
195 LOG(INFO) << "Done verifying no from-space refs";
196 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700197 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800198 }
199 {
200 ReaderMutexLock mu(self, *Locks::mutator_lock_);
201 ReclaimPhase();
202 }
203 FinishPhase();
204 CHECK(is_active_);
205 is_active_ = false;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700206 thread_running_gc_ = nullptr;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800207}
208
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700209class ConcurrentCopying::ActivateReadBarrierEntrypointsCheckpoint : public Closure {
210 public:
211 explicit ActivateReadBarrierEntrypointsCheckpoint(ConcurrentCopying* concurrent_copying)
212 : concurrent_copying_(concurrent_copying) {}
213
214 void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
215 // Note: self is not necessarily equal to thread since thread may be suspended.
216 Thread* self = Thread::Current();
217 DCHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
218 << thread->GetState() << " thread " << thread << " self " << self;
219 // Switch to the read barrier entrypoints.
220 thread->SetReadBarrierEntrypoints();
221 // If thread is a running mutator, then act on behalf of the garbage collector.
222 // See the code in ThreadList::RunCheckpoint.
223 concurrent_copying_->GetBarrier().Pass(self);
224 }
225
226 private:
227 ConcurrentCopying* const concurrent_copying_;
228};
229
230class ConcurrentCopying::ActivateReadBarrierEntrypointsCallback : public Closure {
231 public:
232 explicit ActivateReadBarrierEntrypointsCallback(ConcurrentCopying* concurrent_copying)
233 : concurrent_copying_(concurrent_copying) {}
234
235 void Run(Thread* self ATTRIBUTE_UNUSED) OVERRIDE REQUIRES(Locks::thread_list_lock_) {
236 // This needs to run under the thread_list_lock_ critical section in ThreadList::RunCheckpoint()
237 // to avoid a race with ThreadList::Register().
238 CHECK(!concurrent_copying_->is_using_read_barrier_entrypoints_);
239 concurrent_copying_->is_using_read_barrier_entrypoints_ = true;
240 }
241
242 private:
243 ConcurrentCopying* const concurrent_copying_;
244};
245
246void ConcurrentCopying::ActivateReadBarrierEntrypoints() {
247 Thread* const self = Thread::Current();
248 ActivateReadBarrierEntrypointsCheckpoint checkpoint(this);
249 ThreadList* thread_list = Runtime::Current()->GetThreadList();
250 gc_barrier_->Init(self, 0);
251 ActivateReadBarrierEntrypointsCallback callback(this);
252 const size_t barrier_count = thread_list->RunCheckpoint(&checkpoint, &callback);
253 // If there are no threads to wait which implies that all the checkpoint functions are finished,
254 // then no need to release the mutator lock.
255 if (barrier_count == 0) {
256 return;
257 }
258 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
259 gc_barrier_->Increment(self, barrier_count);
260}
261
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800262void ConcurrentCopying::BindBitmaps() {
263 Thread* self = Thread::Current();
264 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
265 // Mark all of the spaces we never collect as immune.
266 for (const auto& space : heap_->GetContinuousSpaces()) {
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800267 if (space->GetGcRetentionPolicy() == space::kGcRetentionPolicyNeverCollect ||
268 space->GetGcRetentionPolicy() == space::kGcRetentionPolicyFullCollect) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800269 CHECK(space->IsZygoteSpace() || space->IsImageSpace());
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800270 immune_spaces_.AddSpace(space);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800271 } else if (space == region_space_) {
Mathieu Chartier7ec38dc2016-10-07 15:24:46 -0700272 // It is OK to clear the bitmap with mutators running since the only place it is read is
273 // VisitObjects which has exclusion with CC.
274 region_space_bitmap_ = region_space_->GetMarkBitmap();
275 region_space_bitmap_->Clear();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800276 }
277 }
278}
279
280void ConcurrentCopying::InitializePhase() {
281 TimingLogger::ScopedTiming split("InitializePhase", GetTimings());
282 if (kVerboseMode) {
283 LOG(INFO) << "GC InitializePhase";
284 LOG(INFO) << "Region-space : " << reinterpret_cast<void*>(region_space_->Begin()) << "-"
285 << reinterpret_cast<void*>(region_space_->Limit());
286 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700287 CheckEmptyMarkStack();
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800288 if (kIsDebugBuild) {
289 MutexLock mu(Thread::Current(), mark_stack_lock_);
290 CHECK(false_gray_stack_.empty());
291 }
Mathieu Chartier56fe2582016-07-14 13:30:03 -0700292
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700293 rb_mark_bit_stack_full_ = false;
Mathieu Chartier56fe2582016-07-14 13:30:03 -0700294 mark_from_read_barrier_measurements_ = measure_read_barrier_slow_path_;
295 if (measure_read_barrier_slow_path_) {
Orion Hodson88591fe2018-03-06 13:35:43 +0000296 rb_slow_path_ns_.store(0, std::memory_order_relaxed);
297 rb_slow_path_count_.store(0, std::memory_order_relaxed);
298 rb_slow_path_count_gc_.store(0, std::memory_order_relaxed);
Mathieu Chartier56fe2582016-07-14 13:30:03 -0700299 }
300
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800301 immune_spaces_.Reset();
Orion Hodson88591fe2018-03-06 13:35:43 +0000302 bytes_moved_.store(0, std::memory_order_relaxed);
303 objects_moved_.store(0, std::memory_order_relaxed);
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -0800304 bytes_moved_gc_thread_ = 0;
305 objects_moved_gc_thread_ = 0;
Hiroshi Yamauchi60985b72016-08-24 13:53:12 -0700306 GcCause gc_cause = GetCurrentIteration()->GetGcCause();
307 if (gc_cause == kGcCauseExplicit ||
Hiroshi Yamauchi60985b72016-08-24 13:53:12 -0700308 gc_cause == kGcCauseCollectorTransition ||
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800309 GetCurrentIteration()->GetClearSoftReferences()) {
310 force_evacuate_all_ = true;
311 } else {
312 force_evacuate_all_ = false;
313 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700314 if (kUseBakerReadBarrier) {
Orion Hodson88591fe2018-03-06 13:35:43 +0000315 updated_all_immune_objects_.store(false, std::memory_order_relaxed);
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700316 // GC may gray immune objects in the thread flip.
317 gc_grays_immune_objects_ = true;
318 if (kIsDebugBuild) {
319 MutexLock mu(Thread::Current(), immune_gray_stack_lock_);
320 DCHECK(immune_gray_stack_.empty());
321 }
322 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800323 BindBitmaps();
324 if (kVerboseMode) {
325 LOG(INFO) << "force_evacuate_all=" << force_evacuate_all_;
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800326 LOG(INFO) << "Largest immune region: " << immune_spaces_.GetLargestImmuneRegion().Begin()
327 << "-" << immune_spaces_.GetLargestImmuneRegion().End();
328 for (space::ContinuousSpace* space : immune_spaces_.GetSpaces()) {
329 LOG(INFO) << "Immune space: " << *space;
330 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800331 LOG(INFO) << "GC end of InitializePhase";
332 }
Mathieu Chartier962cd7a2016-08-16 12:15:59 -0700333 // Mark all of the zygote large objects without graying them.
334 MarkZygoteLargeObjects();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800335}
336
337// Used to switch the thread roots of a thread from from-space refs to to-space refs.
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700338class ConcurrentCopying::ThreadFlipVisitor : public Closure, public RootVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800339 public:
Roland Levillain3887c462015-08-12 18:15:42 +0100340 ThreadFlipVisitor(ConcurrentCopying* concurrent_copying, bool use_tlab)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800341 : concurrent_copying_(concurrent_copying), use_tlab_(use_tlab) {
342 }
343
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700344 virtual void Run(Thread* thread) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800345 // Note: self is not necessarily equal to thread since thread may be suspended.
346 Thread* self = Thread::Current();
347 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
348 << thread->GetState() << " thread " << thread << " self " << self;
Mathieu Chartierfe814e82016-11-09 14:32:49 -0800349 thread->SetIsGcMarkingAndUpdateEntrypoints(true);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800350 if (use_tlab_ && thread->HasTlab()) {
351 if (ConcurrentCopying::kEnableFromSpaceAccountingCheck) {
352 // This must come before the revoke.
353 size_t thread_local_objects = thread->GetThreadLocalObjectsAllocated();
354 concurrent_copying_->region_space_->RevokeThreadLocalBuffers(thread);
Roland Levillain2ae376f2018-01-30 11:35:11 +0000355 reinterpret_cast<Atomic<size_t>*>(
356 &concurrent_copying_->from_space_num_objects_at_first_pause_)->
Orion Hodson88591fe2018-03-06 13:35:43 +0000357 fetch_add(thread_local_objects, std::memory_order_seq_cst);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800358 } else {
359 concurrent_copying_->region_space_->RevokeThreadLocalBuffers(thread);
360 }
361 }
362 if (kUseThreadLocalAllocationStack) {
363 thread->RevokeThreadLocalAllocationStack();
364 }
365 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700366 // We can use the non-CAS VisitRoots functions below because we update thread-local GC roots
367 // only.
Andreas Gampe513061a2017-06-01 09:17:34 -0700368 thread->VisitRoots(this, kVisitRootFlagAllRoots);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800369 concurrent_copying_->GetBarrier().Pass(self);
370 }
371
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700372 void VisitRoots(mirror::Object*** roots,
373 size_t count,
374 const RootInfo& info ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700375 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -0800376 Thread* self = Thread::Current();
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700377 for (size_t i = 0; i < count; ++i) {
378 mirror::Object** root = roots[i];
379 mirror::Object* ref = *root;
380 if (ref != nullptr) {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -0800381 mirror::Object* to_ref = concurrent_copying_->Mark(self, ref);
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700382 if (to_ref != ref) {
383 *root = to_ref;
384 }
385 }
386 }
387 }
388
389 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots,
390 size_t count,
391 const RootInfo& info ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700392 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -0800393 Thread* self = Thread::Current();
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700394 for (size_t i = 0; i < count; ++i) {
395 mirror::CompressedReference<mirror::Object>* const root = roots[i];
396 if (!root->IsNull()) {
397 mirror::Object* ref = root->AsMirrorPtr();
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -0800398 mirror::Object* to_ref = concurrent_copying_->Mark(self, ref);
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700399 if (to_ref != ref) {
400 root->Assign(to_ref);
401 }
402 }
403 }
404 }
405
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800406 private:
407 ConcurrentCopying* const concurrent_copying_;
408 const bool use_tlab_;
409};
410
411// Called back from Runtime::FlipThreadRoots() during a pause.
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700412class ConcurrentCopying::FlipCallback : public Closure {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800413 public:
414 explicit FlipCallback(ConcurrentCopying* concurrent_copying)
415 : concurrent_copying_(concurrent_copying) {
416 }
417
Mathieu Chartier90443472015-07-16 20:32:27 -0700418 virtual void Run(Thread* thread) OVERRIDE REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800419 ConcurrentCopying* cc = concurrent_copying_;
420 TimingLogger::ScopedTiming split("(Paused)FlipCallback", cc->GetTimings());
421 // Note: self is not necessarily equal to thread since thread may be suspended.
422 Thread* self = Thread::Current();
Mathieu Chartiera1467d02017-02-22 09:22:50 -0800423 if (kVerifyNoMissingCardMarks) {
424 cc->VerifyNoMissingCardMarks();
425 }
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700426 CHECK_EQ(thread, self);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800427 Locks::mutator_lock_->AssertExclusiveHeld(self);
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700428 {
429 TimingLogger::ScopedTiming split2("(Paused)SetFromSpace", cc->GetTimings());
430 cc->region_space_->SetFromSpace(cc->rb_table_, cc->force_evacuate_all_);
431 }
Mathieu Chartiera4f6af92015-08-11 17:35:25 -0700432 cc->SwapStacks();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800433 if (ConcurrentCopying::kEnableFromSpaceAccountingCheck) {
434 cc->RecordLiveStackFreezeSize(self);
435 cc->from_space_num_objects_at_first_pause_ = cc->region_space_->GetObjectsAllocated();
436 cc->from_space_num_bytes_at_first_pause_ = cc->region_space_->GetBytesAllocated();
437 }
438 cc->is_marking_ = true;
Orion Hodson88591fe2018-03-06 13:35:43 +0000439 cc->mark_stack_mode_.store(ConcurrentCopying::kMarkStackModeThreadLocal,
440 std::memory_order_relaxed);
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800441 if (kIsDebugBuild) {
442 cc->region_space_->AssertAllRegionLiveBytesZeroOrCleared();
443 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800444 if (UNLIKELY(Runtime::Current()->IsActiveTransaction())) {
Mathieu Chartier184c9dc2015-03-05 13:20:54 -0800445 CHECK(Runtime::Current()->IsAotCompiler());
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700446 TimingLogger::ScopedTiming split3("(Paused)VisitTransactionRoots", cc->GetTimings());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700447 Runtime::Current()->VisitTransactionRoots(cc);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800448 }
Mathieu Chartier21328a12016-07-22 10:47:45 -0700449 if (kUseBakerReadBarrier && kGrayDirtyImmuneObjects) {
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700450 cc->GrayAllNewlyDirtyImmuneObjects();
Mathieu Chartier21328a12016-07-22 10:47:45 -0700451 if (kIsDebugBuild) {
Roland Levillain001eff92018-01-24 14:24:33 +0000452 // Check that all non-gray immune objects only reference immune objects.
Mathieu Chartier21328a12016-07-22 10:47:45 -0700453 cc->VerifyGrayImmuneObjects();
454 }
455 }
Mathieu Chartier9aef9922017-04-23 13:53:50 -0700456 // May be null during runtime creation, in this case leave java_lang_Object null.
457 // This is safe since single threaded behavior should mean FillDummyObject does not
458 // happen when java_lang_Object_ is null.
459 if (WellKnownClasses::java_lang_Object != nullptr) {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -0800460 cc->java_lang_Object_ = down_cast<mirror::Class*>(cc->Mark(thread,
Mathieu Chartier9aef9922017-04-23 13:53:50 -0700461 WellKnownClasses::ToClass(WellKnownClasses::java_lang_Object).Ptr()));
462 } else {
463 cc->java_lang_Object_ = nullptr;
464 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800465 }
466
467 private:
468 ConcurrentCopying* const concurrent_copying_;
469};
470
Mathieu Chartier21328a12016-07-22 10:47:45 -0700471class ConcurrentCopying::VerifyGrayImmuneObjectsVisitor {
472 public:
473 explicit VerifyGrayImmuneObjectsVisitor(ConcurrentCopying* collector)
474 : collector_(collector) {}
475
Mathieu Chartier31e88222016-10-14 18:43:19 -0700476 void operator()(ObjPtr<mirror::Object> obj, MemberOffset offset, bool /* is_static */)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700477 const ALWAYS_INLINE REQUIRES_SHARED(Locks::mutator_lock_)
478 REQUIRES_SHARED(Locks::heap_bitmap_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700479 CheckReference(obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(offset),
480 obj, offset);
481 }
482
Mathieu Chartier31e88222016-10-14 18:43:19 -0700483 void operator()(ObjPtr<mirror::Class> klass, ObjPtr<mirror::Reference> ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700484 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700485 CHECK(klass->IsTypeOfReferenceClass());
486 CheckReference(ref->GetReferent<kWithoutReadBarrier>(),
487 ref,
488 mirror::Reference::ReferentOffset());
489 }
490
491 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
492 ALWAYS_INLINE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700493 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700494 if (!root->IsNull()) {
495 VisitRoot(root);
496 }
497 }
498
499 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
500 ALWAYS_INLINE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700501 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700502 CheckReference(root->AsMirrorPtr(), nullptr, MemberOffset(0));
503 }
504
505 private:
506 ConcurrentCopying* const collector_;
507
Mathieu Chartier31e88222016-10-14 18:43:19 -0700508 void CheckReference(ObjPtr<mirror::Object> ref,
509 ObjPtr<mirror::Object> holder,
510 MemberOffset offset) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700511 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700512 if (ref != nullptr) {
Mathieu Chartier31e88222016-10-14 18:43:19 -0700513 if (!collector_->immune_spaces_.ContainsObject(ref.Ptr())) {
Mathieu Chartier962cd7a2016-08-16 12:15:59 -0700514 // Not immune, must be a zygote large object.
515 CHECK(Runtime::Current()->GetHeap()->GetLargeObjectsSpace()->IsZygoteLargeObject(
Mathieu Chartier31e88222016-10-14 18:43:19 -0700516 Thread::Current(), ref.Ptr()))
Mathieu Chartier962cd7a2016-08-16 12:15:59 -0700517 << "Non gray object references non immune, non zygote large object "<< ref << " "
David Sehr709b0702016-10-13 09:12:37 -0700518 << mirror::Object::PrettyTypeOf(ref) << " in holder " << holder << " "
519 << mirror::Object::PrettyTypeOf(holder) << " offset=" << offset.Uint32Value();
Mathieu Chartier962cd7a2016-08-16 12:15:59 -0700520 } else {
521 // Make sure the large object class is immune since we will never scan the large object.
522 CHECK(collector_->immune_spaces_.ContainsObject(
523 ref->GetClass<kVerifyNone, kWithoutReadBarrier>()));
524 }
Mathieu Chartier21328a12016-07-22 10:47:45 -0700525 }
526 }
527};
528
529void ConcurrentCopying::VerifyGrayImmuneObjects() {
530 TimingLogger::ScopedTiming split(__FUNCTION__, GetTimings());
531 for (auto& space : immune_spaces_.GetSpaces()) {
532 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
533 accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
534 VerifyGrayImmuneObjectsVisitor visitor(this);
535 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()),
536 reinterpret_cast<uintptr_t>(space->Limit()),
537 [&visitor](mirror::Object* obj)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700538 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700539 // If an object is not gray, it should only have references to things in the immune spaces.
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700540 if (obj->GetReadBarrierState() != ReadBarrier::GrayState()) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700541 obj->VisitReferences</*kVisitNativeRoots*/true,
542 kDefaultVerifyFlags,
543 kWithoutReadBarrier>(visitor, visitor);
544 }
545 });
546 }
547}
548
Mathieu Chartiera1467d02017-02-22 09:22:50 -0800549class ConcurrentCopying::VerifyNoMissingCardMarkVisitor {
550 public:
551 VerifyNoMissingCardMarkVisitor(ConcurrentCopying* cc, ObjPtr<mirror::Object> holder)
552 : cc_(cc),
553 holder_(holder) {}
554
555 void operator()(ObjPtr<mirror::Object> obj,
556 MemberOffset offset,
557 bool is_static ATTRIBUTE_UNUSED) const
558 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
559 if (offset.Uint32Value() != mirror::Object::ClassOffset().Uint32Value()) {
560 CheckReference(obj->GetFieldObject<mirror::Object, kDefaultVerifyFlags, kWithoutReadBarrier>(
561 offset), offset.Uint32Value());
562 }
563 }
564 void operator()(ObjPtr<mirror::Class> klass,
565 ObjPtr<mirror::Reference> ref) const
566 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
567 CHECK(klass->IsTypeOfReferenceClass());
568 this->operator()(ref, mirror::Reference::ReferentOffset(), false);
569 }
570
571 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
572 REQUIRES_SHARED(Locks::mutator_lock_) {
573 if (!root->IsNull()) {
574 VisitRoot(root);
575 }
576 }
577
578 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
579 REQUIRES_SHARED(Locks::mutator_lock_) {
580 CheckReference(root->AsMirrorPtr());
581 }
582
583 void CheckReference(mirror::Object* ref, int32_t offset = -1) const
584 REQUIRES_SHARED(Locks::mutator_lock_) {
585 CHECK(ref == nullptr || !cc_->region_space_->IsInNewlyAllocatedRegion(ref))
586 << holder_->PrettyTypeOf() << "(" << holder_.Ptr() << ") references object "
587 << ref->PrettyTypeOf() << "(" << ref << ") in newly allocated region at offset=" << offset;
588 }
589
590 private:
591 ConcurrentCopying* const cc_;
592 ObjPtr<mirror::Object> const holder_;
593};
594
Mathieu Chartiera1467d02017-02-22 09:22:50 -0800595void ConcurrentCopying::VerifyNoMissingCardMarks() {
Andreas Gampe0c183382017-07-13 22:26:24 -0700596 auto visitor = [&](mirror::Object* obj)
597 REQUIRES(Locks::mutator_lock_)
598 REQUIRES(!mark_stack_lock_) {
599 // Objects not on dirty or aged cards should never have references to newly allocated regions.
600 if (heap_->GetCardTable()->GetCard(obj) == gc::accounting::CardTable::kCardClean) {
601 VerifyNoMissingCardMarkVisitor internal_visitor(this, /*holder*/ obj);
602 obj->VisitReferences</*kVisitNativeRoots*/true, kVerifyNone, kWithoutReadBarrier>(
603 internal_visitor, internal_visitor);
604 }
605 };
Mathieu Chartiera1467d02017-02-22 09:22:50 -0800606 TimingLogger::ScopedTiming split(__FUNCTION__, GetTimings());
Andreas Gampe0c183382017-07-13 22:26:24 -0700607 region_space_->Walk(visitor);
Mathieu Chartiera1467d02017-02-22 09:22:50 -0800608 {
609 ReaderMutexLock rmu(Thread::Current(), *Locks::heap_bitmap_lock_);
Andreas Gampe0c183382017-07-13 22:26:24 -0700610 heap_->GetLiveBitmap()->Visit(visitor);
Mathieu Chartiera1467d02017-02-22 09:22:50 -0800611 }
612}
613
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800614// Switch threads that from from-space to to-space refs. Forward/mark the thread roots.
615void ConcurrentCopying::FlipThreadRoots() {
616 TimingLogger::ScopedTiming split("FlipThreadRoots", GetTimings());
617 if (kVerboseMode) {
618 LOG(INFO) << "time=" << region_space_->Time();
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700619 region_space_->DumpNonFreeRegions(LOG_STREAM(INFO));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800620 }
621 Thread* self = Thread::Current();
622 Locks::mutator_lock_->AssertNotHeld(self);
623 gc_barrier_->Init(self, 0);
624 ThreadFlipVisitor thread_flip_visitor(this, heap_->use_tlab_);
625 FlipCallback flip_callback(this);
Andreas Gampe4934eb12017-01-30 13:15:26 -0800626
Andreas Gampe6e644452017-05-09 16:30:27 -0700627 size_t barrier_count = Runtime::Current()->GetThreadList()->FlipThreadRoots(
628 &thread_flip_visitor, &flip_callback, this, GetHeap()->GetGcPauseListener());
Andreas Gampe4934eb12017-01-30 13:15:26 -0800629
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800630 {
631 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
632 gc_barrier_->Increment(self, barrier_count);
633 }
634 is_asserting_to_space_invariant_ = true;
635 QuasiAtomic::ThreadFenceForConstructor();
636 if (kVerboseMode) {
637 LOG(INFO) << "time=" << region_space_->Time();
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700638 region_space_->DumpNonFreeRegions(LOG_STREAM(INFO));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800639 LOG(INFO) << "GC end of FlipThreadRoots";
640 }
641}
642
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700643template <bool kConcurrent>
Mathieu Chartier21328a12016-07-22 10:47:45 -0700644class ConcurrentCopying::GrayImmuneObjectVisitor {
645 public:
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700646 explicit GrayImmuneObjectVisitor(Thread* self) : self_(self) {}
Mathieu Chartier21328a12016-07-22 10:47:45 -0700647
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700648 ALWAYS_INLINE void operator()(mirror::Object* obj) const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700649 if (kUseBakerReadBarrier && obj->GetReadBarrierState() == ReadBarrier::WhiteState()) {
650 if (kConcurrent) {
651 Locks::mutator_lock_->AssertSharedHeld(self_);
652 obj->AtomicSetReadBarrierState(ReadBarrier::WhiteState(), ReadBarrier::GrayState());
653 // Mod union table VisitObjects may visit the same object multiple times so we can't check
654 // the result of the atomic set.
655 } else {
656 Locks::mutator_lock_->AssertExclusiveHeld(self_);
657 obj->SetReadBarrierState(ReadBarrier::GrayState());
Mathieu Chartier21328a12016-07-22 10:47:45 -0700658 }
Mathieu Chartier21328a12016-07-22 10:47:45 -0700659 }
660 }
661
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700662 static void Callback(mirror::Object* obj, void* arg) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700663 reinterpret_cast<GrayImmuneObjectVisitor<kConcurrent>*>(arg)->operator()(obj);
Mathieu Chartier21328a12016-07-22 10:47:45 -0700664 }
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700665
666 private:
667 Thread* const self_;
Mathieu Chartier21328a12016-07-22 10:47:45 -0700668};
669
670void ConcurrentCopying::GrayAllDirtyImmuneObjects() {
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700671 TimingLogger::ScopedTiming split("GrayAllDirtyImmuneObjects", GetTimings());
672 accounting::CardTable* const card_table = heap_->GetCardTable();
673 Thread* const self = Thread::Current();
674 using VisitorType = GrayImmuneObjectVisitor</* kIsConcurrent */ true>;
675 VisitorType visitor(self);
676 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier21328a12016-07-22 10:47:45 -0700677 for (space::ContinuousSpace* space : immune_spaces_.GetSpaces()) {
678 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700679 accounting::ModUnionTable* table = heap_->FindModUnionTableFromSpace(space);
Mathieu Chartier21328a12016-07-22 10:47:45 -0700680 // Mark all the objects on dirty cards since these may point to objects in other space.
681 // Once these are marked, the GC will eventually clear them later.
682 // Table is non null for boot image and zygote spaces. It is only null for application image
683 // spaces.
684 if (table != nullptr) {
Mathieu Chartier6e6078a2016-10-24 15:45:41 -0700685 table->ProcessCards();
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700686 table->VisitObjects(&VisitorType::Callback, &visitor);
687 // Don't clear cards here since we need to rescan in the pause. If we cleared the cards here,
688 // there would be races with the mutator marking new cards.
689 } else {
690 // Keep cards aged if we don't have a mod-union table since we may need to scan them in future
691 // GCs. This case is for app images.
692 card_table->ModifyCardsAtomic(
693 space->Begin(),
694 space->End(),
695 [](uint8_t card) {
696 return (card != gc::accounting::CardTable::kCardClean)
697 ? gc::accounting::CardTable::kCardAged
698 : card;
699 },
700 /* card modified visitor */ VoidFunctor());
701 card_table->Scan</* kClearCard */ false>(space->GetMarkBitmap(),
702 space->Begin(),
703 space->End(),
704 visitor,
705 gc::accounting::CardTable::kCardAged);
706 }
707 }
708}
709
710void ConcurrentCopying::GrayAllNewlyDirtyImmuneObjects() {
711 TimingLogger::ScopedTiming split("(Paused)GrayAllNewlyDirtyImmuneObjects", GetTimings());
712 accounting::CardTable* const card_table = heap_->GetCardTable();
713 using VisitorType = GrayImmuneObjectVisitor</* kIsConcurrent */ false>;
714 Thread* const self = Thread::Current();
715 VisitorType visitor(self);
716 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
717 for (space::ContinuousSpace* space : immune_spaces_.GetSpaces()) {
718 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
719 accounting::ModUnionTable* table = heap_->FindModUnionTableFromSpace(space);
720
721 // Don't need to scan aged cards since we did these before the pause. Note that scanning cards
722 // also handles the mod-union table cards.
723 card_table->Scan</* kClearCard */ false>(space->GetMarkBitmap(),
724 space->Begin(),
725 space->End(),
726 visitor,
727 gc::accounting::CardTable::kCardDirty);
728 if (table != nullptr) {
729 // Add the cards to the mod-union table so that we can clear cards to save RAM.
730 table->ProcessCards();
Mathieu Chartier6e6078a2016-10-24 15:45:41 -0700731 TimingLogger::ScopedTiming split2("(Paused)ClearCards", GetTimings());
732 card_table->ClearCardRange(space->Begin(),
733 AlignDown(space->End(), accounting::CardTable::kCardSize));
Mathieu Chartier21328a12016-07-22 10:47:45 -0700734 }
735 }
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700736 // Since all of the objects that may point to other spaces are gray, we can avoid all the read
Mathieu Chartier21328a12016-07-22 10:47:45 -0700737 // barriers in the immune spaces.
Orion Hodson88591fe2018-03-06 13:35:43 +0000738 updated_all_immune_objects_.store(true, std::memory_order_relaxed);
Mathieu Chartier21328a12016-07-22 10:47:45 -0700739}
740
Mathieu Chartiera4f6af92015-08-11 17:35:25 -0700741void ConcurrentCopying::SwapStacks() {
742 heap_->SwapStacks();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800743}
744
745void ConcurrentCopying::RecordLiveStackFreezeSize(Thread* self) {
746 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
747 live_stack_freeze_size_ = heap_->GetLiveStack()->Size();
748}
749
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700750// Used to visit objects in the immune spaces.
751inline void ConcurrentCopying::ScanImmuneObject(mirror::Object* obj) {
752 DCHECK(obj != nullptr);
753 DCHECK(immune_spaces_.ContainsObject(obj));
754 // Update the fields without graying it or pushing it onto the mark stack.
755 Scan(obj);
756}
757
758class ConcurrentCopying::ImmuneSpaceScanObjVisitor {
759 public:
760 explicit ImmuneSpaceScanObjVisitor(ConcurrentCopying* cc)
761 : collector_(cc) {}
762
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700763 ALWAYS_INLINE void operator()(mirror::Object* obj) const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700764 if (kUseBakerReadBarrier && kGrayDirtyImmuneObjects) {
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700765 // Only need to scan gray objects.
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700766 if (obj->GetReadBarrierState() == ReadBarrier::GrayState()) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700767 collector_->ScanImmuneObject(obj);
768 // Done scanning the object, go back to white.
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700769 bool success = obj->AtomicSetReadBarrierState(ReadBarrier::GrayState(),
770 ReadBarrier::WhiteState());
Mathieu Chartier2af7a3e2017-12-14 18:36:05 -0800771 CHECK(success)
772 << Runtime::Current()->GetHeap()->GetVerification()->DumpObjectInfo(obj, "failed CAS");
Mathieu Chartier21328a12016-07-22 10:47:45 -0700773 }
774 } else {
775 collector_->ScanImmuneObject(obj);
776 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700777 }
778
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700779 static void Callback(mirror::Object* obj, void* arg) REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi5408f232016-07-29 15:07:05 -0700780 reinterpret_cast<ImmuneSpaceScanObjVisitor*>(arg)->operator()(obj);
781 }
782
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700783 private:
784 ConcurrentCopying* const collector_;
785};
786
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800787// Concurrently mark roots that are guarded by read barriers and process the mark stack.
788void ConcurrentCopying::MarkingPhase() {
789 TimingLogger::ScopedTiming split("MarkingPhase", GetTimings());
790 if (kVerboseMode) {
791 LOG(INFO) << "GC MarkingPhase";
792 }
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -0700793 Thread* self = Thread::Current();
794 if (kIsDebugBuild) {
795 MutexLock mu(self, *Locks::thread_list_lock_);
796 CHECK(weak_ref_access_enabled_);
797 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700798
799 // Scan immune spaces.
800 // Update all the fields in the immune spaces first without graying the objects so that we
801 // minimize dirty pages in the immune spaces. Note mutators can concurrently access and gray some
802 // of the objects.
803 if (kUseBakerReadBarrier) {
804 gc_grays_immune_objects_ = false;
Hiroshi Yamauchi16292fc2016-06-20 20:23:34 -0700805 }
Mathieu Chartier21328a12016-07-22 10:47:45 -0700806 {
807 TimingLogger::ScopedTiming split2("ScanImmuneSpaces", GetTimings());
808 for (auto& space : immune_spaces_.GetSpaces()) {
809 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
810 accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
Hiroshi Yamauchi5408f232016-07-29 15:07:05 -0700811 accounting::ModUnionTable* table = heap_->FindModUnionTableFromSpace(space);
Mathieu Chartier21328a12016-07-22 10:47:45 -0700812 ImmuneSpaceScanObjVisitor visitor(this);
Hiroshi Yamauchi5408f232016-07-29 15:07:05 -0700813 if (kUseBakerReadBarrier && kGrayDirtyImmuneObjects && table != nullptr) {
814 table->VisitObjects(ImmuneSpaceScanObjVisitor::Callback, &visitor);
815 } else {
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700816 // TODO: Scan only the aged cards.
Hiroshi Yamauchi5408f232016-07-29 15:07:05 -0700817 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()),
818 reinterpret_cast<uintptr_t>(space->Limit()),
819 visitor);
820 }
Mathieu Chartier21328a12016-07-22 10:47:45 -0700821 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700822 }
823 if (kUseBakerReadBarrier) {
824 // This release fence makes the field updates in the above loop visible before allowing mutator
825 // getting access to immune objects without graying it first.
Orion Hodson88591fe2018-03-06 13:35:43 +0000826 updated_all_immune_objects_.store(true, std::memory_order_release);
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700827 // Now whiten immune objects concurrently accessed and grayed by mutators. We can't do this in
828 // the above loop because we would incorrectly disable the read barrier by whitening an object
829 // which may point to an unscanned, white object, breaking the to-space invariant.
830 //
831 // Make sure no mutators are in the middle of marking an immune object before whitening immune
832 // objects.
833 IssueEmptyCheckpoint();
834 MutexLock mu(Thread::Current(), immune_gray_stack_lock_);
835 if (kVerboseMode) {
836 LOG(INFO) << "immune gray stack size=" << immune_gray_stack_.size();
837 }
838 for (mirror::Object* obj : immune_gray_stack_) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700839 DCHECK(obj->GetReadBarrierState() == ReadBarrier::GrayState());
840 bool success = obj->AtomicSetReadBarrierState(ReadBarrier::GrayState(),
841 ReadBarrier::WhiteState());
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700842 DCHECK(success);
843 }
844 immune_gray_stack_.clear();
845 }
846
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800847 {
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -0700848 TimingLogger::ScopedTiming split2("VisitConcurrentRoots", GetTimings());
849 Runtime::Current()->VisitConcurrentRoots(this, kVisitRootFlagAllRoots);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800850 }
851 {
852 // TODO: don't visit the transaction roots if it's not active.
853 TimingLogger::ScopedTiming split5("VisitNonThreadRoots", GetTimings());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700854 Runtime::Current()->VisitNonThreadRoots(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800855 }
856
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800857 {
Mathieu Chartiera6b1ead2015-10-06 10:32:38 -0700858 TimingLogger::ScopedTiming split7("ProcessMarkStack", GetTimings());
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700859 // We transition through three mark stack modes (thread-local, shared, GC-exclusive). The
860 // primary reasons are the fact that we need to use a checkpoint to process thread-local mark
861 // stacks, but after we disable weak refs accesses, we can't use a checkpoint due to a deadlock
862 // issue because running threads potentially blocking at WaitHoldingLocks, and that once we
863 // reach the point where we process weak references, we can avoid using a lock when accessing
864 // the GC mark stack, which makes mark stack processing more efficient.
865
866 // Process the mark stack once in the thread local stack mode. This marks most of the live
867 // objects, aside from weak ref accesses with read barriers (Reference::GetReferent() and system
868 // weaks) that may happen concurrently while we processing the mark stack and newly mark/gray
869 // objects and push refs on the mark stack.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800870 ProcessMarkStack();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700871 // Switch to the shared mark stack mode. That is, revoke and process thread-local mark stacks
872 // for the last time before transitioning to the shared mark stack mode, which would process new
873 // refs that may have been concurrently pushed onto the mark stack during the ProcessMarkStack()
874 // call above. At the same time, disable weak ref accesses using a per-thread flag. It's
875 // important to do these together in a single checkpoint so that we can ensure that mutators
876 // won't newly gray objects and push new refs onto the mark stack due to weak ref accesses and
877 // mutators safely transition to the shared mark stack mode (without leaving unprocessed refs on
878 // the thread-local mark stacks), without a race. This is why we use a thread-local weak ref
879 // access flag Thread::tls32_.weak_ref_access_enabled_ instead of the global ones.
880 SwitchToSharedMarkStackMode();
881 CHECK(!self->GetWeakRefAccessEnabled());
882 // Now that weak refs accesses are disabled, once we exhaust the shared mark stack again here
883 // (which may be non-empty if there were refs found on thread-local mark stacks during the above
884 // SwitchToSharedMarkStackMode() call), we won't have new refs to process, that is, mutators
885 // (via read barriers) have no way to produce any more refs to process. Marking converges once
886 // before we process weak refs below.
887 ProcessMarkStack();
888 CheckEmptyMarkStack();
889 // Switch to the GC exclusive mark stack mode so that we can process the mark stack without a
890 // lock from this point on.
891 SwitchToGcExclusiveMarkStackMode();
892 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800893 if (kVerboseMode) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800894 LOG(INFO) << "ProcessReferences";
895 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700896 // Process weak references. This may produce new refs to process and have them processed via
Mathieu Chartier97509952015-07-13 14:35:43 -0700897 // ProcessMarkStack (in the GC exclusive mark stack mode).
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700898 ProcessReferences(self);
899 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800900 if (kVerboseMode) {
901 LOG(INFO) << "SweepSystemWeaks";
902 }
903 SweepSystemWeaks(self);
904 if (kVerboseMode) {
905 LOG(INFO) << "SweepSystemWeaks done";
906 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700907 // Process the mark stack here one last time because the above SweepSystemWeaks() call may have
908 // marked some objects (strings alive) as hash_set::Erase() can call the hash function for
909 // arbitrary elements in the weak intern table in InternTable::Table::SweepWeaks().
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800910 ProcessMarkStack();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700911 CheckEmptyMarkStack();
912 // Re-enable weak ref accesses.
913 ReenableWeakRefAccess(self);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -0700914 // Free data for class loaders that we unloaded.
915 Runtime::Current()->GetClassLinker()->CleanupClassLoaders();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700916 // Marking is done. Disable marking.
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700917 DisableMarking();
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800918 if (kUseBakerReadBarrier) {
919 ProcessFalseGrayStack();
920 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700921 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800922 }
923
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -0700924 if (kIsDebugBuild) {
925 MutexLock mu(self, *Locks::thread_list_lock_);
926 CHECK(weak_ref_access_enabled_);
927 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800928 if (kVerboseMode) {
929 LOG(INFO) << "GC end of MarkingPhase";
930 }
931}
932
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700933void ConcurrentCopying::ReenableWeakRefAccess(Thread* self) {
934 if (kVerboseMode) {
935 LOG(INFO) << "ReenableWeakRefAccess";
936 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700937 // Iterate all threads (don't need to or can't use a checkpoint) and re-enable weak ref access.
938 {
939 MutexLock mu(self, *Locks::thread_list_lock_);
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -0700940 weak_ref_access_enabled_ = true; // This is for new threads.
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700941 std::list<Thread*> thread_list = Runtime::Current()->GetThreadList()->GetList();
942 for (Thread* thread : thread_list) {
943 thread->SetWeakRefAccessEnabled(true);
944 }
945 }
946 // Unblock blocking threads.
947 GetHeap()->GetReferenceProcessor()->BroadcastForSlowPath(self);
948 Runtime::Current()->BroadcastForNewSystemWeaks();
949}
950
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700951class ConcurrentCopying::DisableMarkingCheckpoint : public Closure {
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700952 public:
953 explicit DisableMarkingCheckpoint(ConcurrentCopying* concurrent_copying)
954 : concurrent_copying_(concurrent_copying) {
955 }
956
957 void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
958 // Note: self is not necessarily equal to thread since thread may be suspended.
959 Thread* self = Thread::Current();
960 DCHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
961 << thread->GetState() << " thread " << thread << " self " << self;
962 // Disable the thread-local is_gc_marking flag.
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -0700963 // Note a thread that has just started right before this checkpoint may have already this flag
964 // set to false, which is ok.
Mathieu Chartierfe814e82016-11-09 14:32:49 -0800965 thread->SetIsGcMarkingAndUpdateEntrypoints(false);
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700966 // If thread is a running mutator, then act on behalf of the garbage collector.
967 // See the code in ThreadList::RunCheckpoint.
Mathieu Chartier10d25082015-10-28 18:36:09 -0700968 concurrent_copying_->GetBarrier().Pass(self);
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700969 }
970
971 private:
972 ConcurrentCopying* const concurrent_copying_;
973};
974
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -0700975class ConcurrentCopying::DisableMarkingCallback : public Closure {
976 public:
977 explicit DisableMarkingCallback(ConcurrentCopying* concurrent_copying)
978 : concurrent_copying_(concurrent_copying) {
979 }
980
981 void Run(Thread* self ATTRIBUTE_UNUSED) OVERRIDE REQUIRES(Locks::thread_list_lock_) {
982 // This needs to run under the thread_list_lock_ critical section in ThreadList::RunCheckpoint()
983 // to avoid a race with ThreadList::Register().
984 CHECK(concurrent_copying_->is_marking_);
985 concurrent_copying_->is_marking_ = false;
Mathieu Chartiera9a4f5f2017-05-03 18:19:13 -0700986 if (kUseBakerReadBarrier && kGrayDirtyImmuneObjects) {
987 CHECK(concurrent_copying_->is_using_read_barrier_entrypoints_);
988 concurrent_copying_->is_using_read_barrier_entrypoints_ = false;
989 } else {
990 CHECK(!concurrent_copying_->is_using_read_barrier_entrypoints_);
991 }
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -0700992 }
993
994 private:
995 ConcurrentCopying* const concurrent_copying_;
996};
997
Hiroshi Yamauchi00370822015-08-18 14:47:25 -0700998void ConcurrentCopying::IssueDisableMarkingCheckpoint() {
999 Thread* self = Thread::Current();
1000 DisableMarkingCheckpoint check_point(this);
1001 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1002 gc_barrier_->Init(self, 0);
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001003 DisableMarkingCallback dmc(this);
1004 size_t barrier_count = thread_list->RunCheckpoint(&check_point, &dmc);
Hiroshi Yamauchi00370822015-08-18 14:47:25 -07001005 // If there are no threads to wait which implies that all the checkpoint functions are finished,
1006 // then no need to release the mutator lock.
1007 if (barrier_count == 0) {
1008 return;
1009 }
1010 // Release locks then wait for all mutator threads to pass the barrier.
1011 Locks::mutator_lock_->SharedUnlock(self);
1012 {
1013 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
1014 gc_barrier_->Increment(self, barrier_count);
1015 }
1016 Locks::mutator_lock_->SharedLock(self);
1017}
1018
1019void ConcurrentCopying::DisableMarking() {
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001020 // Use a checkpoint to turn off the global is_marking and the thread-local is_gc_marking flags and
1021 // to ensure no threads are still in the middle of a read barrier which may have a from-space ref
1022 // cached in a local variable.
Hiroshi Yamauchi00370822015-08-18 14:47:25 -07001023 IssueDisableMarkingCheckpoint();
1024 if (kUseTableLookupReadBarrier) {
1025 heap_->rb_table_->ClearAll();
1026 DCHECK(heap_->rb_table_->IsAllCleared());
1027 }
Orion Hodson88591fe2018-03-06 13:35:43 +00001028 is_mark_stack_push_disallowed_.store(1, std::memory_order_seq_cst);
1029 mark_stack_mode_.store(kMarkStackModeOff, std::memory_order_seq_cst);
Hiroshi Yamauchi00370822015-08-18 14:47:25 -07001030}
1031
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08001032void ConcurrentCopying::PushOntoFalseGrayStack(Thread* const self, mirror::Object* ref) {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001033 CHECK(kUseBakerReadBarrier);
1034 DCHECK(ref != nullptr);
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08001035 MutexLock mu(self, mark_stack_lock_);
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001036 false_gray_stack_.push_back(ref);
1037}
1038
1039void ConcurrentCopying::ProcessFalseGrayStack() {
1040 CHECK(kUseBakerReadBarrier);
1041 // Change the objects on the false gray stack from gray to white.
1042 MutexLock mu(Thread::Current(), mark_stack_lock_);
1043 for (mirror::Object* obj : false_gray_stack_) {
1044 DCHECK(IsMarked(obj));
1045 // The object could be white here if a thread got preempted after a success at the
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001046 // AtomicSetReadBarrierState in Mark(), GC started marking through it (but not finished so
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001047 // still gray), and the thread ran to register it onto the false gray stack.
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001048 if (obj->GetReadBarrierState() == ReadBarrier::GrayState()) {
1049 bool success = obj->AtomicSetReadBarrierState(ReadBarrier::GrayState(),
1050 ReadBarrier::WhiteState());
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001051 DCHECK(success);
1052 }
1053 }
1054 false_gray_stack_.clear();
1055}
1056
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001057void ConcurrentCopying::IssueEmptyCheckpoint() {
1058 Thread* self = Thread::Current();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001059 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001060 // Release locks then wait for all mutator threads to pass the barrier.
1061 Locks::mutator_lock_->SharedUnlock(self);
Hiroshi Yamauchia2224042017-02-08 16:35:45 -08001062 thread_list->RunEmptyCheckpoint();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001063 Locks::mutator_lock_->SharedLock(self);
1064}
1065
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -07001066void ConcurrentCopying::ExpandGcMarkStack() {
1067 DCHECK(gc_mark_stack_->IsFull());
1068 const size_t new_size = gc_mark_stack_->Capacity() * 2;
1069 std::vector<StackReference<mirror::Object>> temp(gc_mark_stack_->Begin(),
1070 gc_mark_stack_->End());
1071 gc_mark_stack_->Resize(new_size);
1072 for (auto& ref : temp) {
1073 gc_mark_stack_->PushBack(ref.AsMirrorPtr());
1074 }
1075 DCHECK(!gc_mark_stack_->IsFull());
1076}
1077
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08001078void ConcurrentCopying::PushOntoMarkStack(Thread* const self, mirror::Object* to_ref) {
Orion Hodson88591fe2018-03-06 13:35:43 +00001079 CHECK_EQ(is_mark_stack_push_disallowed_.load(std::memory_order_relaxed), 0)
David Sehr709b0702016-10-13 09:12:37 -07001080 << " " << to_ref << " " << mirror::Object::PrettyTypeOf(to_ref);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001081 CHECK(thread_running_gc_ != nullptr);
Orion Hodson88591fe2018-03-06 13:35:43 +00001082 MarkStackMode mark_stack_mode = mark_stack_mode_.load(std::memory_order_relaxed);
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001083 if (LIKELY(mark_stack_mode == kMarkStackModeThreadLocal)) {
1084 if (LIKELY(self == thread_running_gc_)) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001085 // If GC-running thread, use the GC mark stack instead of a thread-local mark stack.
1086 CHECK(self->GetThreadLocalMarkStack() == nullptr);
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -07001087 if (UNLIKELY(gc_mark_stack_->IsFull())) {
1088 ExpandGcMarkStack();
1089 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001090 gc_mark_stack_->PushBack(to_ref);
1091 } else {
1092 // Otherwise, use a thread-local mark stack.
1093 accounting::AtomicStack<mirror::Object>* tl_mark_stack = self->GetThreadLocalMarkStack();
1094 if (UNLIKELY(tl_mark_stack == nullptr || tl_mark_stack->IsFull())) {
1095 MutexLock mu(self, mark_stack_lock_);
1096 // Get a new thread local mark stack.
1097 accounting::AtomicStack<mirror::Object>* new_tl_mark_stack;
1098 if (!pooled_mark_stacks_.empty()) {
1099 // Use a pooled mark stack.
1100 new_tl_mark_stack = pooled_mark_stacks_.back();
1101 pooled_mark_stacks_.pop_back();
1102 } else {
1103 // None pooled. Create a new one.
1104 new_tl_mark_stack =
1105 accounting::AtomicStack<mirror::Object>::Create(
1106 "thread local mark stack", 4 * KB, 4 * KB);
1107 }
1108 DCHECK(new_tl_mark_stack != nullptr);
1109 DCHECK(new_tl_mark_stack->IsEmpty());
1110 new_tl_mark_stack->PushBack(to_ref);
1111 self->SetThreadLocalMarkStack(new_tl_mark_stack);
1112 if (tl_mark_stack != nullptr) {
1113 // Store the old full stack into a vector.
1114 revoked_mark_stacks_.push_back(tl_mark_stack);
1115 }
1116 } else {
1117 tl_mark_stack->PushBack(to_ref);
1118 }
1119 }
1120 } else if (mark_stack_mode == kMarkStackModeShared) {
1121 // Access the shared GC mark stack with a lock.
1122 MutexLock mu(self, mark_stack_lock_);
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -07001123 if (UNLIKELY(gc_mark_stack_->IsFull())) {
1124 ExpandGcMarkStack();
1125 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001126 gc_mark_stack_->PushBack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001127 } else {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001128 CHECK_EQ(static_cast<uint32_t>(mark_stack_mode),
Hiroshi Yamauchifa755182015-09-30 20:12:11 -07001129 static_cast<uint32_t>(kMarkStackModeGcExclusive))
1130 << "ref=" << to_ref
1131 << " self->gc_marking=" << self->GetIsGcMarking()
1132 << " cc->is_marking=" << is_marking_;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001133 CHECK(self == thread_running_gc_)
1134 << "Only GC-running thread should access the mark stack "
1135 << "in the GC exclusive mark stack mode";
1136 // Access the GC mark stack without a lock.
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -07001137 if (UNLIKELY(gc_mark_stack_->IsFull())) {
1138 ExpandGcMarkStack();
1139 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001140 gc_mark_stack_->PushBack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001141 }
1142}
1143
1144accounting::ObjectStack* ConcurrentCopying::GetAllocationStack() {
1145 return heap_->allocation_stack_.get();
1146}
1147
1148accounting::ObjectStack* ConcurrentCopying::GetLiveStack() {
1149 return heap_->live_stack_.get();
1150}
1151
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001152// The following visitors are used to verify that there's no references to the from-space left after
1153// marking.
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001154class ConcurrentCopying::VerifyNoFromSpaceRefsVisitor : public SingleRootVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001155 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001156 explicit VerifyNoFromSpaceRefsVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001157 : collector_(collector) {}
1158
Mathieu Chartierbc632f02017-04-20 13:31:39 -07001159 void operator()(mirror::Object* ref,
1160 MemberOffset offset = MemberOffset(0),
1161 mirror::Object* holder = nullptr) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001162 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001163 if (ref == nullptr) {
1164 // OK.
1165 return;
1166 }
Mathieu Chartierbc632f02017-04-20 13:31:39 -07001167 collector_->AssertToSpaceInvariant(holder, offset, ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001168 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001169 CHECK_EQ(ref->GetReadBarrierState(), ReadBarrier::WhiteState())
David Sehr709b0702016-10-13 09:12:37 -07001170 << "Ref " << ref << " " << ref->PrettyTypeOf()
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001171 << " has non-white rb_state ";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001172 }
1173 }
1174
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001175 void VisitRoot(mirror::Object* root, const RootInfo& info ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001176 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001177 DCHECK(root != nullptr);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001178 operator()(root);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001179 }
1180
1181 private:
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001182 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001183};
1184
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001185class ConcurrentCopying::VerifyNoFromSpaceRefsFieldVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001186 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001187 explicit VerifyNoFromSpaceRefsFieldVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001188 : collector_(collector) {}
1189
Mathieu Chartier31e88222016-10-14 18:43:19 -07001190 void operator()(ObjPtr<mirror::Object> obj,
1191 MemberOffset offset,
1192 bool is_static ATTRIBUTE_UNUSED) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001193 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001194 mirror::Object* ref =
1195 obj->GetFieldObject<mirror::Object, kDefaultVerifyFlags, kWithoutReadBarrier>(offset);
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001196 VerifyNoFromSpaceRefsVisitor visitor(collector_);
Mathieu Chartierbc632f02017-04-20 13:31:39 -07001197 visitor(ref, offset, obj.Ptr());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001198 }
Mathieu Chartier31e88222016-10-14 18:43:19 -07001199 void operator()(ObjPtr<mirror::Class> klass,
1200 ObjPtr<mirror::Reference> ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001201 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001202 CHECK(klass->IsTypeOfReferenceClass());
1203 this->operator()(ref, mirror::Reference::ReferentOffset(), false);
1204 }
1205
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001206 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001207 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001208 if (!root->IsNull()) {
1209 VisitRoot(root);
1210 }
1211 }
1212
1213 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001214 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001215 VerifyNoFromSpaceRefsVisitor visitor(collector_);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001216 visitor(root->AsMirrorPtr());
1217 }
1218
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001219 private:
Mathieu Chartier97509952015-07-13 14:35:43 -07001220 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001221};
1222
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001223// Verify there's no from-space references left after the marking phase.
1224void ConcurrentCopying::VerifyNoFromSpaceReferences() {
1225 Thread* self = Thread::Current();
1226 DCHECK(Locks::mutator_lock_->IsExclusiveHeld(self));
Hiroshi Yamauchi00370822015-08-18 14:47:25 -07001227 // Verify all threads have is_gc_marking to be false
1228 {
1229 MutexLock mu(self, *Locks::thread_list_lock_);
1230 std::list<Thread*> thread_list = Runtime::Current()->GetThreadList()->GetList();
1231 for (Thread* thread : thread_list) {
1232 CHECK(!thread->GetIsGcMarking());
1233 }
1234 }
Andreas Gampe0c183382017-07-13 22:26:24 -07001235
1236 auto verify_no_from_space_refs_visitor = [&](mirror::Object* obj)
1237 REQUIRES_SHARED(Locks::mutator_lock_) {
1238 CHECK(obj != nullptr);
1239 space::RegionSpace* region_space = RegionSpace();
1240 CHECK(!region_space->IsInFromSpace(obj)) << "Scanning object " << obj << " in from space";
1241 VerifyNoFromSpaceRefsFieldVisitor visitor(this);
1242 obj->VisitReferences</*kVisitNativeRoots*/true, kDefaultVerifyFlags, kWithoutReadBarrier>(
1243 visitor,
1244 visitor);
1245 if (kUseBakerReadBarrier) {
1246 CHECK_EQ(obj->GetReadBarrierState(), ReadBarrier::WhiteState())
1247 << "obj=" << obj << " non-white rb_state " << obj->GetReadBarrierState();
1248 }
1249 };
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001250 // Roots.
1251 {
1252 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001253 VerifyNoFromSpaceRefsVisitor ref_visitor(this);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001254 Runtime::Current()->VisitRoots(&ref_visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001255 }
1256 // The to-space.
Andreas Gampe0c183382017-07-13 22:26:24 -07001257 region_space_->WalkToSpace(verify_no_from_space_refs_visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001258 // Non-moving spaces.
1259 {
1260 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Andreas Gampe0c183382017-07-13 22:26:24 -07001261 heap_->GetMarkBitmap()->Visit(verify_no_from_space_refs_visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001262 }
1263 // The alloc stack.
1264 {
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001265 VerifyNoFromSpaceRefsVisitor ref_visitor(this);
Mathieu Chartiercb535da2015-01-23 13:50:03 -08001266 for (auto* it = heap_->allocation_stack_->Begin(), *end = heap_->allocation_stack_->End();
1267 it < end; ++it) {
1268 mirror::Object* const obj = it->AsMirrorPtr();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001269 if (obj != nullptr && obj->GetClass() != nullptr) {
1270 // TODO: need to call this only if obj is alive?
1271 ref_visitor(obj);
Andreas Gampe0c183382017-07-13 22:26:24 -07001272 verify_no_from_space_refs_visitor(obj);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001273 }
1274 }
1275 }
1276 // TODO: LOS. But only refs in LOS are classes.
1277}
1278
1279// The following visitors are used to assert the to-space invariant.
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001280class ConcurrentCopying::AssertToSpaceInvariantRefsVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001281 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001282 explicit AssertToSpaceInvariantRefsVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001283 : collector_(collector) {}
1284
1285 void operator()(mirror::Object* ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001286 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001287 if (ref == nullptr) {
1288 // OK.
1289 return;
1290 }
1291 collector_->AssertToSpaceInvariant(nullptr, MemberOffset(0), ref);
1292 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001293
1294 private:
Mathieu Chartier97509952015-07-13 14:35:43 -07001295 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001296};
1297
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001298class ConcurrentCopying::AssertToSpaceInvariantFieldVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001299 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001300 explicit AssertToSpaceInvariantFieldVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001301 : collector_(collector) {}
1302
Mathieu Chartier31e88222016-10-14 18:43:19 -07001303 void operator()(ObjPtr<mirror::Object> obj,
1304 MemberOffset offset,
1305 bool is_static ATTRIBUTE_UNUSED) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001306 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001307 mirror::Object* ref =
1308 obj->GetFieldObject<mirror::Object, kDefaultVerifyFlags, kWithoutReadBarrier>(offset);
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001309 AssertToSpaceInvariantRefsVisitor visitor(collector_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001310 visitor(ref);
1311 }
Mathieu Chartier31e88222016-10-14 18:43:19 -07001312 void operator()(ObjPtr<mirror::Class> klass, ObjPtr<mirror::Reference> ref ATTRIBUTE_UNUSED) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001313 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001314 CHECK(klass->IsTypeOfReferenceClass());
1315 }
1316
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001317 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001318 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001319 if (!root->IsNull()) {
1320 VisitRoot(root);
1321 }
1322 }
1323
1324 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001325 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001326 AssertToSpaceInvariantRefsVisitor visitor(collector_);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001327 visitor(root->AsMirrorPtr());
1328 }
1329
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001330 private:
Mathieu Chartier97509952015-07-13 14:35:43 -07001331 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001332};
1333
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001334class ConcurrentCopying::RevokeThreadLocalMarkStackCheckpoint : public Closure {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001335 public:
Roland Levillain3887c462015-08-12 18:15:42 +01001336 RevokeThreadLocalMarkStackCheckpoint(ConcurrentCopying* concurrent_copying,
1337 bool disable_weak_ref_access)
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001338 : concurrent_copying_(concurrent_copying),
1339 disable_weak_ref_access_(disable_weak_ref_access) {
1340 }
1341
1342 virtual void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
1343 // Note: self is not necessarily equal to thread since thread may be suspended.
1344 Thread* self = Thread::Current();
1345 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
1346 << thread->GetState() << " thread " << thread << " self " << self;
1347 // Revoke thread local mark stacks.
1348 accounting::AtomicStack<mirror::Object>* tl_mark_stack = thread->GetThreadLocalMarkStack();
1349 if (tl_mark_stack != nullptr) {
1350 MutexLock mu(self, concurrent_copying_->mark_stack_lock_);
1351 concurrent_copying_->revoked_mark_stacks_.push_back(tl_mark_stack);
1352 thread->SetThreadLocalMarkStack(nullptr);
1353 }
1354 // Disable weak ref access.
1355 if (disable_weak_ref_access_) {
1356 thread->SetWeakRefAccessEnabled(false);
1357 }
1358 // If thread is a running mutator, then act on behalf of the garbage collector.
1359 // See the code in ThreadList::RunCheckpoint.
Mathieu Chartier10d25082015-10-28 18:36:09 -07001360 concurrent_copying_->GetBarrier().Pass(self);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001361 }
1362
1363 private:
1364 ConcurrentCopying* const concurrent_copying_;
1365 const bool disable_weak_ref_access_;
1366};
1367
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001368void ConcurrentCopying::RevokeThreadLocalMarkStacks(bool disable_weak_ref_access,
1369 Closure* checkpoint_callback) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001370 Thread* self = Thread::Current();
1371 RevokeThreadLocalMarkStackCheckpoint check_point(this, disable_weak_ref_access);
1372 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1373 gc_barrier_->Init(self, 0);
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001374 size_t barrier_count = thread_list->RunCheckpoint(&check_point, checkpoint_callback);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001375 // If there are no threads to wait which implys that all the checkpoint functions are finished,
1376 // then no need to release the mutator lock.
1377 if (barrier_count == 0) {
1378 return;
1379 }
1380 Locks::mutator_lock_->SharedUnlock(self);
1381 {
1382 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
1383 gc_barrier_->Increment(self, barrier_count);
1384 }
1385 Locks::mutator_lock_->SharedLock(self);
1386}
1387
1388void ConcurrentCopying::RevokeThreadLocalMarkStack(Thread* thread) {
1389 Thread* self = Thread::Current();
1390 CHECK_EQ(self, thread);
1391 accounting::AtomicStack<mirror::Object>* tl_mark_stack = thread->GetThreadLocalMarkStack();
1392 if (tl_mark_stack != nullptr) {
1393 CHECK(is_marking_);
1394 MutexLock mu(self, mark_stack_lock_);
1395 revoked_mark_stacks_.push_back(tl_mark_stack);
1396 thread->SetThreadLocalMarkStack(nullptr);
1397 }
1398}
1399
1400void ConcurrentCopying::ProcessMarkStack() {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001401 if (kVerboseMode) {
1402 LOG(INFO) << "ProcessMarkStack. ";
1403 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001404 bool empty_prev = false;
1405 while (true) {
1406 bool empty = ProcessMarkStackOnce();
1407 if (empty_prev && empty) {
1408 // Saw empty mark stack for a second time, done.
1409 break;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001410 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001411 empty_prev = empty;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001412 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001413}
1414
1415bool ConcurrentCopying::ProcessMarkStackOnce() {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08001416 DCHECK(thread_running_gc_ != nullptr);
1417 Thread* const self = Thread::Current();
1418 DCHECK(self == thread_running_gc_);
1419 DCHECK(thread_running_gc_->GetThreadLocalMarkStack() == nullptr);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001420 size_t count = 0;
Orion Hodson88591fe2018-03-06 13:35:43 +00001421 MarkStackMode mark_stack_mode = mark_stack_mode_.load(std::memory_order_relaxed);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001422 if (mark_stack_mode == kMarkStackModeThreadLocal) {
1423 // Process the thread-local mark stacks and the GC mark stack.
Roland Levillainaf290312018-02-27 20:02:17 +00001424 count += ProcessThreadLocalMarkStacks(/* disable_weak_ref_access */ false,
1425 /* checkpoint_callback */ nullptr);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001426 while (!gc_mark_stack_->IsEmpty()) {
1427 mirror::Object* to_ref = gc_mark_stack_->PopBack();
1428 ProcessMarkStackRef(to_ref);
1429 ++count;
1430 }
1431 gc_mark_stack_->Reset();
1432 } else if (mark_stack_mode == kMarkStackModeShared) {
Hiroshi Yamauchi30493242016-11-03 13:06:52 -07001433 // Do an empty checkpoint to avoid a race with a mutator preempted in the middle of a read
1434 // barrier but before pushing onto the mark stack. b/32508093. Note the weak ref access is
1435 // disabled at this point.
1436 IssueEmptyCheckpoint();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001437 // Process the shared GC mark stack with a lock.
1438 {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08001439 MutexLock mu(thread_running_gc_, mark_stack_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001440 CHECK(revoked_mark_stacks_.empty());
1441 }
1442 while (true) {
1443 std::vector<mirror::Object*> refs;
1444 {
1445 // Copy refs with lock. Note the number of refs should be small.
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08001446 MutexLock mu(thread_running_gc_, mark_stack_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001447 if (gc_mark_stack_->IsEmpty()) {
1448 break;
1449 }
1450 for (StackReference<mirror::Object>* p = gc_mark_stack_->Begin();
1451 p != gc_mark_stack_->End(); ++p) {
1452 refs.push_back(p->AsMirrorPtr());
1453 }
1454 gc_mark_stack_->Reset();
1455 }
1456 for (mirror::Object* ref : refs) {
1457 ProcessMarkStackRef(ref);
1458 ++count;
1459 }
1460 }
1461 } else {
1462 CHECK_EQ(static_cast<uint32_t>(mark_stack_mode),
1463 static_cast<uint32_t>(kMarkStackModeGcExclusive));
1464 {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08001465 MutexLock mu(thread_running_gc_, mark_stack_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001466 CHECK(revoked_mark_stacks_.empty());
1467 }
1468 // Process the GC mark stack in the exclusive mode. No need to take the lock.
1469 while (!gc_mark_stack_->IsEmpty()) {
1470 mirror::Object* to_ref = gc_mark_stack_->PopBack();
1471 ProcessMarkStackRef(to_ref);
1472 ++count;
1473 }
1474 gc_mark_stack_->Reset();
1475 }
1476
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001477 // Return true if the stack was empty.
1478 return count == 0;
1479}
1480
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001481size_t ConcurrentCopying::ProcessThreadLocalMarkStacks(bool disable_weak_ref_access,
1482 Closure* checkpoint_callback) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001483 // Run a checkpoint to collect all thread local mark stacks and iterate over them all.
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001484 RevokeThreadLocalMarkStacks(disable_weak_ref_access, checkpoint_callback);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001485 size_t count = 0;
1486 std::vector<accounting::AtomicStack<mirror::Object>*> mark_stacks;
1487 {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08001488 MutexLock mu(thread_running_gc_, mark_stack_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001489 // Make a copy of the mark stack vector.
1490 mark_stacks = revoked_mark_stacks_;
1491 revoked_mark_stacks_.clear();
1492 }
1493 for (accounting::AtomicStack<mirror::Object>* mark_stack : mark_stacks) {
1494 for (StackReference<mirror::Object>* p = mark_stack->Begin(); p != mark_stack->End(); ++p) {
1495 mirror::Object* to_ref = p->AsMirrorPtr();
1496 ProcessMarkStackRef(to_ref);
1497 ++count;
1498 }
1499 {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08001500 MutexLock mu(thread_running_gc_, mark_stack_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001501 if (pooled_mark_stacks_.size() >= kMarkStackPoolSize) {
1502 // The pool has enough. Delete it.
1503 delete mark_stack;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001504 } else {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001505 // Otherwise, put it into the pool for later reuse.
1506 mark_stack->Reset();
1507 pooled_mark_stacks_.push_back(mark_stack);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001508 }
1509 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001510 }
1511 return count;
1512}
1513
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001514inline void ConcurrentCopying::ProcessMarkStackRef(mirror::Object* to_ref) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001515 DCHECK(!region_space_->IsInFromSpace(to_ref));
1516 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001517 DCHECK(to_ref->GetReadBarrierState() == ReadBarrier::GrayState())
1518 << " " << to_ref << " " << to_ref->GetReadBarrierState()
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001519 << " is_marked=" << IsMarked(to_ref);
1520 }
Mathieu Chartierc381c362016-08-23 13:27:53 -07001521 bool add_to_live_bytes = false;
1522 if (region_space_->IsInUnevacFromSpace(to_ref)) {
1523 // Mark the bitmap only in the GC thread here so that we don't need a CAS.
1524 if (!kUseBakerReadBarrier || !region_space_bitmap_->Set(to_ref)) {
1525 // It may be already marked if we accidentally pushed the same object twice due to the racy
1526 // bitmap read in MarkUnevacFromSpaceRegion.
1527 Scan(to_ref);
1528 // Only add to the live bytes if the object was not already marked.
1529 add_to_live_bytes = true;
1530 }
1531 } else {
1532 Scan(to_ref);
1533 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001534 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001535 DCHECK(to_ref->GetReadBarrierState() == ReadBarrier::GrayState())
1536 << " " << to_ref << " " << to_ref->GetReadBarrierState()
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001537 << " is_marked=" << IsMarked(to_ref);
1538 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001539#ifdef USE_BAKER_OR_BROOKS_READ_BARRIER
Hiroshi Yamauchi39c12d42016-12-06 16:46:37 -08001540 mirror::Object* referent = nullptr;
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001541 if (UNLIKELY((to_ref->GetClass<kVerifyNone, kWithoutReadBarrier>()->IsTypeOfReferenceClass() &&
Hiroshi Yamauchi39c12d42016-12-06 16:46:37 -08001542 (referent = to_ref->AsReference()->GetReferent<kWithoutReadBarrier>()) != nullptr &&
1543 !IsInToSpace(referent)))) {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001544 // Leave this reference gray in the queue so that GetReferent() will trigger a read barrier. We
1545 // will change it to white later in ReferenceQueue::DequeuePendingReference().
Roland Levillain2ae376f2018-01-30 11:35:11 +00001546 DCHECK(to_ref->AsReference()->GetPendingNext() != nullptr)
1547 << "Left unenqueued ref gray " << to_ref;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001548 } else {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001549 // We may occasionally leave a reference white in the queue if its referent happens to be
1550 // concurrently marked after the Scan() call above has enqueued the Reference, in which case the
1551 // above IsInToSpace() evaluates to true and we change the color from gray to white here in this
1552 // else block.
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001553 if (kUseBakerReadBarrier) {
Mathieu Chartier42c2e502018-06-19 12:30:56 -07001554 bool success = to_ref->AtomicSetReadBarrierState<std::memory_order_release>(
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001555 ReadBarrier::GrayState(),
1556 ReadBarrier::WhiteState());
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001557 DCHECK(success) << "Must succeed as we won the race.";
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001558 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001559 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001560#else
1561 DCHECK(!kUseBakerReadBarrier);
1562#endif
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001563
Mathieu Chartierc381c362016-08-23 13:27:53 -07001564 if (add_to_live_bytes) {
Roland Levillain2ae376f2018-01-30 11:35:11 +00001565 // Add to the live bytes per unevacuated from-space. Note this code is always run by the
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001566 // GC-running thread (no synchronization required).
1567 DCHECK(region_space_bitmap_->Test(to_ref));
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07001568 size_t obj_size = to_ref->SizeOf<kDefaultVerifyFlags>();
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001569 size_t alloc_size = RoundUp(obj_size, space::RegionSpace::kAlignment);
1570 region_space_->AddLiveBytes(to_ref, alloc_size);
1571 }
Andreas Gampee3ce7872017-02-22 13:36:21 -08001572 if (ReadBarrier::kEnableToSpaceInvariantChecks) {
Andreas Gampe0c183382017-07-13 22:26:24 -07001573 CHECK(to_ref != nullptr);
1574 space::RegionSpace* region_space = RegionSpace();
1575 CHECK(!region_space->IsInFromSpace(to_ref)) << "Scanning object " << to_ref << " in from space";
1576 AssertToSpaceInvariant(nullptr, MemberOffset(0), to_ref);
1577 AssertToSpaceInvariantFieldVisitor visitor(this);
1578 to_ref->VisitReferences</*kVisitNativeRoots*/true, kDefaultVerifyFlags, kWithoutReadBarrier>(
1579 visitor,
1580 visitor);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001581 }
1582}
1583
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001584class ConcurrentCopying::DisableWeakRefAccessCallback : public Closure {
1585 public:
1586 explicit DisableWeakRefAccessCallback(ConcurrentCopying* concurrent_copying)
1587 : concurrent_copying_(concurrent_copying) {
1588 }
1589
1590 void Run(Thread* self ATTRIBUTE_UNUSED) OVERRIDE REQUIRES(Locks::thread_list_lock_) {
1591 // This needs to run under the thread_list_lock_ critical section in ThreadList::RunCheckpoint()
1592 // to avoid a deadlock b/31500969.
1593 CHECK(concurrent_copying_->weak_ref_access_enabled_);
1594 concurrent_copying_->weak_ref_access_enabled_ = false;
1595 }
1596
1597 private:
1598 ConcurrentCopying* const concurrent_copying_;
1599};
1600
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001601void ConcurrentCopying::SwitchToSharedMarkStackMode() {
1602 Thread* self = Thread::Current();
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08001603 DCHECK(thread_running_gc_ != nullptr);
1604 DCHECK(self == thread_running_gc_);
1605 DCHECK(thread_running_gc_->GetThreadLocalMarkStack() == nullptr);
Orion Hodson88591fe2018-03-06 13:35:43 +00001606 MarkStackMode before_mark_stack_mode = mark_stack_mode_.load(std::memory_order_relaxed);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001607 CHECK_EQ(static_cast<uint32_t>(before_mark_stack_mode),
1608 static_cast<uint32_t>(kMarkStackModeThreadLocal));
Orion Hodson88591fe2018-03-06 13:35:43 +00001609 mark_stack_mode_.store(kMarkStackModeShared, std::memory_order_relaxed);
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001610 DisableWeakRefAccessCallback dwrac(this);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001611 // Process the thread local mark stacks one last time after switching to the shared mark stack
1612 // mode and disable weak ref accesses.
Roland Levillainaf290312018-02-27 20:02:17 +00001613 ProcessThreadLocalMarkStacks(/* disable_weak_ref_access */ true, &dwrac);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001614 if (kVerboseMode) {
1615 LOG(INFO) << "Switched to shared mark stack mode and disabled weak ref access";
1616 }
1617}
1618
1619void ConcurrentCopying::SwitchToGcExclusiveMarkStackMode() {
1620 Thread* self = Thread::Current();
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08001621 DCHECK(thread_running_gc_ != nullptr);
1622 DCHECK(self == thread_running_gc_);
1623 DCHECK(thread_running_gc_->GetThreadLocalMarkStack() == nullptr);
Orion Hodson88591fe2018-03-06 13:35:43 +00001624 MarkStackMode before_mark_stack_mode = mark_stack_mode_.load(std::memory_order_relaxed);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001625 CHECK_EQ(static_cast<uint32_t>(before_mark_stack_mode),
1626 static_cast<uint32_t>(kMarkStackModeShared));
Orion Hodson88591fe2018-03-06 13:35:43 +00001627 mark_stack_mode_.store(kMarkStackModeGcExclusive, std::memory_order_relaxed);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001628 QuasiAtomic::ThreadFenceForConstructor();
1629 if (kVerboseMode) {
1630 LOG(INFO) << "Switched to GC exclusive mark stack mode";
1631 }
1632}
1633
1634void ConcurrentCopying::CheckEmptyMarkStack() {
1635 Thread* self = Thread::Current();
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08001636 DCHECK(thread_running_gc_ != nullptr);
1637 DCHECK(self == thread_running_gc_);
1638 DCHECK(thread_running_gc_->GetThreadLocalMarkStack() == nullptr);
Orion Hodson88591fe2018-03-06 13:35:43 +00001639 MarkStackMode mark_stack_mode = mark_stack_mode_.load(std::memory_order_relaxed);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001640 if (mark_stack_mode == kMarkStackModeThreadLocal) {
1641 // Thread-local mark stack mode.
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001642 RevokeThreadLocalMarkStacks(false, nullptr);
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08001643 MutexLock mu(thread_running_gc_, mark_stack_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001644 if (!revoked_mark_stacks_.empty()) {
1645 for (accounting::AtomicStack<mirror::Object>* mark_stack : revoked_mark_stacks_) {
1646 while (!mark_stack->IsEmpty()) {
1647 mirror::Object* obj = mark_stack->PopBack();
1648 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001649 uint32_t rb_state = obj->GetReadBarrierState();
1650 LOG(INFO) << "On mark queue : " << obj << " " << obj->PrettyTypeOf() << " rb_state="
1651 << rb_state << " is_marked=" << IsMarked(obj);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001652 } else {
David Sehr709b0702016-10-13 09:12:37 -07001653 LOG(INFO) << "On mark queue : " << obj << " " << obj->PrettyTypeOf()
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001654 << " is_marked=" << IsMarked(obj);
1655 }
1656 }
1657 }
1658 LOG(FATAL) << "mark stack is not empty";
1659 }
1660 } else {
1661 // Shared, GC-exclusive, or off.
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08001662 MutexLock mu(thread_running_gc_, mark_stack_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001663 CHECK(gc_mark_stack_->IsEmpty());
1664 CHECK(revoked_mark_stacks_.empty());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001665 }
1666}
1667
1668void ConcurrentCopying::SweepSystemWeaks(Thread* self) {
1669 TimingLogger::ScopedTiming split("SweepSystemWeaks", GetTimings());
1670 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier97509952015-07-13 14:35:43 -07001671 Runtime::Current()->SweepSystemWeaks(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001672}
1673
1674void ConcurrentCopying::Sweep(bool swap_bitmaps) {
1675 {
1676 TimingLogger::ScopedTiming t("MarkStackAsLive", GetTimings());
1677 accounting::ObjectStack* live_stack = heap_->GetLiveStack();
1678 if (kEnableFromSpaceAccountingCheck) {
1679 CHECK_GE(live_stack_freeze_size_, live_stack->Size());
1680 }
1681 heap_->MarkAllocStackAsLive(live_stack);
1682 live_stack->Reset();
1683 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001684 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001685 TimingLogger::ScopedTiming split("Sweep", GetTimings());
1686 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
1687 if (space->IsContinuousMemMapAllocSpace()) {
1688 space::ContinuousMemMapAllocSpace* alloc_space = space->AsContinuousMemMapAllocSpace();
Mathieu Chartier763a31e2015-11-16 16:05:55 -08001689 if (space == region_space_ || immune_spaces_.ContainsSpace(space)) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001690 continue;
1691 }
1692 TimingLogger::ScopedTiming split2(
1693 alloc_space->IsZygoteSpace() ? "SweepZygoteSpace" : "SweepAllocSpace", GetTimings());
1694 RecordFree(alloc_space->Sweep(swap_bitmaps));
1695 }
1696 }
1697 SweepLargeObjects(swap_bitmaps);
1698}
1699
Mathieu Chartier962cd7a2016-08-16 12:15:59 -07001700void ConcurrentCopying::MarkZygoteLargeObjects() {
1701 TimingLogger::ScopedTiming split(__FUNCTION__, GetTimings());
1702 Thread* const self = Thread::Current();
1703 WriterMutexLock rmu(self, *Locks::heap_bitmap_lock_);
1704 space::LargeObjectSpace* const los = heap_->GetLargeObjectsSpace();
Nicolas Geoffray7acddd82017-05-03 15:04:55 +01001705 if (los != nullptr) {
1706 // Pick the current live bitmap (mark bitmap if swapped).
1707 accounting::LargeObjectBitmap* const live_bitmap = los->GetLiveBitmap();
1708 accounting::LargeObjectBitmap* const mark_bitmap = los->GetMarkBitmap();
1709 // Walk through all of the objects and explicitly mark the zygote ones so they don't get swept.
1710 std::pair<uint8_t*, uint8_t*> range = los->GetBeginEndAtomic();
1711 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(range.first),
1712 reinterpret_cast<uintptr_t>(range.second),
1713 [mark_bitmap, los, self](mirror::Object* obj)
1714 REQUIRES(Locks::heap_bitmap_lock_)
1715 REQUIRES_SHARED(Locks::mutator_lock_) {
1716 if (los->IsZygoteLargeObject(self, obj)) {
1717 mark_bitmap->Set(obj);
1718 }
1719 });
1720 }
Mathieu Chartier962cd7a2016-08-16 12:15:59 -07001721}
1722
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001723void ConcurrentCopying::SweepLargeObjects(bool swap_bitmaps) {
1724 TimingLogger::ScopedTiming split("SweepLargeObjects", GetTimings());
Nicolas Geoffray7acddd82017-05-03 15:04:55 +01001725 if (heap_->GetLargeObjectsSpace() != nullptr) {
1726 RecordFreeLOS(heap_->GetLargeObjectsSpace()->Sweep(swap_bitmaps));
1727 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001728}
1729
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001730void ConcurrentCopying::ReclaimPhase() {
1731 TimingLogger::ScopedTiming split("ReclaimPhase", GetTimings());
1732 if (kVerboseMode) {
1733 LOG(INFO) << "GC ReclaimPhase";
1734 }
1735 Thread* self = Thread::Current();
1736
1737 {
1738 // Double-check that the mark stack is empty.
1739 // Note: need to set this after VerifyNoFromSpaceRef().
1740 is_asserting_to_space_invariant_ = false;
1741 QuasiAtomic::ThreadFenceForConstructor();
1742 if (kVerboseMode) {
1743 LOG(INFO) << "Issue an empty check point. ";
1744 }
1745 IssueEmptyCheckpoint();
1746 // Disable the check.
Orion Hodson88591fe2018-03-06 13:35:43 +00001747 is_mark_stack_push_disallowed_.store(0, std::memory_order_seq_cst);
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001748 if (kUseBakerReadBarrier) {
Orion Hodson88591fe2018-03-06 13:35:43 +00001749 updated_all_immune_objects_.store(false, std::memory_order_seq_cst);
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001750 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001751 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001752 }
1753
1754 {
1755 // Record freed objects.
1756 TimingLogger::ScopedTiming split2("RecordFree", GetTimings());
1757 // Don't include thread-locals that are in the to-space.
Mathieu Chartier371b0472017-02-27 16:37:21 -08001758 const uint64_t from_bytes = region_space_->GetBytesAllocatedInFromSpace();
1759 const uint64_t from_objects = region_space_->GetObjectsAllocatedInFromSpace();
1760 const uint64_t unevac_from_bytes = region_space_->GetBytesAllocatedInUnevacFromSpace();
1761 const uint64_t unevac_from_objects = region_space_->GetObjectsAllocatedInUnevacFromSpace();
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08001762 uint64_t to_bytes = bytes_moved_.load(std::memory_order_seq_cst) + bytes_moved_gc_thread_;
Orion Hodson88591fe2018-03-06 13:35:43 +00001763 cumulative_bytes_moved_.fetch_add(to_bytes, std::memory_order_relaxed);
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08001764 uint64_t to_objects = objects_moved_.load(std::memory_order_seq_cst) + objects_moved_gc_thread_;
Orion Hodson88591fe2018-03-06 13:35:43 +00001765 cumulative_objects_moved_.fetch_add(to_objects, std::memory_order_relaxed);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001766 if (kEnableFromSpaceAccountingCheck) {
1767 CHECK_EQ(from_space_num_objects_at_first_pause_, from_objects + unevac_from_objects);
1768 CHECK_EQ(from_space_num_bytes_at_first_pause_, from_bytes + unevac_from_bytes);
1769 }
1770 CHECK_LE(to_objects, from_objects);
1771 CHECK_LE(to_bytes, from_bytes);
Roland Levillain8f7ea9a2018-01-26 17:27:59 +00001772 // Cleared bytes and objects, populated by the call to RegionSpace::ClearFromSpace below.
Mathieu Chartier371b0472017-02-27 16:37:21 -08001773 uint64_t cleared_bytes;
1774 uint64_t cleared_objects;
1775 {
1776 TimingLogger::ScopedTiming split4("ClearFromSpace", GetTimings());
1777 region_space_->ClearFromSpace(&cleared_bytes, &cleared_objects);
Roland Levillain8f7ea9a2018-01-26 17:27:59 +00001778 // `cleared_bytes` and `cleared_objects` may be greater than the from space equivalents since
1779 // RegionSpace::ClearFromSpace may clear empty unevac regions.
Mathieu Chartier371b0472017-02-27 16:37:21 -08001780 CHECK_GE(cleared_bytes, from_bytes);
1781 CHECK_GE(cleared_objects, from_objects);
1782 }
1783 int64_t freed_bytes = cleared_bytes - to_bytes;
1784 int64_t freed_objects = cleared_objects - to_objects;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001785 if (kVerboseMode) {
1786 LOG(INFO) << "RecordFree:"
1787 << " from_bytes=" << from_bytes << " from_objects=" << from_objects
Roland Levillain2ae376f2018-01-30 11:35:11 +00001788 << " unevac_from_bytes=" << unevac_from_bytes
1789 << " unevac_from_objects=" << unevac_from_objects
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001790 << " to_bytes=" << to_bytes << " to_objects=" << to_objects
1791 << " freed_bytes=" << freed_bytes << " freed_objects=" << freed_objects
1792 << " from_space size=" << region_space_->FromSpaceSize()
1793 << " unevac_from_space size=" << region_space_->UnevacFromSpaceSize()
1794 << " to_space size=" << region_space_->ToSpaceSize();
Roland Levillain2ae376f2018-01-30 11:35:11 +00001795 LOG(INFO) << "(before) num_bytes_allocated="
Orion Hodson88591fe2018-03-06 13:35:43 +00001796 << heap_->num_bytes_allocated_.load(std::memory_order_seq_cst);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001797 }
1798 RecordFree(ObjectBytePair(freed_objects, freed_bytes));
1799 if (kVerboseMode) {
Roland Levillain2ae376f2018-01-30 11:35:11 +00001800 LOG(INFO) << "(after) num_bytes_allocated="
Orion Hodson88591fe2018-03-06 13:35:43 +00001801 << heap_->num_bytes_allocated_.load(std::memory_order_seq_cst);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001802 }
1803 }
1804
1805 {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001806 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001807 Sweep(false);
1808 SwapBitmaps();
1809 heap_->UnBindBitmaps();
1810
Mathieu Chartier7ec38dc2016-10-07 15:24:46 -07001811 // The bitmap was cleared at the start of the GC, there is nothing we need to do here.
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001812 DCHECK(region_space_bitmap_ != nullptr);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001813 region_space_bitmap_ = nullptr;
1814 }
1815
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001816 CheckEmptyMarkStack();
1817
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001818 if (kVerboseMode) {
1819 LOG(INFO) << "GC end of ReclaimPhase";
1820 }
1821}
1822
Roland Levillain001eff92018-01-24 14:24:33 +00001823std::string ConcurrentCopying::DumpReferenceInfo(mirror::Object* ref,
1824 const char* ref_name,
Andreas Gampebc802de2018-06-20 17:24:11 -07001825 const char* indent) {
Roland Levillain001eff92018-01-24 14:24:33 +00001826 std::ostringstream oss;
1827 oss << indent << heap_->GetVerification()->DumpObjectInfo(ref, ref_name) << '\n';
1828 if (ref != nullptr) {
1829 if (kUseBakerReadBarrier) {
1830 oss << indent << ref_name << "->GetMarkBit()=" << ref->GetMarkBit() << '\n';
1831 oss << indent << ref_name << "->GetReadBarrierState()=" << ref->GetReadBarrierState() << '\n';
1832 }
1833 }
1834 if (region_space_->HasAddress(ref)) {
1835 oss << indent << "Region containing " << ref_name << ":" << '\n';
1836 region_space_->DumpRegionForObject(oss, ref);
1837 if (region_space_bitmap_ != nullptr) {
1838 oss << indent << "region_space_bitmap_->Test(" << ref_name << ")="
1839 << std::boolalpha << region_space_bitmap_->Test(ref) << std::noboolalpha;
1840 }
1841 }
1842 return oss.str();
1843}
1844
1845std::string ConcurrentCopying::DumpHeapReference(mirror::Object* obj,
1846 MemberOffset offset,
1847 mirror::Object* ref) {
1848 std::ostringstream oss;
Andreas Gampebc802de2018-06-20 17:24:11 -07001849 constexpr const char* kIndent = " ";
1850 oss << kIndent << "Invalid reference: ref=" << ref
Roland Levillain001eff92018-01-24 14:24:33 +00001851 << " referenced from: object=" << obj << " offset= " << offset << '\n';
1852 // Information about `obj`.
Andreas Gampebc802de2018-06-20 17:24:11 -07001853 oss << DumpReferenceInfo(obj, "obj", kIndent) << '\n';
Roland Levillain001eff92018-01-24 14:24:33 +00001854 // Information about `ref`.
Andreas Gampebc802de2018-06-20 17:24:11 -07001855 oss << DumpReferenceInfo(ref, "ref", kIndent);
Roland Levillain001eff92018-01-24 14:24:33 +00001856 return oss.str();
1857}
1858
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07001859void ConcurrentCopying::AssertToSpaceInvariant(mirror::Object* obj,
1860 MemberOffset offset,
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001861 mirror::Object* ref) {
Roland Levillain001eff92018-01-24 14:24:33 +00001862 CHECK_EQ(heap_->collector_type_, kCollectorTypeCC) << static_cast<size_t>(heap_->collector_type_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001863 if (is_asserting_to_space_invariant_) {
Roland Levillain001eff92018-01-24 14:24:33 +00001864 if (region_space_->HasAddress(ref)) {
1865 // Check to-space invariant in region space (moving space).
1866 using RegionType = space::RegionSpace::RegionType;
Roland Levillain2dd2e1e2018-02-28 16:24:51 +00001867 space::RegionSpace::RegionType type = region_space_->GetRegionTypeUnsafe(ref);
Roland Levillain001eff92018-01-24 14:24:33 +00001868 if (type == RegionType::kRegionTypeToSpace) {
1869 // OK.
1870 return;
1871 } else if (type == RegionType::kRegionTypeUnevacFromSpace) {
1872 if (!IsMarkedInUnevacFromSpace(ref)) {
1873 LOG(FATAL_WITHOUT_ABORT) << "Found unmarked reference in unevac from-space:";
1874 LOG(FATAL_WITHOUT_ABORT) << DumpHeapReference(obj, offset, ref);
1875 }
1876 CHECK(IsMarkedInUnevacFromSpace(ref)) << ref;
1877 } else {
1878 // Not OK: either a from-space ref or a reference in an unused region.
1879 // Do extra logging.
1880 if (type == RegionType::kRegionTypeFromSpace) {
1881 LOG(FATAL_WITHOUT_ABORT) << "Found from-space reference:";
1882 } else {
1883 LOG(FATAL_WITHOUT_ABORT) << "Found reference in region with type " << type << ":";
1884 }
1885 LOG(FATAL_WITHOUT_ABORT) << DumpHeapReference(obj, offset, ref);
1886 if (obj != nullptr) {
1887 LogFromSpaceRefHolder(obj, offset);
1888 }
1889 ref->GetLockWord(false).Dump(LOG_STREAM(FATAL_WITHOUT_ABORT));
1890 LOG(FATAL_WITHOUT_ABORT) << "Non-free regions:";
1891 region_space_->DumpNonFreeRegions(LOG_STREAM(FATAL_WITHOUT_ABORT));
1892 PrintFileToLog("/proc/self/maps", LogSeverity::FATAL_WITHOUT_ABORT);
1893 MemMap::DumpMaps(LOG_STREAM(FATAL_WITHOUT_ABORT), true);
1894 LOG(FATAL) << "Invalid reference " << ref
1895 << " referenced from object " << obj << " at offset " << offset;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001896 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001897 } else {
Roland Levillain001eff92018-01-24 14:24:33 +00001898 // Check to-space invariant in non-moving space.
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001899 AssertToSpaceInvariantInNonMovingSpace(obj, ref);
1900 }
1901 }
1902}
1903
1904class RootPrinter {
1905 public:
1906 RootPrinter() { }
1907
1908 template <class MirrorType>
1909 ALWAYS_INLINE void VisitRootIfNonNull(mirror::CompressedReference<MirrorType>* root)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001910 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001911 if (!root->IsNull()) {
1912 VisitRoot(root);
1913 }
1914 }
1915
1916 template <class MirrorType>
1917 void VisitRoot(mirror::Object** root)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001918 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07001919 LOG(FATAL_WITHOUT_ABORT) << "root=" << root << " ref=" << *root;
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001920 }
1921
1922 template <class MirrorType>
1923 void VisitRoot(mirror::CompressedReference<MirrorType>* root)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001924 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07001925 LOG(FATAL_WITHOUT_ABORT) << "root=" << root << " ref=" << root->AsMirrorPtr();
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001926 }
1927};
1928
Roland Levillain001eff92018-01-24 14:24:33 +00001929std::string ConcurrentCopying::DumpGcRoot(mirror::Object* ref) {
1930 std::ostringstream oss;
Andreas Gampebc802de2018-06-20 17:24:11 -07001931 constexpr const char* kIndent = " ";
1932 oss << kIndent << "Invalid GC root: ref=" << ref << '\n';
Roland Levillain001eff92018-01-24 14:24:33 +00001933 // Information about `ref`.
Andreas Gampebc802de2018-06-20 17:24:11 -07001934 oss << DumpReferenceInfo(ref, "ref", kIndent);
Roland Levillain001eff92018-01-24 14:24:33 +00001935 return oss.str();
1936}
1937
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001938void ConcurrentCopying::AssertToSpaceInvariant(GcRootSource* gc_root_source,
1939 mirror::Object* ref) {
Roland Levillain001eff92018-01-24 14:24:33 +00001940 CHECK_EQ(heap_->collector_type_, kCollectorTypeCC) << static_cast<size_t>(heap_->collector_type_);
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001941 if (is_asserting_to_space_invariant_) {
Roland Levillain001eff92018-01-24 14:24:33 +00001942 if (region_space_->HasAddress(ref)) {
1943 // Check to-space invariant in region space (moving space).
1944 using RegionType = space::RegionSpace::RegionType;
Roland Levillain2dd2e1e2018-02-28 16:24:51 +00001945 space::RegionSpace::RegionType type = region_space_->GetRegionTypeUnsafe(ref);
Roland Levillain001eff92018-01-24 14:24:33 +00001946 if (type == RegionType::kRegionTypeToSpace) {
1947 // OK.
1948 return;
1949 } else if (type == RegionType::kRegionTypeUnevacFromSpace) {
1950 if (!IsMarkedInUnevacFromSpace(ref)) {
1951 LOG(FATAL_WITHOUT_ABORT) << "Found unmarked reference in unevac from-space:";
1952 LOG(FATAL_WITHOUT_ABORT) << DumpGcRoot(ref);
1953 }
1954 CHECK(IsMarkedInUnevacFromSpace(ref)) << ref;
1955 } else {
1956 // Not OK: either a from-space ref or a reference in an unused region.
1957 // Do extra logging.
1958 if (type == RegionType::kRegionTypeFromSpace) {
1959 LOG(FATAL_WITHOUT_ABORT) << "Found from-space reference:";
1960 } else {
1961 LOG(FATAL_WITHOUT_ABORT) << "Found reference in region with type " << type << ":";
1962 }
1963 LOG(FATAL_WITHOUT_ABORT) << DumpGcRoot(ref);
1964 if (gc_root_source == nullptr) {
1965 // No info.
1966 } else if (gc_root_source->HasArtField()) {
1967 ArtField* field = gc_root_source->GetArtField();
1968 LOG(FATAL_WITHOUT_ABORT) << "gc root in field " << field << " "
1969 << ArtField::PrettyField(field);
1970 RootPrinter root_printer;
1971 field->VisitRoots(root_printer);
1972 } else if (gc_root_source->HasArtMethod()) {
1973 ArtMethod* method = gc_root_source->GetArtMethod();
1974 LOG(FATAL_WITHOUT_ABORT) << "gc root in method " << method << " "
1975 << ArtMethod::PrettyMethod(method);
1976 RootPrinter root_printer;
1977 method->VisitRoots(root_printer, kRuntimePointerSize);
1978 }
1979 ref->GetLockWord(false).Dump(LOG_STREAM(FATAL_WITHOUT_ABORT));
1980 LOG(FATAL_WITHOUT_ABORT) << "Non-free regions:";
1981 region_space_->DumpNonFreeRegions(LOG_STREAM(FATAL_WITHOUT_ABORT));
1982 PrintFileToLog("/proc/self/maps", LogSeverity::FATAL_WITHOUT_ABORT);
1983 MemMap::DumpMaps(LOG_STREAM(FATAL_WITHOUT_ABORT), true);
1984 LOG(FATAL) << "Invalid reference " << ref;
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001985 }
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001986 } else {
Roland Levillain001eff92018-01-24 14:24:33 +00001987 // Check to-space invariant in non-moving space.
1988 AssertToSpaceInvariantInNonMovingSpace(/* obj */ nullptr, ref);
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001989 }
1990 }
1991}
1992
1993void ConcurrentCopying::LogFromSpaceRefHolder(mirror::Object* obj, MemberOffset offset) {
1994 if (kUseBakerReadBarrier) {
David Sehr709b0702016-10-13 09:12:37 -07001995 LOG(INFO) << "holder=" << obj << " " << obj->PrettyTypeOf()
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001996 << " holder rb_state=" << obj->GetReadBarrierState();
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001997 } else {
David Sehr709b0702016-10-13 09:12:37 -07001998 LOG(INFO) << "holder=" << obj << " " << obj->PrettyTypeOf();
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07001999 }
2000 if (region_space_->IsInFromSpace(obj)) {
2001 LOG(INFO) << "holder is in the from-space.";
2002 } else if (region_space_->IsInToSpace(obj)) {
2003 LOG(INFO) << "holder is in the to-space.";
2004 } else if (region_space_->IsInUnevacFromSpace(obj)) {
2005 LOG(INFO) << "holder is in the unevac from-space.";
Mathieu Chartierc381c362016-08-23 13:27:53 -07002006 if (IsMarkedInUnevacFromSpace(obj)) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002007 LOG(INFO) << "holder is marked in the region space bitmap.";
2008 } else {
2009 LOG(INFO) << "holder is not marked in the region space bitmap.";
2010 }
2011 } else {
2012 // In a non-moving space.
Mathieu Chartier763a31e2015-11-16 16:05:55 -08002013 if (immune_spaces_.ContainsObject(obj)) {
2014 LOG(INFO) << "holder is in an immune image or the zygote space.";
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002015 } else {
Mathieu Chartier763a31e2015-11-16 16:05:55 -08002016 LOG(INFO) << "holder is in a non-immune, non-moving (or main) space.";
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002017 accounting::ContinuousSpaceBitmap* mark_bitmap =
2018 heap_mark_bitmap_->GetContinuousSpaceBitmap(obj);
2019 accounting::LargeObjectBitmap* los_bitmap =
2020 heap_mark_bitmap_->GetLargeObjectBitmap(obj);
2021 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
2022 bool is_los = mark_bitmap == nullptr;
2023 if (!is_los && mark_bitmap->Test(obj)) {
2024 LOG(INFO) << "holder is marked in the mark bit map.";
2025 } else if (is_los && los_bitmap->Test(obj)) {
2026 LOG(INFO) << "holder is marked in the los bit map.";
2027 } else {
2028 // If ref is on the allocation stack, then it is considered
2029 // mark/alive (but not necessarily on the live stack.)
2030 if (IsOnAllocStack(obj)) {
2031 LOG(INFO) << "holder is on the alloc stack.";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002032 } else {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002033 LOG(INFO) << "holder is not marked or on the alloc stack.";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002034 }
2035 }
2036 }
2037 }
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002038 LOG(INFO) << "offset=" << offset.SizeValue();
2039}
2040
2041void ConcurrentCopying::AssertToSpaceInvariantInNonMovingSpace(mirror::Object* obj,
2042 mirror::Object* ref) {
Roland Levillain001eff92018-01-24 14:24:33 +00002043 CHECK(!region_space_->HasAddress(ref)) << "obj=" << obj << " ref=" << ref;
Roland Levillainef012222017-06-21 16:28:06 +01002044 // In a non-moving space. Check that the ref is marked.
Mathieu Chartier763a31e2015-11-16 16:05:55 -08002045 if (immune_spaces_.ContainsObject(ref)) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002046 if (kUseBakerReadBarrier) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002047 // Immune object may not be gray if called from the GC.
2048 if (Thread::Current() == thread_running_gc_ && !gc_grays_immune_objects_) {
2049 return;
2050 }
Orion Hodson88591fe2018-03-06 13:35:43 +00002051 bool updated_all_immune_objects = updated_all_immune_objects_.load(std::memory_order_seq_cst);
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002052 CHECK(updated_all_immune_objects || ref->GetReadBarrierState() == ReadBarrier::GrayState())
2053 << "Unmarked immune space ref. obj=" << obj << " rb_state="
2054 << (obj != nullptr ? obj->GetReadBarrierState() : 0U)
2055 << " ref=" << ref << " ref rb_state=" << ref->GetReadBarrierState()
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002056 << " updated_all_immune_objects=" << updated_all_immune_objects;
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002057 }
2058 } else {
2059 accounting::ContinuousSpaceBitmap* mark_bitmap =
2060 heap_mark_bitmap_->GetContinuousSpaceBitmap(ref);
2061 accounting::LargeObjectBitmap* los_bitmap =
2062 heap_mark_bitmap_->GetLargeObjectBitmap(ref);
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002063 bool is_los = mark_bitmap == nullptr;
2064 if ((!is_los && mark_bitmap->Test(ref)) ||
2065 (is_los && los_bitmap->Test(ref))) {
2066 // OK.
2067 } else {
Roland Levillain2ae376f2018-01-30 11:35:11 +00002068 // If `ref` is on the allocation stack, then it may not be
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002069 // marked live, but considered marked/alive (but not
2070 // necessarily on the live stack).
Roland Levillain2ae376f2018-01-30 11:35:11 +00002071 CHECK(IsOnAllocStack(ref)) << "Unmarked ref that's not on the allocation stack."
2072 << " obj=" << obj
2073 << " ref=" << ref
2074 << " is_los=" << std::boolalpha << is_los << std::noboolalpha;
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002075 }
2076 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002077}
2078
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002079// Used to scan ref fields of an object.
Mathieu Chartiera07f5592016-06-16 11:44:28 -07002080class ConcurrentCopying::RefFieldsVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002081 public:
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002082 explicit RefFieldsVisitor(ConcurrentCopying* collector, Thread* const thread)
2083 : collector_(collector), thread_(thread) {}
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002084
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07002085 void operator()(mirror::Object* obj, MemberOffset offset, bool /* is_static */)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002086 const ALWAYS_INLINE REQUIRES_SHARED(Locks::mutator_lock_)
2087 REQUIRES_SHARED(Locks::heap_bitmap_lock_) {
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07002088 collector_->Process(obj, offset);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002089 }
2090
Mathieu Chartier31e88222016-10-14 18:43:19 -07002091 void operator()(ObjPtr<mirror::Class> klass, ObjPtr<mirror::Reference> ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002092 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002093 CHECK(klass->IsTypeOfReferenceClass());
2094 collector_->DelayReferenceReferent(klass, ref);
2095 }
2096
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002097 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002098 ALWAYS_INLINE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002099 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002100 if (!root->IsNull()) {
2101 VisitRoot(root);
2102 }
2103 }
2104
2105 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002106 ALWAYS_INLINE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002107 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002108 collector_->MarkRoot</*kGrayImmuneObject*/false>(thread_, root);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002109 }
2110
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002111 private:
2112 ConcurrentCopying* const collector_;
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002113 Thread* const thread_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002114};
2115
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002116inline void ConcurrentCopying::Scan(mirror::Object* to_ref) {
Hiroshi Yamauchi9b60d502017-02-03 15:09:26 -08002117 if (kDisallowReadBarrierDuringScan && !Runtime::Current()->IsActiveTransaction()) {
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07002118 // Avoid all read barriers during visit references to help performance.
Hiroshi Yamauchi9b60d502017-02-03 15:09:26 -08002119 // Don't do this in transaction mode because we may read the old value of an field which may
2120 // trigger read barriers.
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07002121 Thread::Current()->ModifyDebugDisallowReadBarrier(1);
2122 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002123 DCHECK(!region_space_->IsInFromSpace(to_ref));
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002124 DCHECK_EQ(Thread::Current(), thread_running_gc_);
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002125 RefFieldsVisitor visitor(this, thread_running_gc_);
Hiroshi Yamauchi5496f692016-02-17 13:29:59 -08002126 // Disable the read barrier for a performance reason.
2127 to_ref->VisitReferences</*kVisitNativeRoots*/true, kDefaultVerifyFlags, kWithoutReadBarrier>(
2128 visitor, visitor);
Hiroshi Yamauchi9b60d502017-02-03 15:09:26 -08002129 if (kDisallowReadBarrierDuringScan && !Runtime::Current()->IsActiveTransaction()) {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002130 thread_running_gc_->ModifyDebugDisallowReadBarrier(-1);
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07002131 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002132}
2133
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002134inline void ConcurrentCopying::Process(mirror::Object* obj, MemberOffset offset) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002135 DCHECK_EQ(Thread::Current(), thread_running_gc_);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002136 mirror::Object* ref = obj->GetFieldObject<
2137 mirror::Object, kVerifyNone, kWithoutReadBarrier, false>(offset);
Mathieu Chartier4ce0c762017-05-18 10:01:07 -07002138 mirror::Object* to_ref = Mark</*kGrayImmuneObject*/false, /*kFromGCThread*/true>(
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002139 thread_running_gc_,
Mathieu Chartier4ce0c762017-05-18 10:01:07 -07002140 ref,
2141 /*holder*/ obj,
2142 offset);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002143 if (to_ref == ref) {
2144 return;
2145 }
2146 // This may fail if the mutator writes to the field at the same time. But it's ok.
2147 mirror::Object* expected_ref = ref;
2148 mirror::Object* new_ref = to_ref;
2149 do {
2150 if (expected_ref !=
2151 obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier, false>(offset)) {
2152 // It was updated by the mutator.
2153 break;
2154 }
Roland Levillain2ae376f2018-01-30 11:35:11 +00002155 // Use release CAS to make sure threads reading the reference see contents of copied objects.
Mathieu Chartiera9746b92018-06-22 10:25:40 -07002156 } while (!obj->CasFieldObjectWithoutWriteBarrier<false, false, kVerifyNone>(
Mathieu Chartierfdd513d2017-06-01 11:26:50 -07002157 offset,
2158 expected_ref,
Mathieu Chartiera9746b92018-06-22 10:25:40 -07002159 new_ref,
2160 CASMode::kWeak,
2161 std::memory_order_release));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002162}
2163
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002164// Process some roots.
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002165inline void ConcurrentCopying::VisitRoots(
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002166 mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED) {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002167 Thread* const self = Thread::Current();
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002168 for (size_t i = 0; i < count; ++i) {
2169 mirror::Object** root = roots[i];
2170 mirror::Object* ref = *root;
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002171 mirror::Object* to_ref = Mark(self, ref);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002172 if (to_ref == ref) {
Mathieu Chartier4809d0a2015-04-07 10:39:04 -07002173 continue;
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002174 }
2175 Atomic<mirror::Object*>* addr = reinterpret_cast<Atomic<mirror::Object*>*>(root);
2176 mirror::Object* expected_ref = ref;
2177 mirror::Object* new_ref = to_ref;
2178 do {
Orion Hodson88591fe2018-03-06 13:35:43 +00002179 if (expected_ref != addr->load(std::memory_order_relaxed)) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002180 // It was updated by the mutator.
2181 break;
2182 }
Orion Hodson4557b382018-01-03 11:47:54 +00002183 } while (!addr->CompareAndSetWeakRelaxed(expected_ref, new_ref));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002184 }
2185}
2186
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002187template<bool kGrayImmuneObject>
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002188inline void ConcurrentCopying::MarkRoot(Thread* const self,
2189 mirror::CompressedReference<mirror::Object>* root) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002190 DCHECK(!root->IsNull());
2191 mirror::Object* const ref = root->AsMirrorPtr();
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002192 mirror::Object* to_ref = Mark<kGrayImmuneObject>(self, ref);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002193 if (to_ref != ref) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002194 auto* addr = reinterpret_cast<Atomic<mirror::CompressedReference<mirror::Object>>*>(root);
2195 auto expected_ref = mirror::CompressedReference<mirror::Object>::FromMirrorPtr(ref);
2196 auto new_ref = mirror::CompressedReference<mirror::Object>::FromMirrorPtr(to_ref);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002197 // If the cas fails, then it was updated by the mutator.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002198 do {
Orion Hodson88591fe2018-03-06 13:35:43 +00002199 if (ref != addr->load(std::memory_order_relaxed).AsMirrorPtr()) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002200 // It was updated by the mutator.
2201 break;
2202 }
Orion Hodson4557b382018-01-03 11:47:54 +00002203 } while (!addr->CompareAndSetWeakRelaxed(expected_ref, new_ref));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002204 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002205}
2206
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002207inline void ConcurrentCopying::VisitRoots(
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002208 mirror::CompressedReference<mirror::Object>** roots, size_t count,
2209 const RootInfo& info ATTRIBUTE_UNUSED) {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002210 Thread* const self = Thread::Current();
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002211 for (size_t i = 0; i < count; ++i) {
2212 mirror::CompressedReference<mirror::Object>* const root = roots[i];
2213 if (!root->IsNull()) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002214 // kGrayImmuneObject is true because this is used for the thread flip.
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002215 MarkRoot</*kGrayImmuneObject*/true>(self, root);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002216 }
2217 }
2218}
2219
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002220// Temporary set gc_grays_immune_objects_ to true in a scope if the current thread is GC.
2221class ConcurrentCopying::ScopedGcGraysImmuneObjects {
2222 public:
2223 explicit ScopedGcGraysImmuneObjects(ConcurrentCopying* collector)
2224 : collector_(collector), enabled_(false) {
2225 if (kUseBakerReadBarrier &&
2226 collector_->thread_running_gc_ == Thread::Current() &&
2227 !collector_->gc_grays_immune_objects_) {
2228 collector_->gc_grays_immune_objects_ = true;
2229 enabled_ = true;
2230 }
2231 }
2232
2233 ~ScopedGcGraysImmuneObjects() {
2234 if (kUseBakerReadBarrier &&
2235 collector_->thread_running_gc_ == Thread::Current() &&
2236 enabled_) {
2237 DCHECK(collector_->gc_grays_immune_objects_);
2238 collector_->gc_grays_immune_objects_ = false;
2239 }
2240 }
2241
2242 private:
2243 ConcurrentCopying* const collector_;
2244 bool enabled_;
2245};
2246
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002247// Fill the given memory block with a dummy object. Used to fill in a
2248// copy of objects that was lost in race.
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002249void ConcurrentCopying::FillWithDummyObject(Thread* const self,
2250 mirror::Object* dummy_obj,
2251 size_t byte_size) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002252 // GC doesn't gray immune objects while scanning immune objects. But we need to trigger the read
2253 // barriers here because we need the updated reference to the int array class, etc. Temporary set
2254 // gc_grays_immune_objects_ to true so that we won't cause a DCHECK failure in MarkImmuneSpace().
2255 ScopedGcGraysImmuneObjects scoped_gc_gray_immune_objects(this);
Roland Levillain14d90572015-07-16 10:52:26 +01002256 CHECK_ALIGNED(byte_size, kObjectAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002257 memset(dummy_obj, 0, byte_size);
Mathieu Chartierd6636d32016-07-28 11:02:38 -07002258 // Avoid going through read barrier for since kDisallowReadBarrierDuringScan may be enabled.
2259 // Explicitly mark to make sure to get an object in the to-space.
2260 mirror::Class* int_array_class = down_cast<mirror::Class*>(
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002261 Mark(self, GetClassRoot<mirror::IntArray, kWithoutReadBarrier>().Ptr()));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002262 CHECK(int_array_class != nullptr);
Andreas Gampe6c578712017-10-19 13:00:34 -07002263 if (ReadBarrier::kEnableToSpaceInvariantChecks) {
2264 AssertToSpaceInvariant(nullptr, MemberOffset(0), int_array_class);
2265 }
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07002266 size_t component_size = int_array_class->GetComponentSize<kWithoutReadBarrier>();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002267 CHECK_EQ(component_size, sizeof(int32_t));
2268 size_t data_offset = mirror::Array::DataOffset(component_size).SizeValue();
2269 if (data_offset > byte_size) {
2270 // An int array is too big. Use java.lang.Object.
Mathieu Chartier9aef9922017-04-23 13:53:50 -07002271 CHECK(java_lang_Object_ != nullptr);
Andreas Gampe6c578712017-10-19 13:00:34 -07002272 if (ReadBarrier::kEnableToSpaceInvariantChecks) {
2273 AssertToSpaceInvariant(nullptr, MemberOffset(0), java_lang_Object_);
2274 }
Mathieu Chartier3ed8ec12017-04-20 19:28:54 -07002275 CHECK_EQ(byte_size, (java_lang_Object_->GetObjectSize<kVerifyNone, kWithoutReadBarrier>()));
2276 dummy_obj->SetClass(java_lang_Object_);
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07002277 CHECK_EQ(byte_size, (dummy_obj->SizeOf<kVerifyNone>()));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002278 } else {
2279 // Use an int array.
2280 dummy_obj->SetClass(int_array_class);
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07002281 CHECK((dummy_obj->IsArrayInstance<kVerifyNone, kWithoutReadBarrier>()));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002282 int32_t length = (byte_size - data_offset) / component_size;
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07002283 mirror::Array* dummy_arr = dummy_obj->AsArray<kVerifyNone, kWithoutReadBarrier>();
2284 dummy_arr->SetLength(length);
2285 CHECK_EQ(dummy_arr->GetLength(), length)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002286 << "byte_size=" << byte_size << " length=" << length
2287 << " component_size=" << component_size << " data_offset=" << data_offset;
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07002288 CHECK_EQ(byte_size, (dummy_obj->SizeOf<kVerifyNone>()))
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002289 << "byte_size=" << byte_size << " length=" << length
2290 << " component_size=" << component_size << " data_offset=" << data_offset;
2291 }
2292}
2293
2294// Reuse the memory blocks that were copy of objects that were lost in race.
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002295mirror::Object* ConcurrentCopying::AllocateInSkippedBlock(Thread* const self, size_t alloc_size) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002296 // Try to reuse the blocks that were unused due to CAS failures.
Roland Levillain14d90572015-07-16 10:52:26 +01002297 CHECK_ALIGNED(alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002298 size_t min_object_size = RoundUp(sizeof(mirror::Object), space::RegionSpace::kAlignment);
Mathieu Chartierd6636d32016-07-28 11:02:38 -07002299 size_t byte_size;
2300 uint8_t* addr;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002301 {
Mathieu Chartierd6636d32016-07-28 11:02:38 -07002302 MutexLock mu(self, skipped_blocks_lock_);
2303 auto it = skipped_blocks_map_.lower_bound(alloc_size);
2304 if (it == skipped_blocks_map_.end()) {
2305 // Not found.
2306 return nullptr;
2307 }
2308 byte_size = it->first;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002309 CHECK_GE(byte_size, alloc_size);
2310 if (byte_size > alloc_size && byte_size - alloc_size < min_object_size) {
2311 // If remainder would be too small for a dummy object, retry with a larger request size.
2312 it = skipped_blocks_map_.lower_bound(alloc_size + min_object_size);
2313 if (it == skipped_blocks_map_.end()) {
2314 // Not found.
2315 return nullptr;
2316 }
Roland Levillain14d90572015-07-16 10:52:26 +01002317 CHECK_ALIGNED(it->first - alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002318 CHECK_GE(it->first - alloc_size, min_object_size)
2319 << "byte_size=" << byte_size << " it->first=" << it->first << " alloc_size=" << alloc_size;
2320 }
Mathieu Chartierd6636d32016-07-28 11:02:38 -07002321 // Found a block.
2322 CHECK(it != skipped_blocks_map_.end());
2323 byte_size = it->first;
2324 addr = it->second;
2325 CHECK_GE(byte_size, alloc_size);
2326 CHECK(region_space_->IsInToSpace(reinterpret_cast<mirror::Object*>(addr)));
2327 CHECK_ALIGNED(byte_size, space::RegionSpace::kAlignment);
2328 if (kVerboseMode) {
2329 LOG(INFO) << "Reusing skipped bytes : " << reinterpret_cast<void*>(addr) << ", " << byte_size;
2330 }
2331 skipped_blocks_map_.erase(it);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002332 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002333 memset(addr, 0, byte_size);
2334 if (byte_size > alloc_size) {
2335 // Return the remainder to the map.
Roland Levillain14d90572015-07-16 10:52:26 +01002336 CHECK_ALIGNED(byte_size - alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002337 CHECK_GE(byte_size - alloc_size, min_object_size);
Mathieu Chartierd6636d32016-07-28 11:02:38 -07002338 // FillWithDummyObject may mark an object, avoid holding skipped_blocks_lock_ to prevent lock
2339 // violation and possible deadlock. The deadlock case is a recursive case:
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002340 // FillWithDummyObject -> Mark(IntArray.class) -> Copy -> AllocateInSkippedBlock.
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002341 FillWithDummyObject(self,
2342 reinterpret_cast<mirror::Object*>(addr + alloc_size),
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002343 byte_size - alloc_size);
2344 CHECK(region_space_->IsInToSpace(reinterpret_cast<mirror::Object*>(addr + alloc_size)));
Mathieu Chartierd6636d32016-07-28 11:02:38 -07002345 {
2346 MutexLock mu(self, skipped_blocks_lock_);
2347 skipped_blocks_map_.insert(std::make_pair(byte_size - alloc_size, addr + alloc_size));
2348 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002349 }
2350 return reinterpret_cast<mirror::Object*>(addr);
2351}
2352
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002353mirror::Object* ConcurrentCopying::Copy(Thread* const self,
2354 mirror::Object* from_ref,
Mathieu Chartieref496d92017-04-28 18:58:59 -07002355 mirror::Object* holder,
2356 MemberOffset offset) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002357 DCHECK(region_space_->IsInFromSpace(from_ref));
Mathieu Chartieref496d92017-04-28 18:58:59 -07002358 // If the class pointer is null, the object is invalid. This could occur for a dangling pointer
2359 // from a previous GC that is either inside or outside the allocated region.
2360 mirror::Class* klass = from_ref->GetClass<kVerifyNone, kWithoutReadBarrier>();
2361 if (UNLIKELY(klass == nullptr)) {
2362 heap_->GetVerification()->LogHeapCorruption(holder, offset, from_ref, /* fatal */ true);
2363 }
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07002364 // There must not be a read barrier to avoid nested RB that might violate the to-space invariant.
2365 // Note that from_ref is a from space ref so the SizeOf() call will access the from-space meta
2366 // objects, but it's ok and necessary.
2367 size_t obj_size = from_ref->SizeOf<kDefaultVerifyFlags>();
Nicolas Geoffray4b361a82017-07-06 15:30:10 +01002368 size_t region_space_alloc_size = (obj_size <= space::RegionSpace::kRegionSize)
2369 ? RoundUp(obj_size, space::RegionSpace::kAlignment)
2370 : RoundUp(obj_size, space::RegionSpace::kRegionSize);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002371 size_t region_space_bytes_allocated = 0U;
2372 size_t non_moving_space_bytes_allocated = 0U;
2373 size_t bytes_allocated = 0U;
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07002374 size_t dummy;
Lokesh Gidraf2a69312018-03-27 18:48:59 -07002375 bool fall_back_to_non_moving = false;
Lokesh Gidrab4f15412018-01-05 18:29:34 -08002376 mirror::Object* to_ref = region_space_->AllocNonvirtual</*kForEvac*/ true>(
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07002377 region_space_alloc_size, &region_space_bytes_allocated, nullptr, &dummy);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002378 bytes_allocated = region_space_bytes_allocated;
Lokesh Gidraf2a69312018-03-27 18:48:59 -07002379 if (LIKELY(to_ref != nullptr)) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002380 DCHECK_EQ(region_space_alloc_size, region_space_bytes_allocated);
Lokesh Gidraf2a69312018-03-27 18:48:59 -07002381 } else {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002382 // Failed to allocate in the region space. Try the skipped blocks.
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002383 to_ref = AllocateInSkippedBlock(self, region_space_alloc_size);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002384 if (to_ref != nullptr) {
2385 // Succeeded to allocate in a skipped block.
2386 if (heap_->use_tlab_) {
2387 // This is necessary for the tlab case as it's not accounted in the space.
2388 region_space_->RecordAlloc(to_ref);
2389 }
2390 bytes_allocated = region_space_alloc_size;
Lokesh Gidraf2a69312018-03-27 18:48:59 -07002391 heap_->num_bytes_allocated_.fetch_sub(bytes_allocated, std::memory_order_seq_cst);
2392 to_space_bytes_skipped_.fetch_sub(bytes_allocated, std::memory_order_seq_cst);
2393 to_space_objects_skipped_.fetch_sub(1, std::memory_order_seq_cst);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002394 } else {
2395 // Fall back to the non-moving space.
2396 fall_back_to_non_moving = true;
2397 if (kVerboseMode) {
2398 LOG(INFO) << "Out of memory in the to-space. Fall back to non-moving. skipped_bytes="
Orion Hodson88591fe2018-03-06 13:35:43 +00002399 << to_space_bytes_skipped_.load(std::memory_order_seq_cst)
2400 << " skipped_objects="
2401 << to_space_objects_skipped_.load(std::memory_order_seq_cst);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002402 }
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002403 to_ref = heap_->non_moving_space_->Alloc(self, obj_size,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07002404 &non_moving_space_bytes_allocated, nullptr, &dummy);
Mathieu Chartierb01335c2017-03-22 13:15:01 -07002405 if (UNLIKELY(to_ref == nullptr)) {
2406 LOG(FATAL_WITHOUT_ABORT) << "Fall-back non-moving space allocation failed for a "
2407 << obj_size << " byte object in region type "
2408 << region_space_->GetRegionType(from_ref);
2409 LOG(FATAL) << "Object address=" << from_ref << " type=" << from_ref->PrettyTypeOf();
2410 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002411 bytes_allocated = non_moving_space_bytes_allocated;
2412 // Mark it in the mark bitmap.
2413 accounting::ContinuousSpaceBitmap* mark_bitmap =
2414 heap_mark_bitmap_->GetContinuousSpaceBitmap(to_ref);
2415 CHECK(mark_bitmap != nullptr);
2416 CHECK(!mark_bitmap->AtomicTestAndSet(to_ref));
2417 }
2418 }
2419 DCHECK(to_ref != nullptr);
2420
Mathieu Chartierd818adb2016-09-15 13:12:47 -07002421 // Copy the object excluding the lock word since that is handled in the loop.
Mathieu Chartieref496d92017-04-28 18:58:59 -07002422 to_ref->SetClass(klass);
Mathieu Chartierd818adb2016-09-15 13:12:47 -07002423 const size_t kObjectHeaderSize = sizeof(mirror::Object);
2424 DCHECK_GE(obj_size, kObjectHeaderSize);
2425 static_assert(kObjectHeaderSize == sizeof(mirror::HeapReference<mirror::Class>) +
2426 sizeof(LockWord),
2427 "Object header size does not match");
2428 // Memcpy can tear for words since it may do byte copy. It is only safe to do this since the
2429 // object in the from space is immutable other than the lock word. b/31423258
2430 memcpy(reinterpret_cast<uint8_t*>(to_ref) + kObjectHeaderSize,
2431 reinterpret_cast<const uint8_t*>(from_ref) + kObjectHeaderSize,
2432 obj_size - kObjectHeaderSize);
2433
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002434 // Attempt to install the forward pointer. This is in a loop as the
2435 // lock word atomic write can fail.
2436 while (true) {
Mathieu Chartierd818adb2016-09-15 13:12:47 -07002437 LockWord old_lock_word = from_ref->GetLockWord(false);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002438
2439 if (old_lock_word.GetState() == LockWord::kForwardingAddress) {
2440 // Lost the race. Another thread (either GC or mutator) stored
2441 // the forwarding pointer first. Make the lost copy (to_ref)
2442 // look like a valid but dead (dummy) object and keep it for
2443 // future reuse.
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002444 FillWithDummyObject(self, to_ref, bytes_allocated);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002445 if (!fall_back_to_non_moving) {
2446 DCHECK(region_space_->IsInToSpace(to_ref));
2447 if (bytes_allocated > space::RegionSpace::kRegionSize) {
2448 // Free the large alloc.
Lokesh Gidrab4f15412018-01-05 18:29:34 -08002449 region_space_->FreeLarge</*kForEvac*/ true>(to_ref, bytes_allocated);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002450 } else {
2451 // Record the lost copy for later reuse.
Orion Hodson88591fe2018-03-06 13:35:43 +00002452 heap_->num_bytes_allocated_.fetch_add(bytes_allocated, std::memory_order_seq_cst);
2453 to_space_bytes_skipped_.fetch_add(bytes_allocated, std::memory_order_seq_cst);
2454 to_space_objects_skipped_.fetch_add(1, std::memory_order_seq_cst);
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002455 MutexLock mu(self, skipped_blocks_lock_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002456 skipped_blocks_map_.insert(std::make_pair(bytes_allocated,
2457 reinterpret_cast<uint8_t*>(to_ref)));
2458 }
2459 } else {
2460 DCHECK(heap_->non_moving_space_->HasAddress(to_ref));
2461 DCHECK_EQ(bytes_allocated, non_moving_space_bytes_allocated);
2462 // Free the non-moving-space chunk.
2463 accounting::ContinuousSpaceBitmap* mark_bitmap =
2464 heap_mark_bitmap_->GetContinuousSpaceBitmap(to_ref);
2465 CHECK(mark_bitmap != nullptr);
2466 CHECK(mark_bitmap->Clear(to_ref));
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002467 heap_->non_moving_space_->Free(self, to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002468 }
2469
2470 // Get the winner's forward ptr.
2471 mirror::Object* lost_fwd_ptr = to_ref;
2472 to_ref = reinterpret_cast<mirror::Object*>(old_lock_word.ForwardingAddress());
2473 CHECK(to_ref != nullptr);
2474 CHECK_NE(to_ref, lost_fwd_ptr);
Mathieu Chartierdfcd6f42016-09-13 10:02:48 -07002475 CHECK(region_space_->IsInToSpace(to_ref) || heap_->non_moving_space_->HasAddress(to_ref))
2476 << "to_ref=" << to_ref << " " << heap_->DumpSpaces();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002477 CHECK_NE(to_ref->GetLockWord(false).GetState(), LockWord::kForwardingAddress);
2478 return to_ref;
2479 }
2480
Mathieu Chartierd818adb2016-09-15 13:12:47 -07002481 // Copy the old lock word over since we did not copy it yet.
2482 to_ref->SetLockWord(old_lock_word, false);
Hiroshi Yamauchi60f63f52015-04-23 16:12:40 -07002483 // Set the gray ptr.
2484 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002485 to_ref->SetReadBarrierState(ReadBarrier::GrayState());
Hiroshi Yamauchi60f63f52015-04-23 16:12:40 -07002486 }
2487
Mathieu Chartiera8131262016-11-29 17:55:19 -08002488 // Do a fence to prevent the field CAS in ConcurrentCopying::Process from possibly reordering
2489 // before the object copy.
Orion Hodson27b96762018-03-13 16:06:57 +00002490 std::atomic_thread_fence(std::memory_order_release);
Mathieu Chartiera8131262016-11-29 17:55:19 -08002491
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002492 LockWord new_lock_word = LockWord::FromForwardingAddress(reinterpret_cast<size_t>(to_ref));
2493
2494 // Try to atomically write the fwd ptr.
Mathieu Chartier42c2e502018-06-19 12:30:56 -07002495 bool success = from_ref->CasLockWord(old_lock_word,
2496 new_lock_word,
2497 CASMode::kWeak,
2498 std::memory_order_relaxed);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002499 if (LIKELY(success)) {
2500 // The CAS succeeded.
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002501 DCHECK(thread_running_gc_ != nullptr);
2502 if (LIKELY(self == thread_running_gc_)) {
2503 objects_moved_gc_thread_ += 1;
2504 bytes_moved_gc_thread_ += region_space_alloc_size;
2505 } else {
2506 objects_moved_.fetch_add(1, std::memory_order_relaxed);
2507 bytes_moved_.fetch_add(region_space_alloc_size, std::memory_order_relaxed);
2508 }
2509
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002510 if (LIKELY(!fall_back_to_non_moving)) {
2511 DCHECK(region_space_->IsInToSpace(to_ref));
2512 } else {
2513 DCHECK(heap_->non_moving_space_->HasAddress(to_ref));
2514 DCHECK_EQ(bytes_allocated, non_moving_space_bytes_allocated);
2515 }
2516 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002517 DCHECK(to_ref->GetReadBarrierState() == ReadBarrier::GrayState());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002518 }
2519 DCHECK(GetFwdPtr(from_ref) == to_ref);
2520 CHECK_NE(to_ref->GetLockWord(false).GetState(), LockWord::kForwardingAddress);
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002521 PushOntoMarkStack(self, to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002522 return to_ref;
2523 } else {
2524 // The CAS failed. It may have lost the race or may have failed
2525 // due to monitor/hashcode ops. Either way, retry.
2526 }
2527 }
2528}
2529
2530mirror::Object* ConcurrentCopying::IsMarked(mirror::Object* from_ref) {
2531 DCHECK(from_ref != nullptr);
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08002532 space::RegionSpace::RegionType rtype = region_space_->GetRegionType(from_ref);
2533 if (rtype == space::RegionSpace::RegionType::kRegionTypeToSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002534 // It's already marked.
2535 return from_ref;
2536 }
2537 mirror::Object* to_ref;
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08002538 if (rtype == space::RegionSpace::RegionType::kRegionTypeFromSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002539 to_ref = GetFwdPtr(from_ref);
2540 DCHECK(to_ref == nullptr || region_space_->IsInToSpace(to_ref) ||
2541 heap_->non_moving_space_->HasAddress(to_ref))
2542 << "from_ref=" << from_ref << " to_ref=" << to_ref;
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08002543 } else if (rtype == space::RegionSpace::RegionType::kRegionTypeUnevacFromSpace) {
Mathieu Chartierc381c362016-08-23 13:27:53 -07002544 if (IsMarkedInUnevacFromSpace(from_ref)) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002545 to_ref = from_ref;
2546 } else {
2547 to_ref = nullptr;
2548 }
2549 } else {
Roland Levillain001eff92018-01-24 14:24:33 +00002550 // At this point, `from_ref` should not be in the region space
2551 // (i.e. within an "unused" region).
2552 DCHECK(!region_space_->HasAddress(from_ref)) << from_ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002553 // from_ref is in a non-moving space.
Mathieu Chartier763a31e2015-11-16 16:05:55 -08002554 if (immune_spaces_.ContainsObject(from_ref)) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002555 // An immune object is alive.
2556 to_ref = from_ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002557 } else {
2558 // Non-immune non-moving space. Use the mark bitmap.
2559 accounting::ContinuousSpaceBitmap* mark_bitmap =
2560 heap_mark_bitmap_->GetContinuousSpaceBitmap(from_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002561 bool is_los = mark_bitmap == nullptr;
2562 if (!is_los && mark_bitmap->Test(from_ref)) {
2563 // Already marked.
2564 to_ref = from_ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002565 } else {
Mathieu Chartier47863bb2017-08-04 11:30:27 -07002566 accounting::LargeObjectBitmap* los_bitmap =
2567 heap_mark_bitmap_->GetLargeObjectBitmap(from_ref);
2568 // We may not have a large object space for dex2oat, don't assume it exists.
2569 if (los_bitmap == nullptr) {
2570 CHECK(heap_->GetLargeObjectsSpace() == nullptr)
2571 << "LOS bitmap covers the entire address range " << from_ref
2572 << " " << heap_->DumpSpaces();
2573 }
2574 if (los_bitmap != nullptr && is_los && los_bitmap->Test(from_ref)) {
2575 // Already marked in LOS.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002576 to_ref = from_ref;
2577 } else {
2578 // Not marked.
Mathieu Chartier47863bb2017-08-04 11:30:27 -07002579 if (IsOnAllocStack(from_ref)) {
2580 // If on the allocation stack, it's considered marked.
2581 to_ref = from_ref;
2582 } else {
2583 // Not marked.
2584 to_ref = nullptr;
2585 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002586 }
2587 }
2588 }
2589 }
2590 return to_ref;
2591}
2592
2593bool ConcurrentCopying::IsOnAllocStack(mirror::Object* ref) {
Hans Boehmcc55e1d2017-07-27 15:28:07 -07002594 // TODO: Explain why this is here. What release operation does it pair with?
Orion Hodson27b96762018-03-13 16:06:57 +00002595 std::atomic_thread_fence(std::memory_order_acquire);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002596 accounting::ObjectStack* alloc_stack = GetAllocationStack();
Mathieu Chartiercb535da2015-01-23 13:50:03 -08002597 return alloc_stack->Contains(ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002598}
2599
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002600mirror::Object* ConcurrentCopying::MarkNonMoving(Thread* const self,
2601 mirror::Object* ref,
Mathieu Chartier1ca68902017-04-18 11:26:22 -07002602 mirror::Object* holder,
2603 MemberOffset offset) {
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002604 // ref is in a non-moving space (from_ref == to_ref).
2605 DCHECK(!region_space_->HasAddress(ref)) << ref;
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002606 DCHECK(!immune_spaces_.ContainsObject(ref));
2607 // Use the mark bitmap.
2608 accounting::ContinuousSpaceBitmap* mark_bitmap =
2609 heap_mark_bitmap_->GetContinuousSpaceBitmap(ref);
2610 accounting::LargeObjectBitmap* los_bitmap =
2611 heap_mark_bitmap_->GetLargeObjectBitmap(ref);
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002612 bool is_los = mark_bitmap == nullptr;
2613 if (!is_los && mark_bitmap->Test(ref)) {
2614 // Already marked.
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002615 } else if (is_los && los_bitmap->Test(ref)) {
2616 // Already marked in LOS.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002617 } else {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002618 // Not marked.
2619 if (IsOnAllocStack(ref)) {
2620 // If it's on the allocation stack, it's considered marked. Keep it white.
2621 // Objects on the allocation stack need not be marked.
2622 if (!is_los) {
2623 DCHECK(!mark_bitmap->Test(ref));
2624 } else {
2625 DCHECK(!los_bitmap->Test(ref));
Nicolas Geoffrayddeb1722016-06-28 08:25:59 +00002626 }
Nicolas Geoffrayddeb1722016-06-28 08:25:59 +00002627 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002628 DCHECK_EQ(ref->GetReadBarrierState(), ReadBarrier::WhiteState());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002629 }
2630 } else {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002631 // For the baker-style RB, we need to handle 'false-gray' cases. See the
2632 // kRegionTypeUnevacFromSpace-case comment in Mark().
2633 if (kUseBakerReadBarrier) {
2634 // Test the bitmap first to reduce the chance of false gray cases.
2635 if ((!is_los && mark_bitmap->Test(ref)) ||
2636 (is_los && los_bitmap->Test(ref))) {
2637 return ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002638 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002639 }
Mathieu Chartier1ca68902017-04-18 11:26:22 -07002640 if (is_los && !IsAligned<kPageSize>(ref)) {
2641 // Ref is a large object that is not aligned, it must be heap corruption. Dump data before
2642 // AtomicSetReadBarrierState since it will fault if the address is not valid.
Mathieu Chartieref496d92017-04-28 18:58:59 -07002643 heap_->GetVerification()->LogHeapCorruption(holder, offset, ref, /* fatal */ true);
Mathieu Chartier1ca68902017-04-18 11:26:22 -07002644 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002645 // Not marked or on the allocation stack. Try to mark it.
2646 // This may or may not succeed, which is ok.
2647 bool cas_success = false;
2648 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002649 cas_success = ref->AtomicSetReadBarrierState(ReadBarrier::WhiteState(),
2650 ReadBarrier::GrayState());
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002651 }
2652 if (!is_los && mark_bitmap->AtomicTestAndSet(ref)) {
2653 // Already marked.
2654 if (kUseBakerReadBarrier && cas_success &&
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002655 ref->GetReadBarrierState() == ReadBarrier::GrayState()) {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002656 PushOntoFalseGrayStack(self, ref);
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002657 }
2658 } else if (is_los && los_bitmap->AtomicTestAndSet(ref)) {
2659 // Already marked in LOS.
2660 if (kUseBakerReadBarrier && cas_success &&
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002661 ref->GetReadBarrierState() == ReadBarrier::GrayState()) {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002662 PushOntoFalseGrayStack(self, ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002663 }
2664 } else {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002665 // Newly marked.
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08002666 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002667 DCHECK_EQ(ref->GetReadBarrierState(), ReadBarrier::GrayState());
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08002668 }
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002669 PushOntoMarkStack(self, ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002670 }
2671 }
2672 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002673 return ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002674}
2675
2676void ConcurrentCopying::FinishPhase() {
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -08002677 Thread* const self = Thread::Current();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002678 {
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -08002679 MutexLock mu(self, mark_stack_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002680 CHECK_EQ(pooled_mark_stacks_.size(), kMarkStackPoolSize);
2681 }
Mathieu Chartiera1467d02017-02-22 09:22:50 -08002682 // kVerifyNoMissingCardMarks relies on the region space cards not being cleared to avoid false
2683 // positives.
2684 if (!kVerifyNoMissingCardMarks) {
Mathieu Chartier6e6078a2016-10-24 15:45:41 -07002685 TimingLogger::ScopedTiming split("ClearRegionSpaceCards", GetTimings());
2686 // We do not currently use the region space cards at all, madvise them away to save ram.
2687 heap_->GetCardTable()->ClearCardRange(region_space_->Begin(), region_space_->Limit());
Mathieu Chartier6e6078a2016-10-24 15:45:41 -07002688 }
2689 {
2690 MutexLock mu(self, skipped_blocks_lock_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002691 skipped_blocks_map_.clear();
2692 }
Mathieu Chartier56fe2582016-07-14 13:30:03 -07002693 {
2694 ReaderMutexLock mu(self, *Locks::mutator_lock_);
Mathieu Chartier21328a12016-07-22 10:47:45 -07002695 {
2696 WriterMutexLock mu2(self, *Locks::heap_bitmap_lock_);
2697 heap_->ClearMarkedObjects();
2698 }
2699 if (kUseBakerReadBarrier && kFilterModUnionCards) {
2700 TimingLogger::ScopedTiming split("FilterModUnionCards", GetTimings());
2701 ReaderMutexLock mu2(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier21328a12016-07-22 10:47:45 -07002702 for (space::ContinuousSpace* space : immune_spaces_.GetSpaces()) {
2703 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
Mathieu Chartier6e6078a2016-10-24 15:45:41 -07002704 accounting::ModUnionTable* table = heap_->FindModUnionTableFromSpace(space);
Mathieu Chartier21328a12016-07-22 10:47:45 -07002705 // Filter out cards that don't need to be set.
2706 if (table != nullptr) {
2707 table->FilterCards();
2708 }
2709 }
2710 }
Mathieu Chartier36a270a2016-07-28 18:08:51 -07002711 if (kUseBakerReadBarrier) {
2712 TimingLogger::ScopedTiming split("EmptyRBMarkBitStack", GetTimings());
Mathieu Chartier6e6078a2016-10-24 15:45:41 -07002713 DCHECK(rb_mark_bit_stack_ != nullptr);
Mathieu Chartier36a270a2016-07-28 18:08:51 -07002714 const auto* limit = rb_mark_bit_stack_->End();
2715 for (StackReference<mirror::Object>* it = rb_mark_bit_stack_->Begin(); it != limit; ++it) {
Roland Levillain001eff92018-01-24 14:24:33 +00002716 CHECK(it->AsMirrorPtr()->AtomicSetMarkBit(1, 0))
2717 << "rb_mark_bit_stack_->Begin()" << rb_mark_bit_stack_->Begin() << '\n'
2718 << "rb_mark_bit_stack_->End()" << rb_mark_bit_stack_->End() << '\n'
2719 << "rb_mark_bit_stack_->IsFull()"
2720 << std::boolalpha << rb_mark_bit_stack_->IsFull() << std::noboolalpha << '\n'
2721 << DumpReferenceInfo(it->AsMirrorPtr(), "*it");
Mathieu Chartier36a270a2016-07-28 18:08:51 -07002722 }
2723 rb_mark_bit_stack_->Reset();
2724 }
Mathieu Chartier56fe2582016-07-14 13:30:03 -07002725 }
2726 if (measure_read_barrier_slow_path_) {
2727 MutexLock mu(self, rb_slow_path_histogram_lock_);
Orion Hodson88591fe2018-03-06 13:35:43 +00002728 rb_slow_path_time_histogram_.AdjustAndAddValue(
2729 rb_slow_path_ns_.load(std::memory_order_relaxed));
2730 rb_slow_path_count_total_ += rb_slow_path_count_.load(std::memory_order_relaxed);
2731 rb_slow_path_count_gc_total_ += rb_slow_path_count_gc_.load(std::memory_order_relaxed);
Mathieu Chartier56fe2582016-07-14 13:30:03 -07002732 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002733}
2734
Hiroshi Yamauchi65f5f242016-12-19 11:44:47 -08002735bool ConcurrentCopying::IsNullOrMarkedHeapReference(mirror::HeapReference<mirror::Object>* field,
2736 bool do_atomic_update) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002737 mirror::Object* from_ref = field->AsMirrorPtr();
Hiroshi Yamauchi65f5f242016-12-19 11:44:47 -08002738 if (from_ref == nullptr) {
2739 return true;
2740 }
Mathieu Chartier97509952015-07-13 14:35:43 -07002741 mirror::Object* to_ref = IsMarked(from_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002742 if (to_ref == nullptr) {
2743 return false;
2744 }
2745 if (from_ref != to_ref) {
Hiroshi Yamauchi65f5f242016-12-19 11:44:47 -08002746 if (do_atomic_update) {
2747 do {
2748 if (field->AsMirrorPtr() != from_ref) {
2749 // Concurrently overwritten by a mutator.
2750 break;
2751 }
2752 } while (!field->CasWeakRelaxed(from_ref, to_ref));
2753 } else {
Hans Boehmcc55e1d2017-07-27 15:28:07 -07002754 // TODO: Why is this seq_cst when the above is relaxed? Document memory ordering.
2755 field->Assign</* kIsVolatile */ true>(to_ref);
Hiroshi Yamauchi65f5f242016-12-19 11:44:47 -08002756 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002757 }
2758 return true;
2759}
2760
Mathieu Chartier97509952015-07-13 14:35:43 -07002761mirror::Object* ConcurrentCopying::MarkObject(mirror::Object* from_ref) {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002762 return Mark(Thread::Current(), from_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002763}
2764
Mathieu Chartier31e88222016-10-14 18:43:19 -07002765void ConcurrentCopying::DelayReferenceReferent(ObjPtr<mirror::Class> klass,
2766 ObjPtr<mirror::Reference> reference) {
Mathieu Chartier97509952015-07-13 14:35:43 -07002767 heap_->GetReferenceProcessor()->DelayReferenceReferent(klass, reference, this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002768}
2769
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002770void ConcurrentCopying::ProcessReferences(Thread* self) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002771 TimingLogger::ScopedTiming split("ProcessReferences", GetTimings());
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002772 // 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 -08002773 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
2774 GetHeap()->GetReferenceProcessor()->ProcessReferences(
Mathieu Chartier97509952015-07-13 14:35:43 -07002775 true /*concurrent*/, GetTimings(), GetCurrentIteration()->GetClearSoftReferences(), this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002776}
2777
2778void ConcurrentCopying::RevokeAllThreadLocalBuffers() {
2779 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
2780 region_space_->RevokeAllThreadLocalBuffers();
2781}
2782
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002783mirror::Object* ConcurrentCopying::MarkFromReadBarrierWithMeasurements(Thread* const self,
2784 mirror::Object* from_ref) {
2785 if (self != thread_running_gc_) {
Orion Hodson88591fe2018-03-06 13:35:43 +00002786 rb_slow_path_count_.fetch_add(1u, std::memory_order_relaxed);
Mathieu Chartier56fe2582016-07-14 13:30:03 -07002787 } else {
Orion Hodson88591fe2018-03-06 13:35:43 +00002788 rb_slow_path_count_gc_.fetch_add(1u, std::memory_order_relaxed);
Mathieu Chartier56fe2582016-07-14 13:30:03 -07002789 }
2790 ScopedTrace tr(__FUNCTION__);
2791 const uint64_t start_time = measure_read_barrier_slow_path_ ? NanoTime() : 0u;
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002792 mirror::Object* ret = Mark(self, from_ref);
Mathieu Chartier56fe2582016-07-14 13:30:03 -07002793 if (measure_read_barrier_slow_path_) {
Orion Hodson88591fe2018-03-06 13:35:43 +00002794 rb_slow_path_ns_.fetch_add(NanoTime() - start_time, std::memory_order_relaxed);
Mathieu Chartier56fe2582016-07-14 13:30:03 -07002795 }
2796 return ret;
2797}
2798
2799void ConcurrentCopying::DumpPerformanceInfo(std::ostream& os) {
2800 GarbageCollector::DumpPerformanceInfo(os);
2801 MutexLock mu(Thread::Current(), rb_slow_path_histogram_lock_);
2802 if (rb_slow_path_time_histogram_.SampleSize() > 0) {
2803 Histogram<uint64_t>::CumulativeData cumulative_data;
2804 rb_slow_path_time_histogram_.CreateHistogram(&cumulative_data);
2805 rb_slow_path_time_histogram_.PrintConfidenceIntervals(os, 0.99, cumulative_data);
2806 }
2807 if (rb_slow_path_count_total_ > 0) {
2808 os << "Slow path count " << rb_slow_path_count_total_ << "\n";
2809 }
2810 if (rb_slow_path_count_gc_total_ > 0) {
2811 os << "GC slow path count " << rb_slow_path_count_gc_total_ << "\n";
2812 }
Orion Hodson88591fe2018-03-06 13:35:43 +00002813 os << "Cumulative bytes moved "
2814 << cumulative_bytes_moved_.load(std::memory_order_relaxed) << "\n";
2815 os << "Cumulative objects moved "
2816 << cumulative_objects_moved_.load(std::memory_order_relaxed) << "\n";
Lokesh Gidra29895822017-12-15 15:37:40 -08002817
2818 os << "Peak regions allocated "
Lokesh Gidrab4f15412018-01-05 18:29:34 -08002819 << region_space_->GetMaxPeakNumNonFreeRegions() << " ("
2820 << PrettySize(region_space_->GetMaxPeakNumNonFreeRegions() * space::RegionSpace::kRegionSize)
2821 << ") / " << region_space_->GetNumRegions() / 2 << " ("
2822 << PrettySize(region_space_->GetNumRegions() * space::RegionSpace::kRegionSize / 2)
Lokesh Gidra29895822017-12-15 15:37:40 -08002823 << ")\n";
Mathieu Chartier56fe2582016-07-14 13:30:03 -07002824}
2825
Hiroshi Yamauchid5307ec2014-03-27 21:07:51 -07002826} // namespace collector
2827} // namespace gc
2828} // namespace art