blob: 23bc7a20ef8617a6825795e5645700a0d5f4841d [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;
Roland Levillainb1e1dc32018-07-10 19:19:31 +010063// Size (in the number of objects) of the sweep array free buffer.
64static constexpr size_t kSweepArrayChunkFreeSize = 1024;
Mathieu Chartiera1467d02017-02-22 09:22:50 -080065// Verify that there are no missing card marks.
66static constexpr bool kVerifyNoMissingCardMarks = kIsDebugBuild;
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -070067
Mathieu Chartier56fe2582016-07-14 13:30:03 -070068ConcurrentCopying::ConcurrentCopying(Heap* heap,
Mathieu Chartier8d1a9962016-08-17 16:39:45 -070069 bool young_gen,
Mathieu Chartier56fe2582016-07-14 13:30:03 -070070 const std::string& name_prefix,
71 bool measure_read_barrier_slow_path)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080072 : GarbageCollector(heap,
73 name_prefix + (name_prefix.empty() ? "" : " ") +
Hiroshi Yamauchi88e08162017-01-06 15:03:26 -080074 "concurrent copying"),
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070075 region_space_(nullptr), gc_barrier_(new Barrier(0)),
76 gc_mark_stack_(accounting::ObjectStack::Create("concurrent copying gc mark stack",
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -070077 kDefaultGcMarkStackSize,
78 kDefaultGcMarkStackSize)),
Mathieu Chartier36a270a2016-07-28 18:08:51 -070079 rb_mark_bit_stack_(accounting::ObjectStack::Create("rb copying gc mark stack",
80 kReadBarrierMarkStackSize,
81 kReadBarrierMarkStackSize)),
82 rb_mark_bit_stack_full_(false),
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070083 mark_stack_lock_("concurrent copying mark stack lock", kMarkSweepMarkStackLock),
84 thread_running_gc_(nullptr),
Andreas Gamped9911ee2017-03-27 13:27:24 -070085 is_marking_(false),
Mathieu Chartier3768ade2017-05-02 14:04:39 -070086 is_using_read_barrier_entrypoints_(false),
Andreas Gamped9911ee2017-03-27 13:27:24 -070087 is_active_(false),
88 is_asserting_to_space_invariant_(false),
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -070089 region_space_bitmap_(nullptr),
Andreas Gamped9911ee2017-03-27 13:27:24 -070090 heap_mark_bitmap_(nullptr),
91 live_stack_freeze_size_(0),
92 from_space_num_objects_at_first_pause_(0),
93 from_space_num_bytes_at_first_pause_(0),
94 mark_stack_mode_(kMarkStackModeOff),
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070095 weak_ref_access_enabled_(true),
Albert Mingkun Yange260e542018-11-05 13:45:59 +000096 copied_live_bytes_ratio_sum_(0.f),
97 gc_count_(0),
Lokesh Gidrad0c5b252018-12-05 01:10:40 -080098 inter_region_bitmap_(nullptr),
Albert Mingkun Yangaf9cce12018-11-07 09:58:35 +000099 reclaimed_bytes_ratio_sum_(0.f),
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700100 young_gen_(young_gen),
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800101 skipped_blocks_lock_("concurrent copying bytes blocks lock", kMarkSweepMarkStackLock),
Mathieu Chartier56fe2582016-07-14 13:30:03 -0700102 measure_read_barrier_slow_path_(measure_read_barrier_slow_path),
Andreas Gamped9911ee2017-03-27 13:27:24 -0700103 mark_from_read_barrier_measurements_(false),
Mathieu Chartier56fe2582016-07-14 13:30:03 -0700104 rb_slow_path_ns_(0),
105 rb_slow_path_count_(0),
106 rb_slow_path_count_gc_(0),
107 rb_slow_path_histogram_lock_("Read barrier histogram lock"),
108 rb_slow_path_time_histogram_("Mutator time in read barrier slow path", 500, 32),
109 rb_slow_path_count_total_(0),
110 rb_slow_path_count_gc_total_(0),
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800111 rb_table_(heap_->GetReadBarrierTable()),
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700112 force_evacuate_all_(false),
Andreas Gamped9911ee2017-03-27 13:27:24 -0700113 gc_grays_immune_objects_(false),
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700114 immune_gray_stack_lock_("concurrent copying immune gray stack lock",
Albert Mingkun Yangaf9cce12018-11-07 09:58:35 +0000115 kMarkSweepMarkStackLock),
116 num_bytes_allocated_before_gc_(0) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800117 static_assert(space::RegionSpace::kRegionSize == accounting::ReadBarrierTable::kRegionSize,
118 "The region space size and the read barrier table region size must match");
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700119 CHECK(kEnableGenerationalConcurrentCopyingCollection || !young_gen_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700120 Thread* self = Thread::Current();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800121 {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800122 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
123 // Cache this so that we won't have to lock heap_bitmap_lock_ in
124 // Mark() which could cause a nested lock on heap_bitmap_lock_
125 // when GC causes a RB while doing GC or a lock order violation
126 // (class_linker_lock_ and heap_bitmap_lock_).
127 heap_mark_bitmap_ = heap->GetMarkBitmap();
128 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700129 {
130 MutexLock mu(self, mark_stack_lock_);
131 for (size_t i = 0; i < kMarkStackPoolSize; ++i) {
132 accounting::AtomicStack<mirror::Object>* mark_stack =
133 accounting::AtomicStack<mirror::Object>::Create(
134 "thread local mark stack", kMarkStackSize, kMarkStackSize);
135 pooled_mark_stacks_.push_back(mark_stack);
136 }
137 }
Roland Levillainb1e1dc32018-07-10 19:19:31 +0100138 if (kEnableGenerationalConcurrentCopyingCollection) {
139 // Allocate sweep array free buffer.
140 std::string error_msg;
141 sweep_array_free_buffer_mem_map_ = MemMap::MapAnonymous(
142 "concurrent copying sweep array free buffer",
Roland Levillainb1e1dc32018-07-10 19:19:31 +0100143 RoundUp(kSweepArrayChunkFreeSize * sizeof(mirror::Object*), kPageSize),
144 PROT_READ | PROT_WRITE,
Vladimir Marko11306592018-10-26 14:22:59 +0100145 /*low_4gb=*/ false,
Roland Levillainb1e1dc32018-07-10 19:19:31 +0100146 &error_msg);
147 CHECK(sweep_array_free_buffer_mem_map_.IsValid())
148 << "Couldn't allocate sweep array free buffer: " << error_msg;
149 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800150}
151
Hiroshi Yamauchi057d9772017-02-17 15:33:23 -0800152void ConcurrentCopying::MarkHeapReference(mirror::HeapReference<mirror::Object>* field,
153 bool do_atomic_update) {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -0800154 Thread* const self = Thread::Current();
Hiroshi Yamauchi057d9772017-02-17 15:33:23 -0800155 if (UNLIKELY(do_atomic_update)) {
156 // Used to mark the referent in DelayReferenceReferent in transaction mode.
157 mirror::Object* from_ref = field->AsMirrorPtr();
158 if (from_ref == nullptr) {
159 return;
160 }
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -0800161 mirror::Object* to_ref = Mark(self, from_ref);
Hiroshi Yamauchi057d9772017-02-17 15:33:23 -0800162 if (from_ref != to_ref) {
163 do {
164 if (field->AsMirrorPtr() != from_ref) {
165 // Concurrently overwritten by a mutator.
166 break;
167 }
168 } while (!field->CasWeakRelaxed(from_ref, to_ref));
169 }
170 } else {
171 // Used for preserving soft references, should be OK to not have a CAS here since there should be
172 // no other threads which can trigger read barriers on the same referent during reference
173 // processing.
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -0800174 field->Assign(Mark(self, field->AsMirrorPtr()));
Hiroshi Yamauchi057d9772017-02-17 15:33:23 -0800175 }
Mathieu Chartier97509952015-07-13 14:35:43 -0700176}
177
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800178ConcurrentCopying::~ConcurrentCopying() {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700179 STLDeleteElements(&pooled_mark_stacks_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800180}
181
182void ConcurrentCopying::RunPhases() {
183 CHECK(kUseBakerReadBarrier || kUseTableLookupReadBarrier);
184 CHECK(!is_active_);
185 is_active_ = true;
186 Thread* self = Thread::Current();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700187 thread_running_gc_ = self;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800188 Locks::mutator_lock_->AssertNotHeld(self);
189 {
190 ReaderMutexLock mu(self, *Locks::mutator_lock_);
191 InitializePhase();
Lokesh Gidra2a9824c2018-11-07 15:57:17 -0800192 // In case of forced evacuation, all regions are evacuated and hence no
193 // need to compute live_bytes.
194 if (kEnableGenerationalConcurrentCopyingCollection && !young_gen_ && !force_evacuate_all_) {
195 MarkingPhase();
196 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800197 }
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700198 if (kUseBakerReadBarrier && kGrayDirtyImmuneObjects) {
199 // Switch to read barrier mark entrypoints before we gray the objects. This is required in case
Roland Levillain97c46462017-05-11 14:04:03 +0100200 // a mutator sees a gray bit and dispatches on the entrypoint. (b/37876887).
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700201 ActivateReadBarrierEntrypoints();
202 // Gray dirty immune objects concurrently to reduce GC pause times. We re-process gray cards in
203 // the pause.
204 ReaderMutexLock mu(self, *Locks::mutator_lock_);
205 GrayAllDirtyImmuneObjects();
206 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800207 FlipThreadRoots();
208 {
209 ReaderMutexLock mu(self, *Locks::mutator_lock_);
Lokesh Gidra2a9824c2018-11-07 15:57:17 -0800210 CopyingPhase();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800211 }
212 // Verify no from space refs. This causes a pause.
Andreas Gampee3ce7872017-02-22 13:36:21 -0800213 if (kEnableNoFromSpaceRefsVerification) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800214 TimingLogger::ScopedTiming split("(Paused)VerifyNoFromSpaceReferences", GetTimings());
Andreas Gampe4934eb12017-01-30 13:15:26 -0800215 ScopedPause pause(this, false);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700216 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800217 if (kVerboseMode) {
218 LOG(INFO) << "Verifying no from-space refs";
219 }
220 VerifyNoFromSpaceReferences();
Mathieu Chartier720e71a2015-04-06 17:10:58 -0700221 if (kVerboseMode) {
222 LOG(INFO) << "Done verifying no from-space refs";
223 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700224 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800225 }
226 {
227 ReaderMutexLock mu(self, *Locks::mutator_lock_);
228 ReclaimPhase();
229 }
230 FinishPhase();
231 CHECK(is_active_);
232 is_active_ = false;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700233 thread_running_gc_ = nullptr;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800234}
235
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700236class ConcurrentCopying::ActivateReadBarrierEntrypointsCheckpoint : public Closure {
237 public:
238 explicit ActivateReadBarrierEntrypointsCheckpoint(ConcurrentCopying* concurrent_copying)
239 : concurrent_copying_(concurrent_copying) {}
240
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100241 void Run(Thread* thread) override NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700242 // Note: self is not necessarily equal to thread since thread may be suspended.
243 Thread* self = Thread::Current();
244 DCHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
245 << thread->GetState() << " thread " << thread << " self " << self;
246 // Switch to the read barrier entrypoints.
247 thread->SetReadBarrierEntrypoints();
248 // If thread is a running mutator, then act on behalf of the garbage collector.
249 // See the code in ThreadList::RunCheckpoint.
250 concurrent_copying_->GetBarrier().Pass(self);
251 }
252
253 private:
254 ConcurrentCopying* const concurrent_copying_;
255};
256
257class ConcurrentCopying::ActivateReadBarrierEntrypointsCallback : public Closure {
258 public:
259 explicit ActivateReadBarrierEntrypointsCallback(ConcurrentCopying* concurrent_copying)
260 : concurrent_copying_(concurrent_copying) {}
261
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100262 void Run(Thread* self ATTRIBUTE_UNUSED) override REQUIRES(Locks::thread_list_lock_) {
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700263 // This needs to run under the thread_list_lock_ critical section in ThreadList::RunCheckpoint()
264 // to avoid a race with ThreadList::Register().
265 CHECK(!concurrent_copying_->is_using_read_barrier_entrypoints_);
266 concurrent_copying_->is_using_read_barrier_entrypoints_ = true;
267 }
268
269 private:
270 ConcurrentCopying* const concurrent_copying_;
271};
272
273void ConcurrentCopying::ActivateReadBarrierEntrypoints() {
274 Thread* const self = Thread::Current();
275 ActivateReadBarrierEntrypointsCheckpoint checkpoint(this);
276 ThreadList* thread_list = Runtime::Current()->GetThreadList();
277 gc_barrier_->Init(self, 0);
278 ActivateReadBarrierEntrypointsCallback callback(this);
279 const size_t barrier_count = thread_list->RunCheckpoint(&checkpoint, &callback);
280 // If there are no threads to wait which implies that all the checkpoint functions are finished,
281 // then no need to release the mutator lock.
282 if (barrier_count == 0) {
283 return;
284 }
285 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
286 gc_barrier_->Increment(self, barrier_count);
287}
288
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800289void ConcurrentCopying::BindBitmaps() {
290 Thread* self = Thread::Current();
291 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Lokesh Gidrad0c5b252018-12-05 01:10:40 -0800292 uintptr_t continuous_spaces_begin = UINTPTR_MAX;
293 uintptr_t continuous_spaces_limit = 0;
294 DCHECK(inter_region_bitmap_ == nullptr);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800295 // Mark all of the spaces we never collect as immune.
296 for (const auto& space : heap_->GetContinuousSpaces()) {
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800297 if (space->GetGcRetentionPolicy() == space::kGcRetentionPolicyNeverCollect ||
298 space->GetGcRetentionPolicy() == space::kGcRetentionPolicyFullCollect) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800299 CHECK(space->IsZygoteSpace() || space->IsImageSpace());
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800300 immune_spaces_.AddSpace(space);
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700301 } else {
302 CHECK(!space->IsZygoteSpace());
303 CHECK(!space->IsImageSpace());
304 if (kEnableGenerationalConcurrentCopyingCollection) {
305 if (space == region_space_) {
306 region_space_bitmap_ = region_space_->GetMarkBitmap();
307 } else if (young_gen_ && space->IsContinuousMemMapAllocSpace()) {
308 DCHECK_EQ(space->GetGcRetentionPolicy(), space::kGcRetentionPolicyAlwaysCollect);
309 space->AsContinuousMemMapAllocSpace()->BindLiveToMarkBitmap();
310 }
Lokesh Gidra2a9824c2018-11-07 15:57:17 -0800311 if (young_gen_) {
312 // Age all of the cards for the region space so that we know which evac regions to scan.
313 heap_->GetCardTable()->ModifyCardsAtomic(space->Begin(),
314 space->End(),
315 AgeCardVisitor(),
316 VoidFunctor());
317 } else {
318 // In a full-heap GC cycle, the card-table corresponding to region-space and
319 // non-moving space can be cleared, because this cycle only needs to
320 // capture writes during the marking phase of this cycle to catch
321 // objects that skipped marking due to heap mutation. Furthermore,
322 // if the next GC is a young-gen cycle, then it only needs writes to
323 // be captured after the thread-flip of this GC cycle, as that is when
324 // the young-gen for the next GC cycle starts getting populated.
325 heap_->GetCardTable()->ClearCardRange(space->Begin(), space->Limit());
Lokesh Gidrad0c5b252018-12-05 01:10:40 -0800326
327 continuous_spaces_begin =
328 std::min(continuous_spaces_begin, reinterpret_cast<uintptr_t>(space->Begin()));
329 continuous_spaces_limit =
330 std::max(continuous_spaces_limit, reinterpret_cast<uintptr_t>(space->Limit()));
Lokesh Gidra2a9824c2018-11-07 15:57:17 -0800331 }
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700332 } else {
333 if (space == region_space_) {
334 // It is OK to clear the bitmap with mutators running since the only place it is read is
335 // VisitObjects which has exclusion with CC.
336 region_space_bitmap_ = region_space_->GetMarkBitmap();
337 region_space_bitmap_->Clear();
338 }
339 }
340 }
341 }
Lokesh Gidrad0c5b252018-12-05 01:10:40 -0800342 if (kEnableGenerationalConcurrentCopyingCollection) {
343 if (young_gen_) {
344 for (const auto& space : GetHeap()->GetDiscontinuousSpaces()) {
345 CHECK(space->IsLargeObjectSpace());
346 space->AsLargeObjectSpace()->CopyLiveToMarked();
347 }
348 } else {
349 inter_region_bitmap_.reset(accounting::ContinuousSpaceBitmap::Create(
350 "inter region ref bitmap",
351 reinterpret_cast<uint8_t*>(continuous_spaces_begin),
352 continuous_spaces_limit - continuous_spaces_begin));
353 CHECK(inter_region_bitmap_ != nullptr) << "Couldn't allocate inter region ref bitmap";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800354 }
355 }
356}
357
358void ConcurrentCopying::InitializePhase() {
359 TimingLogger::ScopedTiming split("InitializePhase", GetTimings());
Albert Mingkun Yangaf9cce12018-11-07 09:58:35 +0000360 num_bytes_allocated_before_gc_ = static_cast<int64_t>(heap_->GetBytesAllocated());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800361 if (kVerboseMode) {
362 LOG(INFO) << "GC InitializePhase";
363 LOG(INFO) << "Region-space : " << reinterpret_cast<void*>(region_space_->Begin()) << "-"
364 << reinterpret_cast<void*>(region_space_->Limit());
365 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700366 CheckEmptyMarkStack();
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700367 rb_mark_bit_stack_full_ = false;
Mathieu Chartier56fe2582016-07-14 13:30:03 -0700368 mark_from_read_barrier_measurements_ = measure_read_barrier_slow_path_;
369 if (measure_read_barrier_slow_path_) {
Orion Hodson88591fe2018-03-06 13:35:43 +0000370 rb_slow_path_ns_.store(0, std::memory_order_relaxed);
371 rb_slow_path_count_.store(0, std::memory_order_relaxed);
372 rb_slow_path_count_gc_.store(0, std::memory_order_relaxed);
Mathieu Chartier56fe2582016-07-14 13:30:03 -0700373 }
374
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800375 immune_spaces_.Reset();
Orion Hodson88591fe2018-03-06 13:35:43 +0000376 bytes_moved_.store(0, std::memory_order_relaxed);
377 objects_moved_.store(0, std::memory_order_relaxed);
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -0800378 bytes_moved_gc_thread_ = 0;
379 objects_moved_gc_thread_ = 0;
Hiroshi Yamauchi60985b72016-08-24 13:53:12 -0700380 GcCause gc_cause = GetCurrentIteration()->GetGcCause();
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700381
382 force_evacuate_all_ = false;
383 if (!kEnableGenerationalConcurrentCopyingCollection || !young_gen_) {
384 if (gc_cause == kGcCauseExplicit ||
385 gc_cause == kGcCauseCollectorTransition ||
386 GetCurrentIteration()->GetClearSoftReferences()) {
387 force_evacuate_all_ = true;
388 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800389 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700390 if (kUseBakerReadBarrier) {
Orion Hodson88591fe2018-03-06 13:35:43 +0000391 updated_all_immune_objects_.store(false, std::memory_order_relaxed);
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700392 // GC may gray immune objects in the thread flip.
393 gc_grays_immune_objects_ = true;
394 if (kIsDebugBuild) {
395 MutexLock mu(Thread::Current(), immune_gray_stack_lock_);
396 DCHECK(immune_gray_stack_.empty());
397 }
398 }
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700399 if (kEnableGenerationalConcurrentCopyingCollection) {
Roland Levillain2d94e292018-08-15 16:46:30 +0100400 done_scanning_.store(false, std::memory_order_release);
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700401 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800402 BindBitmaps();
403 if (kVerboseMode) {
Roland Levillain57ce0542018-08-07 16:20:31 +0100404 LOG(INFO) << "young_gen=" << std::boolalpha << young_gen_ << std::noboolalpha;
405 LOG(INFO) << "force_evacuate_all=" << std::boolalpha << force_evacuate_all_ << std::noboolalpha;
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800406 LOG(INFO) << "Largest immune region: " << immune_spaces_.GetLargestImmuneRegion().Begin()
407 << "-" << immune_spaces_.GetLargestImmuneRegion().End();
408 for (space::ContinuousSpace* space : immune_spaces_.GetSpaces()) {
409 LOG(INFO) << "Immune space: " << *space;
410 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800411 LOG(INFO) << "GC end of InitializePhase";
412 }
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700413 if (kEnableGenerationalConcurrentCopyingCollection && !young_gen_) {
414 region_space_bitmap_->Clear();
415 }
Lokesh Gidra2a9824c2018-11-07 15:57:17 -0800416 mark_stack_mode_.store(ConcurrentCopying::kMarkStackModeThreadLocal, std::memory_order_relaxed);
Mathieu Chartier962cd7a2016-08-16 12:15:59 -0700417 // Mark all of the zygote large objects without graying them.
418 MarkZygoteLargeObjects();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800419}
420
421// Used to switch the thread roots of a thread from from-space refs to to-space refs.
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700422class ConcurrentCopying::ThreadFlipVisitor : public Closure, public RootVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800423 public:
Roland Levillain3887c462015-08-12 18:15:42 +0100424 ThreadFlipVisitor(ConcurrentCopying* concurrent_copying, bool use_tlab)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800425 : concurrent_copying_(concurrent_copying), use_tlab_(use_tlab) {
426 }
427
Roland Levillainf73caca2018-08-24 17:19:07 +0100428 void Run(Thread* thread) override REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800429 // Note: self is not necessarily equal to thread since thread may be suspended.
430 Thread* self = Thread::Current();
431 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
432 << thread->GetState() << " thread " << thread << " self " << self;
Mathieu Chartierfe814e82016-11-09 14:32:49 -0800433 thread->SetIsGcMarkingAndUpdateEntrypoints(true);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800434 if (use_tlab_ && thread->HasTlab()) {
435 if (ConcurrentCopying::kEnableFromSpaceAccountingCheck) {
436 // This must come before the revoke.
437 size_t thread_local_objects = thread->GetThreadLocalObjectsAllocated();
438 concurrent_copying_->region_space_->RevokeThreadLocalBuffers(thread);
Roland Levillain2ae376f2018-01-30 11:35:11 +0000439 reinterpret_cast<Atomic<size_t>*>(
440 &concurrent_copying_->from_space_num_objects_at_first_pause_)->
Hans Boehmfb8b4e22018-09-05 16:45:42 -0700441 fetch_add(thread_local_objects, std::memory_order_relaxed);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800442 } else {
443 concurrent_copying_->region_space_->RevokeThreadLocalBuffers(thread);
444 }
445 }
446 if (kUseThreadLocalAllocationStack) {
447 thread->RevokeThreadLocalAllocationStack();
448 }
449 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700450 // We can use the non-CAS VisitRoots functions below because we update thread-local GC roots
451 // only.
Andreas Gampe513061a2017-06-01 09:17:34 -0700452 thread->VisitRoots(this, kVisitRootFlagAllRoots);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800453 concurrent_copying_->GetBarrier().Pass(self);
454 }
455
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700456 void VisitRoots(mirror::Object*** roots,
457 size_t count,
Andreas Gampefa6a1b02018-09-07 08:11:55 -0700458 const RootInfo& info ATTRIBUTE_UNUSED) override
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700459 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -0800460 Thread* self = Thread::Current();
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700461 for (size_t i = 0; i < count; ++i) {
462 mirror::Object** root = roots[i];
463 mirror::Object* ref = *root;
464 if (ref != nullptr) {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -0800465 mirror::Object* to_ref = concurrent_copying_->Mark(self, ref);
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700466 if (to_ref != ref) {
467 *root = to_ref;
468 }
469 }
470 }
471 }
472
473 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots,
474 size_t count,
Andreas Gampefa6a1b02018-09-07 08:11:55 -0700475 const RootInfo& info ATTRIBUTE_UNUSED) override
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700476 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -0800477 Thread* self = Thread::Current();
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700478 for (size_t i = 0; i < count; ++i) {
479 mirror::CompressedReference<mirror::Object>* const root = roots[i];
480 if (!root->IsNull()) {
481 mirror::Object* ref = root->AsMirrorPtr();
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -0800482 mirror::Object* to_ref = concurrent_copying_->Mark(self, ref);
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700483 if (to_ref != ref) {
484 root->Assign(to_ref);
485 }
486 }
487 }
488 }
489
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800490 private:
491 ConcurrentCopying* const concurrent_copying_;
492 const bool use_tlab_;
493};
494
495// Called back from Runtime::FlipThreadRoots() during a pause.
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700496class ConcurrentCopying::FlipCallback : public Closure {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800497 public:
498 explicit FlipCallback(ConcurrentCopying* concurrent_copying)
499 : concurrent_copying_(concurrent_copying) {
500 }
501
Roland Levillainf73caca2018-08-24 17:19:07 +0100502 void Run(Thread* thread) override REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800503 ConcurrentCopying* cc = concurrent_copying_;
504 TimingLogger::ScopedTiming split("(Paused)FlipCallback", cc->GetTimings());
505 // Note: self is not necessarily equal to thread since thread may be suspended.
506 Thread* self = Thread::Current();
Lokesh Gidra2a9824c2018-11-07 15:57:17 -0800507 if (kVerifyNoMissingCardMarks && cc->young_gen_) {
Mathieu Chartiera1467d02017-02-22 09:22:50 -0800508 cc->VerifyNoMissingCardMarks();
509 }
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700510 CHECK_EQ(thread, self);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800511 Locks::mutator_lock_->AssertExclusiveHeld(self);
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700512 space::RegionSpace::EvacMode evac_mode = space::RegionSpace::kEvacModeLivePercentNewlyAllocated;
513 if (cc->young_gen_) {
514 CHECK(!cc->force_evacuate_all_);
515 evac_mode = space::RegionSpace::kEvacModeNewlyAllocated;
516 } else if (cc->force_evacuate_all_) {
517 evac_mode = space::RegionSpace::kEvacModeForceAll;
518 }
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700519 {
520 TimingLogger::ScopedTiming split2("(Paused)SetFromSpace", cc->GetTimings());
Lokesh Gidra2a9824c2018-11-07 15:57:17 -0800521 // Only change live bytes for 1-phase full heap CC.
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700522 cc->region_space_->SetFromSpace(
Lokesh Gidra2a9824c2018-11-07 15:57:17 -0800523 cc->rb_table_,
524 evac_mode,
525 /*clear_live_bytes=*/ !kEnableGenerationalConcurrentCopyingCollection);
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700526 }
Mathieu Chartiera4f6af92015-08-11 17:35:25 -0700527 cc->SwapStacks();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800528 if (ConcurrentCopying::kEnableFromSpaceAccountingCheck) {
529 cc->RecordLiveStackFreezeSize(self);
530 cc->from_space_num_objects_at_first_pause_ = cc->region_space_->GetObjectsAllocated();
531 cc->from_space_num_bytes_at_first_pause_ = cc->region_space_->GetBytesAllocated();
532 }
533 cc->is_marking_ = true;
Lokesh Gidra2a9824c2018-11-07 15:57:17 -0800534 if (kIsDebugBuild && !kEnableGenerationalConcurrentCopyingCollection) {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800535 cc->region_space_->AssertAllRegionLiveBytesZeroOrCleared();
536 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800537 if (UNLIKELY(Runtime::Current()->IsActiveTransaction())) {
Mathieu Chartier184c9dc2015-03-05 13:20:54 -0800538 CHECK(Runtime::Current()->IsAotCompiler());
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700539 TimingLogger::ScopedTiming split3("(Paused)VisitTransactionRoots", cc->GetTimings());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700540 Runtime::Current()->VisitTransactionRoots(cc);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800541 }
Mathieu Chartier21328a12016-07-22 10:47:45 -0700542 if (kUseBakerReadBarrier && kGrayDirtyImmuneObjects) {
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700543 cc->GrayAllNewlyDirtyImmuneObjects();
Mathieu Chartier21328a12016-07-22 10:47:45 -0700544 if (kIsDebugBuild) {
Roland Levillain001eff92018-01-24 14:24:33 +0000545 // Check that all non-gray immune objects only reference immune objects.
Mathieu Chartier21328a12016-07-22 10:47:45 -0700546 cc->VerifyGrayImmuneObjects();
547 }
548 }
Mathieu Chartier9aef9922017-04-23 13:53:50 -0700549 // May be null during runtime creation, in this case leave java_lang_Object null.
550 // This is safe since single threaded behavior should mean FillDummyObject does not
551 // happen when java_lang_Object_ is null.
552 if (WellKnownClasses::java_lang_Object != nullptr) {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -0800553 cc->java_lang_Object_ = down_cast<mirror::Class*>(cc->Mark(thread,
Mathieu Chartier9aef9922017-04-23 13:53:50 -0700554 WellKnownClasses::ToClass(WellKnownClasses::java_lang_Object).Ptr()));
555 } else {
556 cc->java_lang_Object_ = nullptr;
557 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800558 }
559
560 private:
561 ConcurrentCopying* const concurrent_copying_;
562};
563
Mathieu Chartier21328a12016-07-22 10:47:45 -0700564class ConcurrentCopying::VerifyGrayImmuneObjectsVisitor {
565 public:
566 explicit VerifyGrayImmuneObjectsVisitor(ConcurrentCopying* collector)
567 : collector_(collector) {}
568
Mathieu Chartier31e88222016-10-14 18:43:19 -0700569 void operator()(ObjPtr<mirror::Object> obj, MemberOffset offset, bool /* is_static */)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700570 const ALWAYS_INLINE REQUIRES_SHARED(Locks::mutator_lock_)
571 REQUIRES_SHARED(Locks::heap_bitmap_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700572 CheckReference(obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(offset),
573 obj, offset);
574 }
575
Mathieu Chartier31e88222016-10-14 18:43:19 -0700576 void operator()(ObjPtr<mirror::Class> klass, ObjPtr<mirror::Reference> ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700577 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700578 CHECK(klass->IsTypeOfReferenceClass());
579 CheckReference(ref->GetReferent<kWithoutReadBarrier>(),
580 ref,
581 mirror::Reference::ReferentOffset());
582 }
583
584 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
585 ALWAYS_INLINE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700586 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700587 if (!root->IsNull()) {
588 VisitRoot(root);
589 }
590 }
591
592 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
593 ALWAYS_INLINE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700594 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700595 CheckReference(root->AsMirrorPtr(), nullptr, MemberOffset(0));
596 }
597
598 private:
599 ConcurrentCopying* const collector_;
600
Mathieu Chartier31e88222016-10-14 18:43:19 -0700601 void CheckReference(ObjPtr<mirror::Object> ref,
602 ObjPtr<mirror::Object> holder,
603 MemberOffset offset) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700604 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700605 if (ref != nullptr) {
Mathieu Chartier31e88222016-10-14 18:43:19 -0700606 if (!collector_->immune_spaces_.ContainsObject(ref.Ptr())) {
Mathieu Chartier962cd7a2016-08-16 12:15:59 -0700607 // Not immune, must be a zygote large object.
Lokesh Gidra02c230c2018-10-10 23:48:43 -0700608 space::LargeObjectSpace* large_object_space =
609 Runtime::Current()->GetHeap()->GetLargeObjectsSpace();
610 CHECK(large_object_space->Contains(ref.Ptr()) &&
611 large_object_space->IsZygoteLargeObject(Thread::Current(), ref.Ptr()))
Mathieu Chartier962cd7a2016-08-16 12:15:59 -0700612 << "Non gray object references non immune, non zygote large object "<< ref << " "
David Sehr709b0702016-10-13 09:12:37 -0700613 << mirror::Object::PrettyTypeOf(ref) << " in holder " << holder << " "
614 << mirror::Object::PrettyTypeOf(holder) << " offset=" << offset.Uint32Value();
Mathieu Chartier962cd7a2016-08-16 12:15:59 -0700615 } else {
616 // Make sure the large object class is immune since we will never scan the large object.
617 CHECK(collector_->immune_spaces_.ContainsObject(
618 ref->GetClass<kVerifyNone, kWithoutReadBarrier>()));
619 }
Mathieu Chartier21328a12016-07-22 10:47:45 -0700620 }
621 }
622};
623
624void ConcurrentCopying::VerifyGrayImmuneObjects() {
625 TimingLogger::ScopedTiming split(__FUNCTION__, GetTimings());
626 for (auto& space : immune_spaces_.GetSpaces()) {
627 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
628 accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
629 VerifyGrayImmuneObjectsVisitor visitor(this);
630 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()),
631 reinterpret_cast<uintptr_t>(space->Limit()),
632 [&visitor](mirror::Object* obj)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700633 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700634 // If an object is not gray, it should only have references to things in the immune spaces.
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700635 if (obj->GetReadBarrierState() != ReadBarrier::GrayState()) {
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700636 obj->VisitReferences</*kVisitNativeRoots=*/true,
Mathieu Chartier21328a12016-07-22 10:47:45 -0700637 kDefaultVerifyFlags,
638 kWithoutReadBarrier>(visitor, visitor);
639 }
640 });
641 }
642}
643
Mathieu Chartiera1467d02017-02-22 09:22:50 -0800644class ConcurrentCopying::VerifyNoMissingCardMarkVisitor {
645 public:
646 VerifyNoMissingCardMarkVisitor(ConcurrentCopying* cc, ObjPtr<mirror::Object> holder)
647 : cc_(cc),
648 holder_(holder) {}
649
650 void operator()(ObjPtr<mirror::Object> obj,
651 MemberOffset offset,
652 bool is_static ATTRIBUTE_UNUSED) const
653 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
654 if (offset.Uint32Value() != mirror::Object::ClassOffset().Uint32Value()) {
655 CheckReference(obj->GetFieldObject<mirror::Object, kDefaultVerifyFlags, kWithoutReadBarrier>(
656 offset), offset.Uint32Value());
657 }
658 }
659 void operator()(ObjPtr<mirror::Class> klass,
660 ObjPtr<mirror::Reference> ref) const
661 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
662 CHECK(klass->IsTypeOfReferenceClass());
663 this->operator()(ref, mirror::Reference::ReferentOffset(), false);
664 }
665
666 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
667 REQUIRES_SHARED(Locks::mutator_lock_) {
668 if (!root->IsNull()) {
669 VisitRoot(root);
670 }
671 }
672
673 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
674 REQUIRES_SHARED(Locks::mutator_lock_) {
675 CheckReference(root->AsMirrorPtr());
676 }
677
678 void CheckReference(mirror::Object* ref, int32_t offset = -1) const
679 REQUIRES_SHARED(Locks::mutator_lock_) {
Roland Levillainb9c68342018-09-04 18:56:31 +0100680 if (ref != nullptr && cc_->region_space_->IsInNewlyAllocatedRegion(ref)) {
681 LOG(FATAL_WITHOUT_ABORT)
Mathieu Chartiera1467d02017-02-22 09:22:50 -0800682 << holder_->PrettyTypeOf() << "(" << holder_.Ptr() << ") references object "
683 << ref->PrettyTypeOf() << "(" << ref << ") in newly allocated region at offset=" << offset;
Roland Levillainb9c68342018-09-04 18:56:31 +0100684 LOG(FATAL_WITHOUT_ABORT) << "time=" << cc_->region_space_->Time();
685 constexpr const char* kIndent = " ";
686 LOG(FATAL_WITHOUT_ABORT) << cc_->DumpReferenceInfo(holder_.Ptr(), "holder_", kIndent);
687 LOG(FATAL_WITHOUT_ABORT) << cc_->DumpReferenceInfo(ref, "ref", kIndent);
688 LOG(FATAL) << "Unexpected reference to newly allocated region.";
689 }
Mathieu Chartiera1467d02017-02-22 09:22:50 -0800690 }
691
692 private:
693 ConcurrentCopying* const cc_;
694 ObjPtr<mirror::Object> const holder_;
695};
696
Mathieu Chartiera1467d02017-02-22 09:22:50 -0800697void ConcurrentCopying::VerifyNoMissingCardMarks() {
Andreas Gampe0c183382017-07-13 22:26:24 -0700698 auto visitor = [&](mirror::Object* obj)
699 REQUIRES(Locks::mutator_lock_)
700 REQUIRES(!mark_stack_lock_) {
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700701 // Objects on clean cards should never have references to newly allocated regions. Note
702 // that aged cards are also not clean.
Andreas Gampe0c183382017-07-13 22:26:24 -0700703 if (heap_->GetCardTable()->GetCard(obj) == gc::accounting::CardTable::kCardClean) {
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700704 VerifyNoMissingCardMarkVisitor internal_visitor(this, /*holder=*/ obj);
705 obj->VisitReferences</*kVisitNativeRoots=*/true, kVerifyNone, kWithoutReadBarrier>(
Andreas Gampe0c183382017-07-13 22:26:24 -0700706 internal_visitor, internal_visitor);
707 }
708 };
Mathieu Chartiera1467d02017-02-22 09:22:50 -0800709 TimingLogger::ScopedTiming split(__FUNCTION__, GetTimings());
Andreas Gampe0c183382017-07-13 22:26:24 -0700710 region_space_->Walk(visitor);
Mathieu Chartiera1467d02017-02-22 09:22:50 -0800711 {
712 ReaderMutexLock rmu(Thread::Current(), *Locks::heap_bitmap_lock_);
Andreas Gampe0c183382017-07-13 22:26:24 -0700713 heap_->GetLiveBitmap()->Visit(visitor);
Mathieu Chartiera1467d02017-02-22 09:22:50 -0800714 }
715}
716
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800717// Switch threads that from from-space to to-space refs. Forward/mark the thread roots.
718void ConcurrentCopying::FlipThreadRoots() {
719 TimingLogger::ScopedTiming split("FlipThreadRoots", GetTimings());
720 if (kVerboseMode) {
721 LOG(INFO) << "time=" << region_space_->Time();
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700722 region_space_->DumpNonFreeRegions(LOG_STREAM(INFO));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800723 }
724 Thread* self = Thread::Current();
725 Locks::mutator_lock_->AssertNotHeld(self);
726 gc_barrier_->Init(self, 0);
727 ThreadFlipVisitor thread_flip_visitor(this, heap_->use_tlab_);
728 FlipCallback flip_callback(this);
Andreas Gampe4934eb12017-01-30 13:15:26 -0800729
Andreas Gampe6e644452017-05-09 16:30:27 -0700730 size_t barrier_count = Runtime::Current()->GetThreadList()->FlipThreadRoots(
731 &thread_flip_visitor, &flip_callback, this, GetHeap()->GetGcPauseListener());
Andreas Gampe4934eb12017-01-30 13:15:26 -0800732
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800733 {
734 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
735 gc_barrier_->Increment(self, barrier_count);
736 }
737 is_asserting_to_space_invariant_ = true;
738 QuasiAtomic::ThreadFenceForConstructor();
739 if (kVerboseMode) {
740 LOG(INFO) << "time=" << region_space_->Time();
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700741 region_space_->DumpNonFreeRegions(LOG_STREAM(INFO));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800742 LOG(INFO) << "GC end of FlipThreadRoots";
743 }
744}
745
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700746template <bool kConcurrent>
Mathieu Chartier21328a12016-07-22 10:47:45 -0700747class ConcurrentCopying::GrayImmuneObjectVisitor {
748 public:
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700749 explicit GrayImmuneObjectVisitor(Thread* self) : self_(self) {}
Mathieu Chartier21328a12016-07-22 10:47:45 -0700750
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700751 ALWAYS_INLINE void operator()(mirror::Object* obj) const REQUIRES_SHARED(Locks::mutator_lock_) {
Roland Levillain14e5a292018-06-28 12:00:56 +0100752 if (kUseBakerReadBarrier && obj->GetReadBarrierState() == ReadBarrier::NonGrayState()) {
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700753 if (kConcurrent) {
754 Locks::mutator_lock_->AssertSharedHeld(self_);
Roland Levillain14e5a292018-06-28 12:00:56 +0100755 obj->AtomicSetReadBarrierState(ReadBarrier::NonGrayState(), ReadBarrier::GrayState());
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700756 // Mod union table VisitObjects may visit the same object multiple times so we can't check
757 // the result of the atomic set.
758 } else {
759 Locks::mutator_lock_->AssertExclusiveHeld(self_);
760 obj->SetReadBarrierState(ReadBarrier::GrayState());
Mathieu Chartier21328a12016-07-22 10:47:45 -0700761 }
Mathieu Chartier21328a12016-07-22 10:47:45 -0700762 }
763 }
764
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700765 static void Callback(mirror::Object* obj, void* arg) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700766 reinterpret_cast<GrayImmuneObjectVisitor<kConcurrent>*>(arg)->operator()(obj);
Mathieu Chartier21328a12016-07-22 10:47:45 -0700767 }
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700768
769 private:
770 Thread* const self_;
Mathieu Chartier21328a12016-07-22 10:47:45 -0700771};
772
773void ConcurrentCopying::GrayAllDirtyImmuneObjects() {
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700774 TimingLogger::ScopedTiming split("GrayAllDirtyImmuneObjects", GetTimings());
775 accounting::CardTable* const card_table = heap_->GetCardTable();
776 Thread* const self = Thread::Current();
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700777 using VisitorType = GrayImmuneObjectVisitor</* kIsConcurrent= */ true>;
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700778 VisitorType visitor(self);
779 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier21328a12016-07-22 10:47:45 -0700780 for (space::ContinuousSpace* space : immune_spaces_.GetSpaces()) {
781 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700782 accounting::ModUnionTable* table = heap_->FindModUnionTableFromSpace(space);
Mathieu Chartier21328a12016-07-22 10:47:45 -0700783 // Mark all the objects on dirty cards since these may point to objects in other space.
784 // Once these are marked, the GC will eventually clear them later.
785 // Table is non null for boot image and zygote spaces. It is only null for application image
786 // spaces.
787 if (table != nullptr) {
Mathieu Chartier6e6078a2016-10-24 15:45:41 -0700788 table->ProcessCards();
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700789 table->VisitObjects(&VisitorType::Callback, &visitor);
790 // Don't clear cards here since we need to rescan in the pause. If we cleared the cards here,
791 // there would be races with the mutator marking new cards.
792 } else {
793 // Keep cards aged if we don't have a mod-union table since we may need to scan them in future
794 // GCs. This case is for app images.
795 card_table->ModifyCardsAtomic(
796 space->Begin(),
797 space->End(),
798 [](uint8_t card) {
799 return (card != gc::accounting::CardTable::kCardClean)
800 ? gc::accounting::CardTable::kCardAged
801 : card;
802 },
803 /* card modified visitor */ VoidFunctor());
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700804 card_table->Scan</*kClearCard=*/ false>(space->GetMarkBitmap(),
805 space->Begin(),
806 space->End(),
807 visitor,
808 gc::accounting::CardTable::kCardAged);
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700809 }
810 }
811}
812
813void ConcurrentCopying::GrayAllNewlyDirtyImmuneObjects() {
814 TimingLogger::ScopedTiming split("(Paused)GrayAllNewlyDirtyImmuneObjects", GetTimings());
815 accounting::CardTable* const card_table = heap_->GetCardTable();
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700816 using VisitorType = GrayImmuneObjectVisitor</* kIsConcurrent= */ false>;
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700817 Thread* const self = Thread::Current();
818 VisitorType visitor(self);
819 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
820 for (space::ContinuousSpace* space : immune_spaces_.GetSpaces()) {
821 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
822 accounting::ModUnionTable* table = heap_->FindModUnionTableFromSpace(space);
823
824 // Don't need to scan aged cards since we did these before the pause. Note that scanning cards
825 // also handles the mod-union table cards.
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700826 card_table->Scan</*kClearCard=*/ false>(space->GetMarkBitmap(),
827 space->Begin(),
828 space->End(),
829 visitor,
830 gc::accounting::CardTable::kCardDirty);
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700831 if (table != nullptr) {
832 // Add the cards to the mod-union table so that we can clear cards to save RAM.
833 table->ProcessCards();
Mathieu Chartier6e6078a2016-10-24 15:45:41 -0700834 TimingLogger::ScopedTiming split2("(Paused)ClearCards", GetTimings());
835 card_table->ClearCardRange(space->Begin(),
836 AlignDown(space->End(), accounting::CardTable::kCardSize));
Mathieu Chartier21328a12016-07-22 10:47:45 -0700837 }
838 }
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700839 // 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 -0700840 // barriers in the immune spaces.
Orion Hodson88591fe2018-03-06 13:35:43 +0000841 updated_all_immune_objects_.store(true, std::memory_order_relaxed);
Mathieu Chartier21328a12016-07-22 10:47:45 -0700842}
843
Mathieu Chartiera4f6af92015-08-11 17:35:25 -0700844void ConcurrentCopying::SwapStacks() {
845 heap_->SwapStacks();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800846}
847
848void ConcurrentCopying::RecordLiveStackFreezeSize(Thread* self) {
849 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
850 live_stack_freeze_size_ = heap_->GetLiveStack()->Size();
851}
852
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700853// Used to visit objects in the immune spaces.
854inline void ConcurrentCopying::ScanImmuneObject(mirror::Object* obj) {
855 DCHECK(obj != nullptr);
856 DCHECK(immune_spaces_.ContainsObject(obj));
857 // Update the fields without graying it or pushing it onto the mark stack.
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700858 if (kEnableGenerationalConcurrentCopyingCollection && young_gen_) {
859 // Young GC does not care about references to unevac space. It is safe to not gray these as
860 // long as scan immune objects happens after scanning the dirty cards.
861 Scan<true>(obj);
862 } else {
863 Scan<false>(obj);
864 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700865}
866
867class ConcurrentCopying::ImmuneSpaceScanObjVisitor {
868 public:
869 explicit ImmuneSpaceScanObjVisitor(ConcurrentCopying* cc)
870 : collector_(cc) {}
871
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700872 ALWAYS_INLINE void operator()(mirror::Object* obj) const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700873 if (kUseBakerReadBarrier && kGrayDirtyImmuneObjects) {
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700874 // Only need to scan gray objects.
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700875 if (obj->GetReadBarrierState() == ReadBarrier::GrayState()) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700876 collector_->ScanImmuneObject(obj);
Roland Levillain14e5a292018-06-28 12:00:56 +0100877 // Done scanning the object, go back to black (non-gray).
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700878 bool success = obj->AtomicSetReadBarrierState(ReadBarrier::GrayState(),
Roland Levillain14e5a292018-06-28 12:00:56 +0100879 ReadBarrier::NonGrayState());
Mathieu Chartier2af7a3e2017-12-14 18:36:05 -0800880 CHECK(success)
881 << Runtime::Current()->GetHeap()->GetVerification()->DumpObjectInfo(obj, "failed CAS");
Mathieu Chartier21328a12016-07-22 10:47:45 -0700882 }
883 } else {
884 collector_->ScanImmuneObject(obj);
885 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700886 }
887
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700888 static void Callback(mirror::Object* obj, void* arg) REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi5408f232016-07-29 15:07:05 -0700889 reinterpret_cast<ImmuneSpaceScanObjVisitor*>(arg)->operator()(obj);
890 }
891
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700892 private:
893 ConcurrentCopying* const collector_;
894};
895
Lokesh Gidra2a9824c2018-11-07 15:57:17 -0800896template <bool kAtomicTestAndSet>
897class ConcurrentCopying::CaptureRootsForMarkingVisitor : public RootVisitor {
898 public:
899 explicit CaptureRootsForMarkingVisitor(ConcurrentCopying* cc, Thread* self)
900 : collector_(cc), self_(self) {}
901
902 void VisitRoots(mirror::Object*** roots,
903 size_t count,
904 const RootInfo& info ATTRIBUTE_UNUSED) override
905 REQUIRES_SHARED(Locks::mutator_lock_) {
906 for (size_t i = 0; i < count; ++i) {
907 mirror::Object** root = roots[i];
908 mirror::Object* ref = *root;
909 if (ref != nullptr && !collector_->TestAndSetMarkBitForRef<kAtomicTestAndSet>(ref)) {
910 collector_->PushOntoMarkStack(self_, ref);
911 }
912 }
913 }
914
915 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots,
916 size_t count,
917 const RootInfo& info ATTRIBUTE_UNUSED) override
918 REQUIRES_SHARED(Locks::mutator_lock_) {
919 for (size_t i = 0; i < count; ++i) {
920 mirror::CompressedReference<mirror::Object>* const root = roots[i];
921 if (!root->IsNull()) {
922 mirror::Object* ref = root->AsMirrorPtr();
923 if (!collector_->TestAndSetMarkBitForRef<kAtomicTestAndSet>(ref)) {
924 collector_->PushOntoMarkStack(self_, ref);
925 }
926 }
927 }
928 }
929
930 private:
931 ConcurrentCopying* const collector_;
932 Thread* const self_;
933};
934
935class ConcurrentCopying::RevokeThreadLocalMarkStackCheckpoint : public Closure {
936 public:
937 RevokeThreadLocalMarkStackCheckpoint(ConcurrentCopying* concurrent_copying,
938 bool disable_weak_ref_access)
939 : concurrent_copying_(concurrent_copying),
940 disable_weak_ref_access_(disable_weak_ref_access) {
941 }
942
943 void Run(Thread* thread) override NO_THREAD_SAFETY_ANALYSIS {
944 // Note: self is not necessarily equal to thread since thread may be suspended.
945 Thread* const self = Thread::Current();
946 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
947 << thread->GetState() << " thread " << thread << " self " << self;
948 // Revoke thread local mark stacks.
949 accounting::AtomicStack<mirror::Object>* tl_mark_stack = thread->GetThreadLocalMarkStack();
950 if (tl_mark_stack != nullptr) {
951 MutexLock mu(self, concurrent_copying_->mark_stack_lock_);
952 concurrent_copying_->revoked_mark_stacks_.push_back(tl_mark_stack);
953 thread->SetThreadLocalMarkStack(nullptr);
954 }
955 // Disable weak ref access.
956 if (disable_weak_ref_access_) {
957 thread->SetWeakRefAccessEnabled(false);
958 }
959 // If thread is a running mutator, then act on behalf of the garbage collector.
960 // See the code in ThreadList::RunCheckpoint.
961 concurrent_copying_->GetBarrier().Pass(self);
962 }
963
964 protected:
965 ConcurrentCopying* const concurrent_copying_;
966
967 private:
968 const bool disable_weak_ref_access_;
969};
970
971class ConcurrentCopying::CaptureThreadRootsForMarkingAndCheckpoint :
972 public RevokeThreadLocalMarkStackCheckpoint {
973 public:
974 explicit CaptureThreadRootsForMarkingAndCheckpoint(ConcurrentCopying* cc) :
975 RevokeThreadLocalMarkStackCheckpoint(cc, /* disable_weak_ref_access */ false) {}
976
977 void Run(Thread* thread) override
978 REQUIRES_SHARED(Locks::mutator_lock_) {
979 Thread* const self = Thread::Current();
980 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
981 // We can use the non-CAS VisitRoots functions below because we update thread-local GC roots
982 // only.
983 CaptureRootsForMarkingVisitor</*kAtomicTestAndSet*/ true> visitor(concurrent_copying_, self);
984 thread->VisitRoots(&visitor, kVisitRootFlagAllRoots);
985 // Barrier handling is done in the base class' Run() below.
986 RevokeThreadLocalMarkStackCheckpoint::Run(thread);
987 }
988};
989
990void ConcurrentCopying::CaptureThreadRootsForMarking() {
991 TimingLogger::ScopedTiming split("CaptureThreadRootsForMarking", GetTimings());
992 if (kVerboseMode) {
993 LOG(INFO) << "time=" << region_space_->Time();
994 region_space_->DumpNonFreeRegions(LOG_STREAM(INFO));
995 }
996 Thread* const self = Thread::Current();
997 CaptureThreadRootsForMarkingAndCheckpoint check_point(this);
998 ThreadList* thread_list = Runtime::Current()->GetThreadList();
999 gc_barrier_->Init(self, 0);
1000 size_t barrier_count = thread_list->RunCheckpoint(&check_point, /* callback */ nullptr);
1001 // If there are no threads to wait which implys that all the checkpoint functions are finished,
1002 // then no need to release the mutator lock.
1003 if (barrier_count == 0) {
1004 return;
1005 }
1006 Locks::mutator_lock_->SharedUnlock(self);
1007 {
1008 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
1009 gc_barrier_->Increment(self, barrier_count);
1010 }
1011 Locks::mutator_lock_->SharedLock(self);
1012 if (kVerboseMode) {
1013 LOG(INFO) << "time=" << region_space_->Time();
1014 region_space_->DumpNonFreeRegions(LOG_STREAM(INFO));
1015 LOG(INFO) << "GC end of CaptureThreadRootsForMarking";
1016 }
1017}
1018
1019// Used to scan ref fields of an object.
1020template <bool kHandleInterRegionRefs>
1021class ConcurrentCopying::ComputeLiveBytesAndMarkRefFieldsVisitor {
1022 public:
1023 explicit ComputeLiveBytesAndMarkRefFieldsVisitor(ConcurrentCopying* collector,
1024 size_t obj_region_idx)
1025 : collector_(collector),
1026 obj_region_idx_(obj_region_idx),
1027 contains_inter_region_idx_(false) {}
1028
1029 void operator()(mirror::Object* obj, MemberOffset offset, bool /* is_static */) const
1030 ALWAYS_INLINE
1031 REQUIRES_SHARED(Locks::mutator_lock_)
1032 REQUIRES_SHARED(Locks::heap_bitmap_lock_) {
1033 DCHECK_EQ(collector_->RegionSpace()->RegionIdxForRef(obj), obj_region_idx_);
1034 DCHECK(kHandleInterRegionRefs || collector_->immune_spaces_.ContainsObject(obj));
1035 CheckReference(obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(offset));
1036 }
1037
1038 void operator()(ObjPtr<mirror::Class> klass, ObjPtr<mirror::Reference> ref) const
1039 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
1040 DCHECK(klass->IsTypeOfReferenceClass());
1041 // If the referent is not null, then we must re-visit the object during
1042 // copying phase to enqueue it for delayed processing and setting
1043 // read-barrier state to gray to ensure that call to GetReferent() triggers
1044 // the read-barrier. We use same data structure that is used to remember
1045 // objects with inter-region refs for this purpose too.
1046 if (kHandleInterRegionRefs
1047 && !contains_inter_region_idx_
1048 && ref->AsReference()->GetReferent<kWithoutReadBarrier>() != nullptr) {
1049 contains_inter_region_idx_ = true;
1050 }
1051 }
1052
1053 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
1054 ALWAYS_INLINE
1055 REQUIRES_SHARED(Locks::mutator_lock_) {
1056 if (!root->IsNull()) {
1057 VisitRoot(root);
1058 }
1059 }
1060
1061 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
1062 ALWAYS_INLINE
1063 REQUIRES_SHARED(Locks::mutator_lock_) {
1064 CheckReference(root->AsMirrorPtr());
1065 }
1066
1067 bool ContainsInterRegionRefs() const ALWAYS_INLINE REQUIRES_SHARED(Locks::mutator_lock_) {
1068 return contains_inter_region_idx_;
1069 }
1070
1071 private:
1072 void CheckReference(mirror::Object* ref) const
1073 REQUIRES_SHARED(Locks::mutator_lock_) {
1074 if (ref == nullptr) {
1075 // Nothing to do.
1076 return;
1077 }
1078 if (!collector_->TestAndSetMarkBitForRef(ref)) {
1079 collector_->PushOntoLocalMarkStack(ref);
1080 }
1081 if (kHandleInterRegionRefs && !contains_inter_region_idx_) {
1082 size_t ref_region_idx = collector_->RegionSpace()->RegionIdxForRef(ref);
1083 // If a region-space object refers to an outside object, we will have a
1084 // mismatch of region idx, but the object need not be re-visited in
1085 // copying phase.
1086 if (ref_region_idx != static_cast<size_t>(-1) && obj_region_idx_ != ref_region_idx) {
1087 contains_inter_region_idx_ = true;
1088 }
1089 }
1090 }
1091
1092 ConcurrentCopying* const collector_;
1093 const size_t obj_region_idx_;
1094 mutable bool contains_inter_region_idx_;
1095};
1096
1097void ConcurrentCopying::AddLiveBytesAndScanRef(mirror::Object* ref) {
1098 DCHECK(ref != nullptr);
1099 DCHECK(!immune_spaces_.ContainsObject(ref));
1100 DCHECK(TestMarkBitmapForRef(ref));
1101 size_t obj_region_idx = static_cast<size_t>(-1);
1102 if (LIKELY(region_space_->HasAddress(ref))) {
1103 obj_region_idx = region_space_->RegionIdxForRefUnchecked(ref);
1104 // Add live bytes to the corresponding region
1105 if (!region_space_->IsRegionNewlyAllocated(obj_region_idx)) {
1106 // Newly Allocated regions are always chosen for evacuation. So no need
1107 // to update live_bytes_.
1108 size_t obj_size = ref->SizeOf<kDefaultVerifyFlags>();
1109 size_t alloc_size = RoundUp(obj_size, space::RegionSpace::kAlignment);
1110 region_space_->AddLiveBytes(ref, alloc_size);
1111 }
1112 }
1113 ComputeLiveBytesAndMarkRefFieldsVisitor</*kHandleInterRegionRefs*/ true>
1114 visitor(this, obj_region_idx);
1115 ref->VisitReferences</*kVisitNativeRoots=*/true, kDefaultVerifyFlags, kWithoutReadBarrier>(
1116 visitor, visitor);
1117 // Mark the corresponding card dirty if the object contains any
1118 // inter-region reference.
1119 if (visitor.ContainsInterRegionRefs()) {
Lokesh Gidrad0c5b252018-12-05 01:10:40 -08001120 inter_region_bitmap_->Set(ref);
Lokesh Gidra2a9824c2018-11-07 15:57:17 -08001121 }
1122}
1123
1124template <bool kAtomic>
1125bool ConcurrentCopying::TestAndSetMarkBitForRef(mirror::Object* ref) {
1126 accounting::ContinuousSpaceBitmap* bitmap = nullptr;
1127 accounting::LargeObjectBitmap* los_bitmap = nullptr;
1128 if (LIKELY(region_space_->HasAddress(ref))) {
1129 bitmap = region_space_bitmap_;
1130 } else if (heap_->GetNonMovingSpace()->HasAddress(ref)) {
1131 bitmap = heap_->GetNonMovingSpace()->GetMarkBitmap();
1132 } else if (immune_spaces_.ContainsObject(ref)) {
1133 // References to immune space objects are always live.
1134 DCHECK(heap_mark_bitmap_->GetContinuousSpaceBitmap(ref)->Test(ref));
1135 return true;
1136 } else {
1137 // Should be a large object. Must be page aligned and the LOS must exist.
1138 if (kIsDebugBuild
1139 && (!IsAligned<kPageSize>(ref) || heap_->GetLargeObjectsSpace() == nullptr)) {
1140 // It must be heap corruption. Remove memory protection and dump data.
1141 region_space_->Unprotect();
1142 heap_->GetVerification()->LogHeapCorruption(/* obj */ nullptr,
1143 MemberOffset(0),
1144 ref,
1145 /* fatal */ true);
1146 }
1147 los_bitmap = heap_->GetLargeObjectsSpace()->GetMarkBitmap();
1148 }
1149 if (kAtomic) {
1150 return (bitmap != nullptr) ? bitmap->AtomicTestAndSet(ref) : los_bitmap->AtomicTestAndSet(ref);
1151 } else {
1152 return (bitmap != nullptr) ? bitmap->Set(ref) : los_bitmap->Set(ref);
1153 }
1154}
1155
1156bool ConcurrentCopying::TestMarkBitmapForRef(mirror::Object* ref) {
1157 if (LIKELY(region_space_->HasAddress(ref))) {
1158 return region_space_bitmap_->Test(ref);
1159 } else if (heap_->GetNonMovingSpace()->HasAddress(ref)) {
1160 return heap_->GetNonMovingSpace()->GetMarkBitmap()->Test(ref);
1161 } else if (immune_spaces_.ContainsObject(ref)) {
1162 // References to immune space objects are always live.
1163 DCHECK(heap_mark_bitmap_->GetContinuousSpaceBitmap(ref)->Test(ref));
1164 return true;
1165 } else {
1166 // Should be a large object. Must be page aligned and the LOS must exist.
1167 if (kIsDebugBuild
1168 && (!IsAligned<kPageSize>(ref) || heap_->GetLargeObjectsSpace() == nullptr)) {
1169 // It must be heap corruption. Remove memory protection and dump data.
1170 region_space_->Unprotect();
1171 heap_->GetVerification()->LogHeapCorruption(/* obj */ nullptr,
1172 MemberOffset(0),
1173 ref,
1174 /* fatal */ true);
1175 }
1176 return heap_->GetLargeObjectsSpace()->GetMarkBitmap()->Test(ref);
1177 }
1178}
1179
1180void ConcurrentCopying::PushOntoLocalMarkStack(mirror::Object* ref) {
1181 if (kIsDebugBuild) {
1182 Thread *self = Thread::Current();
1183 DCHECK_EQ(thread_running_gc_, self);
1184 DCHECK(self->GetThreadLocalMarkStack() == nullptr);
1185 }
1186 DCHECK_EQ(mark_stack_mode_.load(std::memory_order_relaxed), kMarkStackModeThreadLocal);
1187 gc_mark_stack_->PushBack(ref);
1188}
1189
1190void ConcurrentCopying::ProcessMarkStackForMarkingAndComputeLiveBytes() {
1191 // Process thread-local mark stack containing thread roots
1192 ProcessThreadLocalMarkStacks(/* disable_weak_ref_access */ false,
1193 /* checkpoint_callback */ nullptr,
1194 [this] (mirror::Object* ref)
1195 REQUIRES_SHARED(Locks::mutator_lock_) {
1196 AddLiveBytesAndScanRef(ref);
1197 });
1198
1199 while (!gc_mark_stack_->IsEmpty()) {
1200 mirror::Object* ref = gc_mark_stack_->PopBack();
1201 AddLiveBytesAndScanRef(ref);
1202 }
1203}
1204
1205class ConcurrentCopying::ImmuneSpaceCaptureRefsVisitor {
1206 public:
1207 explicit ImmuneSpaceCaptureRefsVisitor(ConcurrentCopying* cc) : collector_(cc) {}
1208
1209 ALWAYS_INLINE void operator()(mirror::Object* obj) const REQUIRES_SHARED(Locks::mutator_lock_) {
1210 ComputeLiveBytesAndMarkRefFieldsVisitor</*kHandleInterRegionRefs*/ false>
1211 visitor(collector_, /*obj_region_idx*/ static_cast<size_t>(-1));
1212 obj->VisitReferences</*kVisitNativeRoots=*/true, kDefaultVerifyFlags, kWithoutReadBarrier>(
1213 visitor, visitor);
1214 }
1215
1216 static void Callback(mirror::Object* obj, void* arg) REQUIRES_SHARED(Locks::mutator_lock_) {
1217 reinterpret_cast<ImmuneSpaceScanObjVisitor*>(arg)->operator()(obj);
1218 }
1219
1220 private:
1221 ConcurrentCopying* const collector_;
1222};
1223
1224/* Invariants for two-phase CC
1225 * ===========================
1226 * A) Definitions
1227 * ---------------
1228 * 1) Black: marked in bitmap, rb_state is non-gray, and not in mark stack
1229 * 2) Black-clean: marked in bitmap, and corresponding card is clean/aged
1230 * 3) Black-dirty: marked in bitmap, and corresponding card is dirty
1231 * 4) Gray: marked in bitmap, and exists in mark stack
1232 * 5) Gray-dirty: marked in bitmap, rb_state is gray, corresponding card is
1233 * dirty, and exists in mark stack
1234 * 6) White: unmarked in bitmap, rb_state is non-gray, and not in mark stack
1235 *
1236 * B) Before marking phase
1237 * -----------------------
1238 * 1) All objects are white
1239 * 2) Cards are either clean or aged (cannot be asserted without a STW pause)
1240 * 3) Mark bitmap is cleared
1241 * 4) Mark stack is empty
1242 *
1243 * C) During marking phase
1244 * ------------------------
1245 * 1) If a black object holds an inter-region or white reference, then its
1246 * corresponding card is dirty. In other words, it changes from being
1247 * black-clean to black-dirty
1248 * 2) No black-clean object points to a white object
1249 *
1250 * D) After marking phase
1251 * -----------------------
1252 * 1) There are no gray objects
1253 * 2) All newly allocated objects are in from space
1254 * 3) No white object can be reachable, directly or otherwise, from a
1255 * black-clean object
1256 *
1257 * E) During copying phase
1258 * ------------------------
1259 * 1) Mutators cannot observe white and black-dirty objects
1260 * 2) New allocations are in to-space (newly allocated regions are part of to-space)
1261 * 3) An object in mark stack must have its rb_state = Gray
1262 *
1263 * F) During card table scan
1264 * --------------------------
1265 * 1) Referents corresponding to root references are gray or in to-space
1266 * 2) Every path from an object that is read or written by a mutator during
1267 * this period to a dirty black object goes through some gray object.
1268 * Mutators preserve this by graying black objects as needed during this
1269 * period. Ensures that a mutator never encounters a black dirty object.
1270 *
1271 * G) After card table scan
1272 * ------------------------
1273 * 1) There are no black-dirty objects
1274 * 2) Referents corresponding to root references are gray, black-clean or in
1275 * to-space
1276 *
1277 * H) After copying phase
1278 * -----------------------
1279 * 1) Mark stack is empty
1280 * 2) No references into evacuated from-space
1281 * 3) No reference to an object which is unmarked and is also not in newly
1282 * allocated region. In other words, no reference to white objects.
1283*/
1284
1285void ConcurrentCopying::MarkingPhase() {
1286 TimingLogger::ScopedTiming split("MarkingPhase", GetTimings());
1287 if (kVerboseMode) {
1288 LOG(INFO) << "GC MarkingPhase";
1289 }
1290 accounting::CardTable* const card_table = heap_->GetCardTable();
1291 Thread* const self = Thread::Current();
1292 // Clear live_bytes_ of every non-free region, except the ones that are newly
1293 // allocated.
1294 region_space_->SetAllRegionLiveBytesZero();
1295 if (kIsDebugBuild) {
1296 region_space_->AssertAllRegionLiveBytesZeroOrCleared();
1297 }
1298 // Scan immune spaces
1299 {
1300 TimingLogger::ScopedTiming split2("ScanImmuneSpaces", GetTimings());
1301 for (auto& space : immune_spaces_.GetSpaces()) {
1302 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
1303 accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
1304 accounting::ModUnionTable* table = heap_->FindModUnionTableFromSpace(space);
1305 ImmuneSpaceCaptureRefsVisitor visitor(this);
1306 if (table != nullptr) {
1307 table->VisitObjects(ImmuneSpaceCaptureRefsVisitor::Callback, &visitor);
1308 } else {
1309 WriterMutexLock rmu(Thread::Current(), *Locks::heap_bitmap_lock_);
1310 card_table->Scan<false>(
1311 live_bitmap,
1312 space->Begin(),
1313 space->Limit(),
1314 visitor,
1315 accounting::CardTable::kCardDirty - 1);
1316 }
1317 }
1318 }
1319 // Scan runtime roots
1320 {
1321 TimingLogger::ScopedTiming split2("VisitConcurrentRoots", GetTimings());
1322 CaptureRootsForMarkingVisitor visitor(this, self);
1323 Runtime::Current()->VisitConcurrentRoots(&visitor, kVisitRootFlagAllRoots);
1324 }
1325 {
1326 // TODO: don't visit the transaction roots if it's not active.
1327 TimingLogger::ScopedTiming split2("VisitNonThreadRoots", GetTimings());
1328 CaptureRootsForMarkingVisitor visitor(this, self);
1329 Runtime::Current()->VisitNonThreadRoots(&visitor);
1330 }
1331 // Capture thread roots
1332 CaptureThreadRootsForMarking();
1333 // Process mark stack
1334 ProcessMarkStackForMarkingAndComputeLiveBytes();
1335
Lokesh Gidra2a9824c2018-11-07 15:57:17 -08001336 if (kVerboseMode) {
1337 LOG(INFO) << "GC end of MarkingPhase";
1338 }
1339}
1340
Lokesh Gidra8f5aaad2018-12-11 15:05:56 -08001341template <bool kNoUnEvac>
1342void ConcurrentCopying::ScanDirtyObject(mirror::Object* obj) {
1343 Scan<kNoUnEvac>(obj);
1344 // Set the read-barrier state of a reference-type object to gray if its
1345 // referent is not marked yet. This is to ensure that if GetReferent() is
1346 // called, it triggers the read-barrier to process the referent before use.
1347 if (UNLIKELY((obj->GetClass<kVerifyNone, kWithoutReadBarrier>()->IsTypeOfReferenceClass()))) {
1348 mirror::Object* referent =
1349 obj->AsReference<kVerifyNone, kWithoutReadBarrier>()->GetReferent<kWithoutReadBarrier>();
1350 if (referent != nullptr && !IsInToSpace(referent)) {
1351 obj->AtomicSetReadBarrierState(ReadBarrier::NonGrayState(), ReadBarrier::GrayState());
1352 }
1353 }
1354}
1355
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001356// Concurrently mark roots that are guarded by read barriers and process the mark stack.
Lokesh Gidra2a9824c2018-11-07 15:57:17 -08001357void ConcurrentCopying::CopyingPhase() {
1358 TimingLogger::ScopedTiming split("CopyingPhase", GetTimings());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001359 if (kVerboseMode) {
Lokesh Gidra2a9824c2018-11-07 15:57:17 -08001360 LOG(INFO) << "GC CopyingPhase";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001361 }
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001362 Thread* self = Thread::Current();
Lokesh Gidra2a9824c2018-11-07 15:57:17 -08001363 accounting::CardTable* const card_table = heap_->GetCardTable();
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001364 if (kIsDebugBuild) {
1365 MutexLock mu(self, *Locks::thread_list_lock_);
1366 CHECK(weak_ref_access_enabled_);
1367 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001368
1369 // Scan immune spaces.
1370 // Update all the fields in the immune spaces first without graying the objects so that we
1371 // minimize dirty pages in the immune spaces. Note mutators can concurrently access and gray some
1372 // of the objects.
1373 if (kUseBakerReadBarrier) {
1374 gc_grays_immune_objects_ = false;
Hiroshi Yamauchi16292fc2016-06-20 20:23:34 -07001375 }
Lokesh Gidra2a9824c2018-11-07 15:57:17 -08001376 if (kEnableGenerationalConcurrentCopyingCollection) {
Roland Levillain57ce0542018-08-07 16:20:31 +01001377 if (kVerboseMode) {
1378 LOG(INFO) << "GC ScanCardsForSpace";
1379 }
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07001380 TimingLogger::ScopedTiming split2("ScanCardsForSpace", GetTimings());
1381 WriterMutexLock rmu(Thread::Current(), *Locks::heap_bitmap_lock_);
Roland Levillain2d94e292018-08-15 16:46:30 +01001382 CHECK(!done_scanning_.load(std::memory_order_relaxed));
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07001383 if (kIsDebugBuild) {
1384 // Leave some time for mutators to race ahead to try and find races between the GC card
1385 // scanning and mutators reading references.
1386 usleep(10 * 1000);
1387 }
1388 for (space::ContinuousSpace* space : GetHeap()->GetContinuousSpaces()) {
1389 if (space->IsImageSpace() || space->IsZygoteSpace()) {
1390 // Image and zygote spaces are already handled since we gray the objects in the pause.
1391 continue;
1392 }
1393 // Scan all of the objects on dirty cards in unevac from space, and non moving space. These
Lokesh Gidra2a9824c2018-11-07 15:57:17 -08001394 // are from previous GCs (or from marking phase of 2-phase full GC) and may reference things
1395 // in the from space.
Roland Levillain4ba92462018-08-15 19:16:24 +01001396 //
1397 // Note that we do not need to process the large-object space (the only discontinuous space)
1398 // as it contains only large string objects and large primitive array objects, that have no
1399 // reference to other objects, except their class. There is no need to scan these large
1400 // objects, as the String class and the primitive array classes are expected to never move
Lokesh Gidra2a9824c2018-11-07 15:57:17 -08001401 // during a collection:
Roland Levillain4ba92462018-08-15 19:16:24 +01001402 // - In the case where we run with a boot image, these classes are part of the image space,
1403 // which is an immune space.
Roland Levillain0e840272018-08-23 19:55:30 +01001404 // - In the case where we run without a boot image, these classes are allocated in the
1405 // non-moving space (see art::ClassLinker::InitWithoutImage).
Lokesh Gidra2a9824c2018-11-07 15:57:17 -08001406 card_table->Scan<false>(
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07001407 space->GetMarkBitmap(),
1408 space->Begin(),
1409 space->End(),
1410 [this, space](mirror::Object* obj)
1411 REQUIRES(Locks::heap_bitmap_lock_)
1412 REQUIRES_SHARED(Locks::mutator_lock_) {
Lokesh Gidra2a9824c2018-11-07 15:57:17 -08001413 // TODO: This code may be refactored to avoid scanning object while
1414 // done_scanning_ is false by setting rb_state to gray, and pushing the
1415 // object on mark stack. However, it will also require clearing the
1416 // corresponding mark-bit and, for region space objects,
1417 // decrementing the object's size from the corresponding region's
1418 // live_bytes.
1419 if (young_gen_) {
1420 // Don't push or gray unevac refs.
1421 if (kIsDebugBuild && space == region_space_) {
1422 // We may get unevac large objects.
1423 if (!region_space_->IsInUnevacFromSpace(obj)) {
1424 CHECK(region_space_bitmap_->Test(obj));
1425 region_space_->DumpRegionForObject(LOG_STREAM(FATAL_WITHOUT_ABORT), obj);
1426 LOG(FATAL) << "Scanning " << obj << " not in unevac space";
1427 }
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07001428 }
Lokesh Gidra2a9824c2018-11-07 15:57:17 -08001429 ScanDirtyObject</*kNoUnEvac*/ true>(obj);
1430 } else if (space != region_space_ || region_space_->IsInUnevacFromSpace(obj)) {
Lokesh Gidrad0c5b252018-12-05 01:10:40 -08001431 // We need to process un-evac references as they may be unprocessed,
1432 // if they skipped the marking phase due to heap mutation.
Lokesh Gidra2a9824c2018-11-07 15:57:17 -08001433 ScanDirtyObject</*kNoUnEvac*/ false>(obj);
Lokesh Gidrad0c5b252018-12-05 01:10:40 -08001434 inter_region_bitmap_->Clear(obj);
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07001435 }
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07001436 },
Lokesh Gidrad0c5b252018-12-05 01:10:40 -08001437 accounting::CardTable::kCardAged);
1438
1439 if (!young_gen_) {
1440 auto visitor = [this](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1441 // We don't need to process un-evac references as any unprocessed
1442 // ones will be taken care of in the card-table scan above.
1443 ScanDirtyObject</*kNoUnEvac*/ true>(obj);
1444 };
1445 if (space == region_space_) {
1446 region_space_->ScanUnevacFromSpace(inter_region_bitmap_.get(), visitor);
1447 } else {
1448 inter_region_bitmap_->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()),
1449 reinterpret_cast<uintptr_t>(space->End()),
1450 visitor);
1451 }
1452 }
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07001453 }
1454 // Done scanning unevac space.
Roland Levillain2d94e292018-08-15 16:46:30 +01001455 done_scanning_.store(true, std::memory_order_release);
Roland Levillain57ce0542018-08-07 16:20:31 +01001456 if (kVerboseMode) {
1457 LOG(INFO) << "GC end of ScanCardsForSpace";
1458 }
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07001459 }
Mathieu Chartier21328a12016-07-22 10:47:45 -07001460 {
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07001461 // For a sticky-bit collection, this phase needs to be after the card scanning since the
1462 // mutator may read an unevac space object out of an image object. If the image object is no
1463 // longer gray it will trigger a read barrier for the unevac space object.
Mathieu Chartier21328a12016-07-22 10:47:45 -07001464 TimingLogger::ScopedTiming split2("ScanImmuneSpaces", GetTimings());
1465 for (auto& space : immune_spaces_.GetSpaces()) {
1466 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
1467 accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
Hiroshi Yamauchi5408f232016-07-29 15:07:05 -07001468 accounting::ModUnionTable* table = heap_->FindModUnionTableFromSpace(space);
Mathieu Chartier21328a12016-07-22 10:47:45 -07001469 ImmuneSpaceScanObjVisitor visitor(this);
Hiroshi Yamauchi5408f232016-07-29 15:07:05 -07001470 if (kUseBakerReadBarrier && kGrayDirtyImmuneObjects && table != nullptr) {
1471 table->VisitObjects(ImmuneSpaceScanObjVisitor::Callback, &visitor);
1472 } else {
Lokesh Gidra2a9824c2018-11-07 15:57:17 -08001473 WriterMutexLock rmu(Thread::Current(), *Locks::heap_bitmap_lock_);
1474 card_table->Scan<false>(
1475 live_bitmap,
1476 space->Begin(),
1477 space->Limit(),
1478 visitor,
1479 accounting::CardTable::kCardDirty - 1);
Hiroshi Yamauchi5408f232016-07-29 15:07:05 -07001480 }
Mathieu Chartier21328a12016-07-22 10:47:45 -07001481 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001482 }
1483 if (kUseBakerReadBarrier) {
1484 // This release fence makes the field updates in the above loop visible before allowing mutator
1485 // getting access to immune objects without graying it first.
Orion Hodson88591fe2018-03-06 13:35:43 +00001486 updated_all_immune_objects_.store(true, std::memory_order_release);
Roland Levillain14e5a292018-06-28 12:00:56 +01001487 // Now "un-gray" (conceptually blacken) immune objects concurrently accessed and grayed by
1488 // mutators. We can't do this in the above loop because we would incorrectly disable the read
1489 // barrier by un-graying (conceptually blackening) an object which may point to an unscanned,
1490 // white object, breaking the to-space invariant (a mutator shall never observe a from-space
1491 // (white) object).
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001492 //
Roland Levillain14e5a292018-06-28 12:00:56 +01001493 // Make sure no mutators are in the middle of marking an immune object before un-graying
1494 // (blackening) immune objects.
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001495 IssueEmptyCheckpoint();
1496 MutexLock mu(Thread::Current(), immune_gray_stack_lock_);
1497 if (kVerboseMode) {
1498 LOG(INFO) << "immune gray stack size=" << immune_gray_stack_.size();
1499 }
1500 for (mirror::Object* obj : immune_gray_stack_) {
Roland Levillain14e5a292018-06-28 12:00:56 +01001501 DCHECK_EQ(obj->GetReadBarrierState(), ReadBarrier::GrayState());
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001502 bool success = obj->AtomicSetReadBarrierState(ReadBarrier::GrayState(),
Roland Levillain14e5a292018-06-28 12:00:56 +01001503 ReadBarrier::NonGrayState());
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07001504 DCHECK(success);
1505 }
1506 immune_gray_stack_.clear();
1507 }
1508
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001509 {
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001510 TimingLogger::ScopedTiming split2("VisitConcurrentRoots", GetTimings());
1511 Runtime::Current()->VisitConcurrentRoots(this, kVisitRootFlagAllRoots);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001512 }
1513 {
1514 // TODO: don't visit the transaction roots if it's not active.
1515 TimingLogger::ScopedTiming split5("VisitNonThreadRoots", GetTimings());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001516 Runtime::Current()->VisitNonThreadRoots(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001517 }
1518
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001519 {
Mathieu Chartiera6b1ead2015-10-06 10:32:38 -07001520 TimingLogger::ScopedTiming split7("ProcessMarkStack", GetTimings());
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001521 // We transition through three mark stack modes (thread-local, shared, GC-exclusive). The
1522 // primary reasons are the fact that we need to use a checkpoint to process thread-local mark
1523 // stacks, but after we disable weak refs accesses, we can't use a checkpoint due to a deadlock
1524 // issue because running threads potentially blocking at WaitHoldingLocks, and that once we
1525 // reach the point where we process weak references, we can avoid using a lock when accessing
1526 // the GC mark stack, which makes mark stack processing more efficient.
1527
1528 // Process the mark stack once in the thread local stack mode. This marks most of the live
1529 // objects, aside from weak ref accesses with read barriers (Reference::GetReferent() and system
1530 // weaks) that may happen concurrently while we processing the mark stack and newly mark/gray
1531 // objects and push refs on the mark stack.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001532 ProcessMarkStack();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001533 // Switch to the shared mark stack mode. That is, revoke and process thread-local mark stacks
1534 // for the last time before transitioning to the shared mark stack mode, which would process new
1535 // refs that may have been concurrently pushed onto the mark stack during the ProcessMarkStack()
1536 // call above. At the same time, disable weak ref accesses using a per-thread flag. It's
1537 // important to do these together in a single checkpoint so that we can ensure that mutators
1538 // won't newly gray objects and push new refs onto the mark stack due to weak ref accesses and
1539 // mutators safely transition to the shared mark stack mode (without leaving unprocessed refs on
1540 // the thread-local mark stacks), without a race. This is why we use a thread-local weak ref
1541 // access flag Thread::tls32_.weak_ref_access_enabled_ instead of the global ones.
1542 SwitchToSharedMarkStackMode();
1543 CHECK(!self->GetWeakRefAccessEnabled());
1544 // Now that weak refs accesses are disabled, once we exhaust the shared mark stack again here
1545 // (which may be non-empty if there were refs found on thread-local mark stacks during the above
1546 // SwitchToSharedMarkStackMode() call), we won't have new refs to process, that is, mutators
1547 // (via read barriers) have no way to produce any more refs to process. Marking converges once
1548 // before we process weak refs below.
1549 ProcessMarkStack();
1550 CheckEmptyMarkStack();
1551 // Switch to the GC exclusive mark stack mode so that we can process the mark stack without a
1552 // lock from this point on.
1553 SwitchToGcExclusiveMarkStackMode();
1554 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001555 if (kVerboseMode) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001556 LOG(INFO) << "ProcessReferences";
1557 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001558 // Process weak references. This may produce new refs to process and have them processed via
Mathieu Chartier97509952015-07-13 14:35:43 -07001559 // ProcessMarkStack (in the GC exclusive mark stack mode).
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001560 ProcessReferences(self);
1561 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001562 if (kVerboseMode) {
1563 LOG(INFO) << "SweepSystemWeaks";
1564 }
1565 SweepSystemWeaks(self);
1566 if (kVerboseMode) {
1567 LOG(INFO) << "SweepSystemWeaks done";
1568 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001569 // Process the mark stack here one last time because the above SweepSystemWeaks() call may have
1570 // marked some objects (strings alive) as hash_set::Erase() can call the hash function for
1571 // arbitrary elements in the weak intern table in InternTable::Table::SweepWeaks().
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001572 ProcessMarkStack();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001573 CheckEmptyMarkStack();
1574 // Re-enable weak ref accesses.
1575 ReenableWeakRefAccess(self);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07001576 // Free data for class loaders that we unloaded.
1577 Runtime::Current()->GetClassLinker()->CleanupClassLoaders();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001578 // Marking is done. Disable marking.
Hiroshi Yamauchi00370822015-08-18 14:47:25 -07001579 DisableMarking();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001580 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001581 }
1582
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001583 if (kIsDebugBuild) {
1584 MutexLock mu(self, *Locks::thread_list_lock_);
1585 CHECK(weak_ref_access_enabled_);
1586 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001587 if (kVerboseMode) {
Lokesh Gidra2a9824c2018-11-07 15:57:17 -08001588 LOG(INFO) << "GC end of CopyingPhase";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001589 }
1590}
1591
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001592void ConcurrentCopying::ReenableWeakRefAccess(Thread* self) {
1593 if (kVerboseMode) {
1594 LOG(INFO) << "ReenableWeakRefAccess";
1595 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001596 // Iterate all threads (don't need to or can't use a checkpoint) and re-enable weak ref access.
1597 {
1598 MutexLock mu(self, *Locks::thread_list_lock_);
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001599 weak_ref_access_enabled_ = true; // This is for new threads.
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001600 std::list<Thread*> thread_list = Runtime::Current()->GetThreadList()->GetList();
1601 for (Thread* thread : thread_list) {
1602 thread->SetWeakRefAccessEnabled(true);
1603 }
1604 }
1605 // Unblock blocking threads.
1606 GetHeap()->GetReferenceProcessor()->BroadcastForSlowPath(self);
1607 Runtime::Current()->BroadcastForNewSystemWeaks();
1608}
1609
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001610class ConcurrentCopying::DisableMarkingCheckpoint : public Closure {
Hiroshi Yamauchi00370822015-08-18 14:47:25 -07001611 public:
1612 explicit DisableMarkingCheckpoint(ConcurrentCopying* concurrent_copying)
1613 : concurrent_copying_(concurrent_copying) {
1614 }
1615
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001616 void Run(Thread* thread) override NO_THREAD_SAFETY_ANALYSIS {
Hiroshi Yamauchi00370822015-08-18 14:47:25 -07001617 // Note: self is not necessarily equal to thread since thread may be suspended.
1618 Thread* self = Thread::Current();
1619 DCHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
1620 << thread->GetState() << " thread " << thread << " self " << self;
1621 // Disable the thread-local is_gc_marking flag.
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -07001622 // Note a thread that has just started right before this checkpoint may have already this flag
1623 // set to false, which is ok.
Mathieu Chartierfe814e82016-11-09 14:32:49 -08001624 thread->SetIsGcMarkingAndUpdateEntrypoints(false);
Hiroshi Yamauchi00370822015-08-18 14:47:25 -07001625 // If thread is a running mutator, then act on behalf of the garbage collector.
1626 // See the code in ThreadList::RunCheckpoint.
Mathieu Chartier10d25082015-10-28 18:36:09 -07001627 concurrent_copying_->GetBarrier().Pass(self);
Hiroshi Yamauchi00370822015-08-18 14:47:25 -07001628 }
1629
1630 private:
1631 ConcurrentCopying* const concurrent_copying_;
1632};
1633
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001634class ConcurrentCopying::DisableMarkingCallback : public Closure {
1635 public:
1636 explicit DisableMarkingCallback(ConcurrentCopying* concurrent_copying)
1637 : concurrent_copying_(concurrent_copying) {
1638 }
1639
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001640 void Run(Thread* self ATTRIBUTE_UNUSED) override REQUIRES(Locks::thread_list_lock_) {
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001641 // This needs to run under the thread_list_lock_ critical section in ThreadList::RunCheckpoint()
1642 // to avoid a race with ThreadList::Register().
1643 CHECK(concurrent_copying_->is_marking_);
1644 concurrent_copying_->is_marking_ = false;
Mathieu Chartiera9a4f5f2017-05-03 18:19:13 -07001645 if (kUseBakerReadBarrier && kGrayDirtyImmuneObjects) {
1646 CHECK(concurrent_copying_->is_using_read_barrier_entrypoints_);
1647 concurrent_copying_->is_using_read_barrier_entrypoints_ = false;
1648 } else {
1649 CHECK(!concurrent_copying_->is_using_read_barrier_entrypoints_);
1650 }
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001651 }
1652
1653 private:
1654 ConcurrentCopying* const concurrent_copying_;
1655};
1656
Hiroshi Yamauchi00370822015-08-18 14:47:25 -07001657void ConcurrentCopying::IssueDisableMarkingCheckpoint() {
1658 Thread* self = Thread::Current();
1659 DisableMarkingCheckpoint check_point(this);
1660 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1661 gc_barrier_->Init(self, 0);
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001662 DisableMarkingCallback dmc(this);
1663 size_t barrier_count = thread_list->RunCheckpoint(&check_point, &dmc);
Hiroshi Yamauchi00370822015-08-18 14:47:25 -07001664 // If there are no threads to wait which implies that all the checkpoint functions are finished,
1665 // then no need to release the mutator lock.
1666 if (barrier_count == 0) {
1667 return;
1668 }
1669 // Release locks then wait for all mutator threads to pass the barrier.
1670 Locks::mutator_lock_->SharedUnlock(self);
1671 {
1672 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
1673 gc_barrier_->Increment(self, barrier_count);
1674 }
1675 Locks::mutator_lock_->SharedLock(self);
1676}
1677
1678void ConcurrentCopying::DisableMarking() {
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001679 // Use a checkpoint to turn off the global is_marking and the thread-local is_gc_marking flags and
1680 // to ensure no threads are still in the middle of a read barrier which may have a from-space ref
1681 // cached in a local variable.
Hiroshi Yamauchi00370822015-08-18 14:47:25 -07001682 IssueDisableMarkingCheckpoint();
1683 if (kUseTableLookupReadBarrier) {
1684 heap_->rb_table_->ClearAll();
1685 DCHECK(heap_->rb_table_->IsAllCleared());
1686 }
Orion Hodson88591fe2018-03-06 13:35:43 +00001687 is_mark_stack_push_disallowed_.store(1, std::memory_order_seq_cst);
1688 mark_stack_mode_.store(kMarkStackModeOff, std::memory_order_seq_cst);
Hiroshi Yamauchi00370822015-08-18 14:47:25 -07001689}
1690
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001691void ConcurrentCopying::IssueEmptyCheckpoint() {
1692 Thread* self = Thread::Current();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001693 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001694 // Release locks then wait for all mutator threads to pass the barrier.
1695 Locks::mutator_lock_->SharedUnlock(self);
Hiroshi Yamauchia2224042017-02-08 16:35:45 -08001696 thread_list->RunEmptyCheckpoint();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001697 Locks::mutator_lock_->SharedLock(self);
1698}
1699
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -07001700void ConcurrentCopying::ExpandGcMarkStack() {
1701 DCHECK(gc_mark_stack_->IsFull());
1702 const size_t new_size = gc_mark_stack_->Capacity() * 2;
1703 std::vector<StackReference<mirror::Object>> temp(gc_mark_stack_->Begin(),
1704 gc_mark_stack_->End());
1705 gc_mark_stack_->Resize(new_size);
1706 for (auto& ref : temp) {
1707 gc_mark_stack_->PushBack(ref.AsMirrorPtr());
1708 }
1709 DCHECK(!gc_mark_stack_->IsFull());
1710}
1711
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08001712void ConcurrentCopying::PushOntoMarkStack(Thread* const self, mirror::Object* to_ref) {
Orion Hodson88591fe2018-03-06 13:35:43 +00001713 CHECK_EQ(is_mark_stack_push_disallowed_.load(std::memory_order_relaxed), 0)
David Sehr709b0702016-10-13 09:12:37 -07001714 << " " << to_ref << " " << mirror::Object::PrettyTypeOf(to_ref);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001715 CHECK(thread_running_gc_ != nullptr);
Orion Hodson88591fe2018-03-06 13:35:43 +00001716 MarkStackMode mark_stack_mode = mark_stack_mode_.load(std::memory_order_relaxed);
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001717 if (LIKELY(mark_stack_mode == kMarkStackModeThreadLocal)) {
1718 if (LIKELY(self == thread_running_gc_)) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001719 // If GC-running thread, use the GC mark stack instead of a thread-local mark stack.
1720 CHECK(self->GetThreadLocalMarkStack() == nullptr);
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -07001721 if (UNLIKELY(gc_mark_stack_->IsFull())) {
1722 ExpandGcMarkStack();
1723 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001724 gc_mark_stack_->PushBack(to_ref);
1725 } else {
1726 // Otherwise, use a thread-local mark stack.
1727 accounting::AtomicStack<mirror::Object>* tl_mark_stack = self->GetThreadLocalMarkStack();
1728 if (UNLIKELY(tl_mark_stack == nullptr || tl_mark_stack->IsFull())) {
1729 MutexLock mu(self, mark_stack_lock_);
1730 // Get a new thread local mark stack.
1731 accounting::AtomicStack<mirror::Object>* new_tl_mark_stack;
1732 if (!pooled_mark_stacks_.empty()) {
1733 // Use a pooled mark stack.
1734 new_tl_mark_stack = pooled_mark_stacks_.back();
1735 pooled_mark_stacks_.pop_back();
1736 } else {
1737 // None pooled. Create a new one.
1738 new_tl_mark_stack =
1739 accounting::AtomicStack<mirror::Object>::Create(
1740 "thread local mark stack", 4 * KB, 4 * KB);
1741 }
1742 DCHECK(new_tl_mark_stack != nullptr);
1743 DCHECK(new_tl_mark_stack->IsEmpty());
1744 new_tl_mark_stack->PushBack(to_ref);
1745 self->SetThreadLocalMarkStack(new_tl_mark_stack);
1746 if (tl_mark_stack != nullptr) {
1747 // Store the old full stack into a vector.
1748 revoked_mark_stacks_.push_back(tl_mark_stack);
1749 }
1750 } else {
1751 tl_mark_stack->PushBack(to_ref);
1752 }
1753 }
1754 } else if (mark_stack_mode == kMarkStackModeShared) {
1755 // Access the shared GC mark stack with a lock.
1756 MutexLock mu(self, mark_stack_lock_);
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -07001757 if (UNLIKELY(gc_mark_stack_->IsFull())) {
1758 ExpandGcMarkStack();
1759 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001760 gc_mark_stack_->PushBack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001761 } else {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001762 CHECK_EQ(static_cast<uint32_t>(mark_stack_mode),
Hiroshi Yamauchifa755182015-09-30 20:12:11 -07001763 static_cast<uint32_t>(kMarkStackModeGcExclusive))
1764 << "ref=" << to_ref
1765 << " self->gc_marking=" << self->GetIsGcMarking()
1766 << " cc->is_marking=" << is_marking_;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001767 CHECK(self == thread_running_gc_)
1768 << "Only GC-running thread should access the mark stack "
1769 << "in the GC exclusive mark stack mode";
1770 // Access the GC mark stack without a lock.
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -07001771 if (UNLIKELY(gc_mark_stack_->IsFull())) {
1772 ExpandGcMarkStack();
1773 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001774 gc_mark_stack_->PushBack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001775 }
1776}
1777
1778accounting::ObjectStack* ConcurrentCopying::GetAllocationStack() {
1779 return heap_->allocation_stack_.get();
1780}
1781
1782accounting::ObjectStack* ConcurrentCopying::GetLiveStack() {
1783 return heap_->live_stack_.get();
1784}
1785
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001786// The following visitors are used to verify that there's no references to the from-space left after
1787// marking.
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001788class ConcurrentCopying::VerifyNoFromSpaceRefsVisitor : public SingleRootVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001789 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001790 explicit VerifyNoFromSpaceRefsVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001791 : collector_(collector) {}
1792
Mathieu Chartierbc632f02017-04-20 13:31:39 -07001793 void operator()(mirror::Object* ref,
1794 MemberOffset offset = MemberOffset(0),
1795 mirror::Object* holder = nullptr) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001796 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001797 if (ref == nullptr) {
1798 // OK.
1799 return;
1800 }
Mathieu Chartierbc632f02017-04-20 13:31:39 -07001801 collector_->AssertToSpaceInvariant(holder, offset, ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001802 if (kUseBakerReadBarrier) {
Roland Levillain14e5a292018-06-28 12:00:56 +01001803 CHECK_EQ(ref->GetReadBarrierState(), ReadBarrier::NonGrayState())
1804 << "Ref " << ref << " " << ref->PrettyTypeOf() << " has gray rb_state";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001805 }
1806 }
1807
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001808 void VisitRoot(mirror::Object* root, const RootInfo& info ATTRIBUTE_UNUSED)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001809 override REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001810 DCHECK(root != nullptr);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001811 operator()(root);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001812 }
1813
1814 private:
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001815 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001816};
1817
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001818class ConcurrentCopying::VerifyNoFromSpaceRefsFieldVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001819 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001820 explicit VerifyNoFromSpaceRefsFieldVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001821 : collector_(collector) {}
1822
Mathieu Chartier31e88222016-10-14 18:43:19 -07001823 void operator()(ObjPtr<mirror::Object> obj,
1824 MemberOffset offset,
1825 bool is_static ATTRIBUTE_UNUSED) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001826 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001827 mirror::Object* ref =
1828 obj->GetFieldObject<mirror::Object, kDefaultVerifyFlags, kWithoutReadBarrier>(offset);
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001829 VerifyNoFromSpaceRefsVisitor visitor(collector_);
Mathieu Chartierbc632f02017-04-20 13:31:39 -07001830 visitor(ref, offset, obj.Ptr());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001831 }
Mathieu Chartier31e88222016-10-14 18:43:19 -07001832 void operator()(ObjPtr<mirror::Class> klass,
1833 ObjPtr<mirror::Reference> ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001834 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001835 CHECK(klass->IsTypeOfReferenceClass());
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07001836 this->operator()(ObjPtr<mirror::Object>(ref), mirror::Reference::ReferentOffset(), false);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001837 }
1838
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001839 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001840 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001841 if (!root->IsNull()) {
1842 VisitRoot(root);
1843 }
1844 }
1845
1846 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001847 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001848 VerifyNoFromSpaceRefsVisitor visitor(collector_);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001849 visitor(root->AsMirrorPtr());
1850 }
1851
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001852 private:
Mathieu Chartier97509952015-07-13 14:35:43 -07001853 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001854};
1855
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001856// Verify there's no from-space references left after the marking phase.
1857void ConcurrentCopying::VerifyNoFromSpaceReferences() {
1858 Thread* self = Thread::Current();
1859 DCHECK(Locks::mutator_lock_->IsExclusiveHeld(self));
Hiroshi Yamauchi00370822015-08-18 14:47:25 -07001860 // Verify all threads have is_gc_marking to be false
1861 {
1862 MutexLock mu(self, *Locks::thread_list_lock_);
1863 std::list<Thread*> thread_list = Runtime::Current()->GetThreadList()->GetList();
1864 for (Thread* thread : thread_list) {
1865 CHECK(!thread->GetIsGcMarking());
1866 }
1867 }
Andreas Gampe0c183382017-07-13 22:26:24 -07001868
1869 auto verify_no_from_space_refs_visitor = [&](mirror::Object* obj)
1870 REQUIRES_SHARED(Locks::mutator_lock_) {
1871 CHECK(obj != nullptr);
1872 space::RegionSpace* region_space = RegionSpace();
1873 CHECK(!region_space->IsInFromSpace(obj)) << "Scanning object " << obj << " in from space";
1874 VerifyNoFromSpaceRefsFieldVisitor visitor(this);
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001875 obj->VisitReferences</*kVisitNativeRoots=*/true, kDefaultVerifyFlags, kWithoutReadBarrier>(
Andreas Gampe0c183382017-07-13 22:26:24 -07001876 visitor,
1877 visitor);
1878 if (kUseBakerReadBarrier) {
Roland Levillain14e5a292018-06-28 12:00:56 +01001879 CHECK_EQ(obj->GetReadBarrierState(), ReadBarrier::NonGrayState())
1880 << "obj=" << obj << " has gray rb_state " << obj->GetReadBarrierState();
Andreas Gampe0c183382017-07-13 22:26:24 -07001881 }
1882 };
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001883 // Roots.
1884 {
1885 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001886 VerifyNoFromSpaceRefsVisitor ref_visitor(this);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001887 Runtime::Current()->VisitRoots(&ref_visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001888 }
1889 // The to-space.
Andreas Gampe0c183382017-07-13 22:26:24 -07001890 region_space_->WalkToSpace(verify_no_from_space_refs_visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001891 // Non-moving spaces.
1892 {
1893 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Andreas Gampe0c183382017-07-13 22:26:24 -07001894 heap_->GetMarkBitmap()->Visit(verify_no_from_space_refs_visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001895 }
1896 // The alloc stack.
1897 {
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001898 VerifyNoFromSpaceRefsVisitor ref_visitor(this);
Mathieu Chartiercb535da2015-01-23 13:50:03 -08001899 for (auto* it = heap_->allocation_stack_->Begin(), *end = heap_->allocation_stack_->End();
1900 it < end; ++it) {
1901 mirror::Object* const obj = it->AsMirrorPtr();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001902 if (obj != nullptr && obj->GetClass() != nullptr) {
1903 // TODO: need to call this only if obj is alive?
1904 ref_visitor(obj);
Andreas Gampe0c183382017-07-13 22:26:24 -07001905 verify_no_from_space_refs_visitor(obj);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001906 }
1907 }
1908 }
1909 // TODO: LOS. But only refs in LOS are classes.
1910}
1911
1912// The following visitors are used to assert the to-space invariant.
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001913class ConcurrentCopying::AssertToSpaceInvariantFieldVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001914 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001915 explicit AssertToSpaceInvariantFieldVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001916 : collector_(collector) {}
1917
Mathieu Chartier31e88222016-10-14 18:43:19 -07001918 void operator()(ObjPtr<mirror::Object> obj,
1919 MemberOffset offset,
1920 bool is_static ATTRIBUTE_UNUSED) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001921 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001922 mirror::Object* ref =
1923 obj->GetFieldObject<mirror::Object, kDefaultVerifyFlags, kWithoutReadBarrier>(offset);
Lokesh Gidra519c1c72018-11-09 17:10:47 -08001924 collector_->AssertToSpaceInvariant(obj.Ptr(), offset, ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001925 }
Mathieu Chartier31e88222016-10-14 18:43:19 -07001926 void operator()(ObjPtr<mirror::Class> klass, ObjPtr<mirror::Reference> ref ATTRIBUTE_UNUSED) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001927 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001928 CHECK(klass->IsTypeOfReferenceClass());
1929 }
1930
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001931 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001932 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001933 if (!root->IsNull()) {
1934 VisitRoot(root);
1935 }
1936 }
1937
1938 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001939 REQUIRES_SHARED(Locks::mutator_lock_) {
Lokesh Gidra519c1c72018-11-09 17:10:47 -08001940 mirror::Object* ref = root->AsMirrorPtr();
1941 collector_->AssertToSpaceInvariant(/* obj */ nullptr, MemberOffset(0), ref);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001942 }
1943
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001944 private:
Mathieu Chartier97509952015-07-13 14:35:43 -07001945 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001946};
1947
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001948void ConcurrentCopying::RevokeThreadLocalMarkStacks(bool disable_weak_ref_access,
1949 Closure* checkpoint_callback) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001950 Thread* self = Thread::Current();
1951 RevokeThreadLocalMarkStackCheckpoint check_point(this, disable_weak_ref_access);
1952 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1953 gc_barrier_->Init(self, 0);
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001954 size_t barrier_count = thread_list->RunCheckpoint(&check_point, checkpoint_callback);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001955 // If there are no threads to wait which implys that all the checkpoint functions are finished,
1956 // then no need to release the mutator lock.
1957 if (barrier_count == 0) {
1958 return;
1959 }
1960 Locks::mutator_lock_->SharedUnlock(self);
1961 {
1962 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
1963 gc_barrier_->Increment(self, barrier_count);
1964 }
1965 Locks::mutator_lock_->SharedLock(self);
1966}
1967
1968void ConcurrentCopying::RevokeThreadLocalMarkStack(Thread* thread) {
1969 Thread* self = Thread::Current();
1970 CHECK_EQ(self, thread);
1971 accounting::AtomicStack<mirror::Object>* tl_mark_stack = thread->GetThreadLocalMarkStack();
1972 if (tl_mark_stack != nullptr) {
1973 CHECK(is_marking_);
1974 MutexLock mu(self, mark_stack_lock_);
1975 revoked_mark_stacks_.push_back(tl_mark_stack);
1976 thread->SetThreadLocalMarkStack(nullptr);
1977 }
1978}
1979
1980void ConcurrentCopying::ProcessMarkStack() {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001981 if (kVerboseMode) {
1982 LOG(INFO) << "ProcessMarkStack. ";
1983 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001984 bool empty_prev = false;
1985 while (true) {
1986 bool empty = ProcessMarkStackOnce();
1987 if (empty_prev && empty) {
1988 // Saw empty mark stack for a second time, done.
1989 break;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001990 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001991 empty_prev = empty;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001992 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001993}
1994
1995bool ConcurrentCopying::ProcessMarkStackOnce() {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08001996 DCHECK(thread_running_gc_ != nullptr);
1997 Thread* const self = Thread::Current();
1998 DCHECK(self == thread_running_gc_);
1999 DCHECK(thread_running_gc_->GetThreadLocalMarkStack() == nullptr);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002000 size_t count = 0;
Orion Hodson88591fe2018-03-06 13:35:43 +00002001 MarkStackMode mark_stack_mode = mark_stack_mode_.load(std::memory_order_relaxed);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002002 if (mark_stack_mode == kMarkStackModeThreadLocal) {
2003 // Process the thread-local mark stacks and the GC mark stack.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07002004 count += ProcessThreadLocalMarkStacks(/* disable_weak_ref_access= */ false,
Lokesh Gidra2a9824c2018-11-07 15:57:17 -08002005 /* checkpoint_callback= */ nullptr,
2006 [this] (mirror::Object* ref)
2007 REQUIRES_SHARED(Locks::mutator_lock_) {
2008 ProcessMarkStackRef(ref);
2009 });
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002010 while (!gc_mark_stack_->IsEmpty()) {
2011 mirror::Object* to_ref = gc_mark_stack_->PopBack();
2012 ProcessMarkStackRef(to_ref);
2013 ++count;
2014 }
2015 gc_mark_stack_->Reset();
2016 } else if (mark_stack_mode == kMarkStackModeShared) {
Hiroshi Yamauchi30493242016-11-03 13:06:52 -07002017 // Do an empty checkpoint to avoid a race with a mutator preempted in the middle of a read
2018 // barrier but before pushing onto the mark stack. b/32508093. Note the weak ref access is
2019 // disabled at this point.
2020 IssueEmptyCheckpoint();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002021 // Process the shared GC mark stack with a lock.
2022 {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002023 MutexLock mu(thread_running_gc_, mark_stack_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002024 CHECK(revoked_mark_stacks_.empty());
2025 }
2026 while (true) {
2027 std::vector<mirror::Object*> refs;
2028 {
2029 // Copy refs with lock. Note the number of refs should be small.
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002030 MutexLock mu(thread_running_gc_, mark_stack_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002031 if (gc_mark_stack_->IsEmpty()) {
2032 break;
2033 }
2034 for (StackReference<mirror::Object>* p = gc_mark_stack_->Begin();
2035 p != gc_mark_stack_->End(); ++p) {
2036 refs.push_back(p->AsMirrorPtr());
2037 }
2038 gc_mark_stack_->Reset();
2039 }
2040 for (mirror::Object* ref : refs) {
2041 ProcessMarkStackRef(ref);
2042 ++count;
2043 }
2044 }
2045 } else {
2046 CHECK_EQ(static_cast<uint32_t>(mark_stack_mode),
2047 static_cast<uint32_t>(kMarkStackModeGcExclusive));
2048 {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002049 MutexLock mu(thread_running_gc_, mark_stack_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002050 CHECK(revoked_mark_stacks_.empty());
2051 }
2052 // Process the GC mark stack in the exclusive mode. No need to take the lock.
2053 while (!gc_mark_stack_->IsEmpty()) {
2054 mirror::Object* to_ref = gc_mark_stack_->PopBack();
2055 ProcessMarkStackRef(to_ref);
2056 ++count;
2057 }
2058 gc_mark_stack_->Reset();
2059 }
2060
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002061 // Return true if the stack was empty.
2062 return count == 0;
2063}
2064
Lokesh Gidra2a9824c2018-11-07 15:57:17 -08002065template <typename Processor>
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07002066size_t ConcurrentCopying::ProcessThreadLocalMarkStacks(bool disable_weak_ref_access,
Lokesh Gidra2a9824c2018-11-07 15:57:17 -08002067 Closure* checkpoint_callback,
2068 const Processor& processor) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002069 // Run a checkpoint to collect all thread local mark stacks and iterate over them all.
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07002070 RevokeThreadLocalMarkStacks(disable_weak_ref_access, checkpoint_callback);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002071 size_t count = 0;
2072 std::vector<accounting::AtomicStack<mirror::Object>*> mark_stacks;
2073 {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002074 MutexLock mu(thread_running_gc_, mark_stack_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002075 // Make a copy of the mark stack vector.
2076 mark_stacks = revoked_mark_stacks_;
2077 revoked_mark_stacks_.clear();
2078 }
2079 for (accounting::AtomicStack<mirror::Object>* mark_stack : mark_stacks) {
2080 for (StackReference<mirror::Object>* p = mark_stack->Begin(); p != mark_stack->End(); ++p) {
2081 mirror::Object* to_ref = p->AsMirrorPtr();
Lokesh Gidra2a9824c2018-11-07 15:57:17 -08002082 processor(to_ref);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002083 ++count;
2084 }
2085 {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002086 MutexLock mu(thread_running_gc_, mark_stack_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002087 if (pooled_mark_stacks_.size() >= kMarkStackPoolSize) {
2088 // The pool has enough. Delete it.
2089 delete mark_stack;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002090 } else {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002091 // Otherwise, put it into the pool for later reuse.
2092 mark_stack->Reset();
2093 pooled_mark_stacks_.push_back(mark_stack);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002094 }
2095 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002096 }
2097 return count;
2098}
2099
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002100inline void ConcurrentCopying::ProcessMarkStackRef(mirror::Object* to_ref) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002101 DCHECK(!region_space_->IsInFromSpace(to_ref));
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002102 space::RegionSpace::RegionType rtype = region_space_->GetRegionType(to_ref);
Roland Levillain5fcf1ea2018-10-30 11:58:08 +00002103 if (kUseBakerReadBarrier) {
2104 DCHECK(to_ref->GetReadBarrierState() == ReadBarrier::GrayState())
2105 << " to_ref=" << to_ref
2106 << " rb_state=" << to_ref->GetReadBarrierState()
2107 << " is_marked=" << IsMarked(to_ref)
2108 << " type=" << to_ref->PrettyTypeOf()
2109 << " young_gen=" << std::boolalpha << young_gen_ << std::noboolalpha
2110 << " space=" << heap_->DumpSpaceNameFromAddress(to_ref)
Roland Levillain0e155592018-11-05 18:31:49 +00002111 << " region_type=" << rtype
2112 // TODO: Temporary; remove this when this is no longer needed (b/116087961).
2113 << " runtime->sentinel=" << Runtime::Current()->GetSentinel().Read<kWithoutReadBarrier>();
Lokesh Gidra420522a2018-10-26 17:31:27 -07002114 }
Mathieu Chartierc381c362016-08-23 13:27:53 -07002115 bool add_to_live_bytes = false;
Roland Levillain4e751132018-01-15 11:52:58 +00002116 // Invariant: There should be no object from a newly-allocated
2117 // region (either large or non-large) on the mark stack.
2118 DCHECK(!region_space_->IsInNewlyAllocatedRegion(to_ref)) << to_ref;
Lokesh Gidra519c1c72018-11-09 17:10:47 -08002119 bool perform_scan = false;
2120 switch (rtype) {
2121 case space::RegionSpace::RegionType::kRegionTypeUnevacFromSpace:
2122 // Mark the bitmap only in the GC thread here so that we don't need a CAS.
2123 if (!kUseBakerReadBarrier || !region_space_bitmap_->Set(to_ref)) {
2124 // It may be already marked if we accidentally pushed the same object twice due to the racy
2125 // bitmap read in MarkUnevacFromSpaceRegion.
2126 if (kEnableGenerationalConcurrentCopyingCollection && young_gen_) {
2127 CHECK(region_space_->IsLargeObject(to_ref));
2128 region_space_->ZeroLiveBytesForLargeObject(to_ref);
2129 }
2130 perform_scan = true;
2131 // Only add to the live bytes if the object was not already marked and we are not the young
2132 // GC.
Lokesh Gidra2a9824c2018-11-07 15:57:17 -08002133 // Why add live bytes even after 2-phase GC?
2134 // We need to ensure that if there is a unevac region with any live
2135 // objects, then its live_bytes must be non-zero. Otherwise,
2136 // ClearFromSpace() will clear the region. Considering, that we may skip
2137 // live objects during marking phase of 2-phase GC, we have to take care
2138 // of such objects here.
Lokesh Gidra519c1c72018-11-09 17:10:47 -08002139 add_to_live_bytes = true;
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002140 }
Lokesh Gidra519c1c72018-11-09 17:10:47 -08002141 break;
2142 case space::RegionSpace::RegionType::kRegionTypeToSpace:
2143 if (kEnableGenerationalConcurrentCopyingCollection) {
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002144 // Copied to to-space, set the bit so that the next GC can scan objects.
2145 region_space_bitmap_->Set(to_ref);
2146 }
Lokesh Gidra519c1c72018-11-09 17:10:47 -08002147 perform_scan = true;
2148 break;
2149 default:
2150 DCHECK(!region_space_->HasAddress(to_ref)) << to_ref;
2151 DCHECK(!immune_spaces_.ContainsObject(to_ref));
2152 // Non-moving or large-object space.
2153 if (kUseBakerReadBarrier) {
2154 accounting::ContinuousSpaceBitmap* mark_bitmap =
2155 heap_->GetNonMovingSpace()->GetMarkBitmap();
2156 const bool is_los = !mark_bitmap->HasAddress(to_ref);
2157 if (is_los) {
2158 if (!IsAligned<kPageSize>(to_ref)) {
2159 // Ref is a large object that is not aligned, it must be heap
2160 // corruption. Remove memory protection and dump data before
2161 // AtomicSetReadBarrierState since it will fault if the address is not
2162 // valid.
2163 region_space_->Unprotect();
2164 heap_->GetVerification()->LogHeapCorruption(/* obj */ nullptr,
2165 MemberOffset(0),
2166 to_ref,
2167 /* fatal */ true);
2168 }
2169 DCHECK(heap_->GetLargeObjectsSpace())
2170 << "ref=" << to_ref
2171 << " doesn't belong to non-moving space and large object space doesn't exist";
2172 accounting::LargeObjectBitmap* los_bitmap =
2173 heap_->GetLargeObjectsSpace()->GetMarkBitmap();
2174 DCHECK(los_bitmap->HasAddress(to_ref));
2175 // Only the GC thread could be setting the LOS bit map hence doesn't
2176 // need to be atomically done.
2177 perform_scan = !los_bitmap->Set(to_ref);
2178 } else {
2179 // Only the GC thread could be setting the non-moving space bit map
2180 // hence doesn't need to be atomically done.
2181 perform_scan = !mark_bitmap->Set(to_ref);
2182 }
2183 } else {
2184 perform_scan = true;
2185 }
2186 }
2187 if (perform_scan) {
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002188 if (kEnableGenerationalConcurrentCopyingCollection && young_gen_) {
2189 Scan<true>(to_ref);
2190 } else {
2191 Scan<false>(to_ref);
2192 }
Mathieu Chartierc381c362016-08-23 13:27:53 -07002193 }
Roland Levillain5fcf1ea2018-10-30 11:58:08 +00002194 if (kUseBakerReadBarrier) {
2195 DCHECK(to_ref->GetReadBarrierState() == ReadBarrier::GrayState())
2196 << " to_ref=" << to_ref
2197 << " rb_state=" << to_ref->GetReadBarrierState()
2198 << " is_marked=" << IsMarked(to_ref)
2199 << " type=" << to_ref->PrettyTypeOf()
2200 << " young_gen=" << std::boolalpha << young_gen_ << std::noboolalpha
2201 << " space=" << heap_->DumpSpaceNameFromAddress(to_ref)
Roland Levillain0e155592018-11-05 18:31:49 +00002202 << " region_type=" << rtype
2203 // TODO: Temporary; remove this when this is no longer needed (b/116087961).
2204 << " runtime->sentinel=" << Runtime::Current()->GetSentinel().Read<kWithoutReadBarrier>();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002205 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002206#ifdef USE_BAKER_OR_BROOKS_READ_BARRIER
Hiroshi Yamauchi39c12d42016-12-06 16:46:37 -08002207 mirror::Object* referent = nullptr;
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002208 if (UNLIKELY((to_ref->GetClass<kVerifyNone, kWithoutReadBarrier>()->IsTypeOfReferenceClass() &&
Hiroshi Yamauchi39c12d42016-12-06 16:46:37 -08002209 (referent = to_ref->AsReference()->GetReferent<kWithoutReadBarrier>()) != nullptr &&
2210 !IsInToSpace(referent)))) {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08002211 // Leave this reference gray in the queue so that GetReferent() will trigger a read barrier. We
Roland Levillain14e5a292018-06-28 12:00:56 +01002212 // will change it to non-gray later in ReferenceQueue::DisableReadBarrierForReference.
Roland Levillain2ae376f2018-01-30 11:35:11 +00002213 DCHECK(to_ref->AsReference()->GetPendingNext() != nullptr)
2214 << "Left unenqueued ref gray " << to_ref;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002215 } else {
Roland Levillain14e5a292018-06-28 12:00:56 +01002216 // We may occasionally leave a reference non-gray in the queue if its referent happens to be
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08002217 // concurrently marked after the Scan() call above has enqueued the Reference, in which case the
Roland Levillain14e5a292018-06-28 12:00:56 +01002218 // above IsInToSpace() evaluates to true and we change the color from gray to non-gray here in
2219 // this else block.
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002220 if (kUseBakerReadBarrier) {
Mathieu Chartier42c2e502018-06-19 12:30:56 -07002221 bool success = to_ref->AtomicSetReadBarrierState<std::memory_order_release>(
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002222 ReadBarrier::GrayState(),
Roland Levillain14e5a292018-06-28 12:00:56 +01002223 ReadBarrier::NonGrayState());
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08002224 DCHECK(success) << "Must succeed as we won the race.";
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002225 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002226 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002227#else
2228 DCHECK(!kUseBakerReadBarrier);
2229#endif
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08002230
Mathieu Chartierc381c362016-08-23 13:27:53 -07002231 if (add_to_live_bytes) {
Roland Levillain2ae376f2018-01-30 11:35:11 +00002232 // Add to the live bytes per unevacuated from-space. Note this code is always run by the
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08002233 // GC-running thread (no synchronization required).
2234 DCHECK(region_space_bitmap_->Test(to_ref));
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07002235 size_t obj_size = to_ref->SizeOf<kDefaultVerifyFlags>();
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08002236 size_t alloc_size = RoundUp(obj_size, space::RegionSpace::kAlignment);
2237 region_space_->AddLiveBytes(to_ref, alloc_size);
2238 }
Andreas Gampee3ce7872017-02-22 13:36:21 -08002239 if (ReadBarrier::kEnableToSpaceInvariantChecks) {
Andreas Gampe0c183382017-07-13 22:26:24 -07002240 CHECK(to_ref != nullptr);
2241 space::RegionSpace* region_space = RegionSpace();
2242 CHECK(!region_space->IsInFromSpace(to_ref)) << "Scanning object " << to_ref << " in from space";
2243 AssertToSpaceInvariant(nullptr, MemberOffset(0), to_ref);
2244 AssertToSpaceInvariantFieldVisitor visitor(this);
Andreas Gampe98ea9d92018-10-19 14:06:15 -07002245 to_ref->VisitReferences</*kVisitNativeRoots=*/true, kDefaultVerifyFlags, kWithoutReadBarrier>(
Andreas Gampe0c183382017-07-13 22:26:24 -07002246 visitor,
2247 visitor);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002248 }
2249}
2250
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07002251class ConcurrentCopying::DisableWeakRefAccessCallback : public Closure {
2252 public:
2253 explicit DisableWeakRefAccessCallback(ConcurrentCopying* concurrent_copying)
2254 : concurrent_copying_(concurrent_copying) {
2255 }
2256
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002257 void Run(Thread* self ATTRIBUTE_UNUSED) override REQUIRES(Locks::thread_list_lock_) {
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07002258 // This needs to run under the thread_list_lock_ critical section in ThreadList::RunCheckpoint()
2259 // to avoid a deadlock b/31500969.
2260 CHECK(concurrent_copying_->weak_ref_access_enabled_);
2261 concurrent_copying_->weak_ref_access_enabled_ = false;
2262 }
2263
2264 private:
2265 ConcurrentCopying* const concurrent_copying_;
2266};
2267
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002268void ConcurrentCopying::SwitchToSharedMarkStackMode() {
2269 Thread* self = Thread::Current();
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002270 DCHECK(thread_running_gc_ != nullptr);
2271 DCHECK(self == thread_running_gc_);
2272 DCHECK(thread_running_gc_->GetThreadLocalMarkStack() == nullptr);
Orion Hodson88591fe2018-03-06 13:35:43 +00002273 MarkStackMode before_mark_stack_mode = mark_stack_mode_.load(std::memory_order_relaxed);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002274 CHECK_EQ(static_cast<uint32_t>(before_mark_stack_mode),
2275 static_cast<uint32_t>(kMarkStackModeThreadLocal));
Orion Hodson88591fe2018-03-06 13:35:43 +00002276 mark_stack_mode_.store(kMarkStackModeShared, std::memory_order_relaxed);
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07002277 DisableWeakRefAccessCallback dwrac(this);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002278 // Process the thread local mark stacks one last time after switching to the shared mark stack
2279 // mode and disable weak ref accesses.
Lokesh Gidra2a9824c2018-11-07 15:57:17 -08002280 ProcessThreadLocalMarkStacks(/* disable_weak_ref_access= */ true,
2281 &dwrac,
2282 [this] (mirror::Object* ref)
2283 REQUIRES_SHARED(Locks::mutator_lock_) {
2284 ProcessMarkStackRef(ref);
2285 });
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002286 if (kVerboseMode) {
2287 LOG(INFO) << "Switched to shared mark stack mode and disabled weak ref access";
2288 }
2289}
2290
2291void ConcurrentCopying::SwitchToGcExclusiveMarkStackMode() {
2292 Thread* self = Thread::Current();
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002293 DCHECK(thread_running_gc_ != nullptr);
2294 DCHECK(self == thread_running_gc_);
2295 DCHECK(thread_running_gc_->GetThreadLocalMarkStack() == nullptr);
Orion Hodson88591fe2018-03-06 13:35:43 +00002296 MarkStackMode before_mark_stack_mode = mark_stack_mode_.load(std::memory_order_relaxed);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002297 CHECK_EQ(static_cast<uint32_t>(before_mark_stack_mode),
2298 static_cast<uint32_t>(kMarkStackModeShared));
Orion Hodson88591fe2018-03-06 13:35:43 +00002299 mark_stack_mode_.store(kMarkStackModeGcExclusive, std::memory_order_relaxed);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002300 QuasiAtomic::ThreadFenceForConstructor();
2301 if (kVerboseMode) {
2302 LOG(INFO) << "Switched to GC exclusive mark stack mode";
2303 }
2304}
2305
2306void ConcurrentCopying::CheckEmptyMarkStack() {
2307 Thread* self = Thread::Current();
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002308 DCHECK(thread_running_gc_ != nullptr);
2309 DCHECK(self == thread_running_gc_);
2310 DCHECK(thread_running_gc_->GetThreadLocalMarkStack() == nullptr);
Orion Hodson88591fe2018-03-06 13:35:43 +00002311 MarkStackMode mark_stack_mode = mark_stack_mode_.load(std::memory_order_relaxed);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002312 if (mark_stack_mode == kMarkStackModeThreadLocal) {
2313 // Thread-local mark stack mode.
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07002314 RevokeThreadLocalMarkStacks(false, nullptr);
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002315 MutexLock mu(thread_running_gc_, mark_stack_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002316 if (!revoked_mark_stacks_.empty()) {
2317 for (accounting::AtomicStack<mirror::Object>* mark_stack : revoked_mark_stacks_) {
2318 while (!mark_stack->IsEmpty()) {
2319 mirror::Object* obj = mark_stack->PopBack();
2320 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002321 uint32_t rb_state = obj->GetReadBarrierState();
2322 LOG(INFO) << "On mark queue : " << obj << " " << obj->PrettyTypeOf() << " rb_state="
2323 << rb_state << " is_marked=" << IsMarked(obj);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002324 } else {
David Sehr709b0702016-10-13 09:12:37 -07002325 LOG(INFO) << "On mark queue : " << obj << " " << obj->PrettyTypeOf()
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002326 << " is_marked=" << IsMarked(obj);
2327 }
2328 }
2329 }
2330 LOG(FATAL) << "mark stack is not empty";
2331 }
2332 } else {
2333 // Shared, GC-exclusive, or off.
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002334 MutexLock mu(thread_running_gc_, mark_stack_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002335 CHECK(gc_mark_stack_->IsEmpty());
2336 CHECK(revoked_mark_stacks_.empty());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002337 }
2338}
2339
2340void ConcurrentCopying::SweepSystemWeaks(Thread* self) {
2341 TimingLogger::ScopedTiming split("SweepSystemWeaks", GetTimings());
2342 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier97509952015-07-13 14:35:43 -07002343 Runtime::Current()->SweepSystemWeaks(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002344}
2345
2346void ConcurrentCopying::Sweep(bool swap_bitmaps) {
Roland Levillainb1e1dc32018-07-10 19:19:31 +01002347 if (kEnableGenerationalConcurrentCopyingCollection && young_gen_) {
2348 // Only sweep objects on the live stack.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07002349 SweepArray(heap_->GetLiveStack(), /* swap_bitmaps= */ false);
Roland Levillainb1e1dc32018-07-10 19:19:31 +01002350 } else {
2351 {
2352 TimingLogger::ScopedTiming t("MarkStackAsLive", GetTimings());
2353 accounting::ObjectStack* live_stack = heap_->GetLiveStack();
2354 if (kEnableFromSpaceAccountingCheck) {
2355 // Ensure that nobody inserted items in the live stack after we swapped the stacks.
2356 CHECK_GE(live_stack_freeze_size_, live_stack->Size());
2357 }
2358 heap_->MarkAllocStackAsLive(live_stack);
2359 live_stack->Reset();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002360 }
Roland Levillainb1e1dc32018-07-10 19:19:31 +01002361 CheckEmptyMarkStack();
2362 TimingLogger::ScopedTiming split("Sweep", GetTimings());
2363 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
2364 if (space->IsContinuousMemMapAllocSpace()) {
2365 space::ContinuousMemMapAllocSpace* alloc_space = space->AsContinuousMemMapAllocSpace();
2366 if (space == region_space_ || immune_spaces_.ContainsSpace(space)) {
2367 continue;
2368 }
2369 TimingLogger::ScopedTiming split2(
2370 alloc_space->IsZygoteSpace() ? "SweepZygoteSpace" : "SweepAllocSpace", GetTimings());
2371 RecordFree(alloc_space->Sweep(swap_bitmaps));
2372 }
2373 }
2374 SweepLargeObjects(swap_bitmaps);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002375 }
Roland Levillainb1e1dc32018-07-10 19:19:31 +01002376}
2377
2378// Copied and adapted from MarkSweep::SweepArray.
2379void ConcurrentCopying::SweepArray(accounting::ObjectStack* allocations, bool swap_bitmaps) {
2380 // This method is only used when Generational CC collection is enabled.
2381 DCHECK(kEnableGenerationalConcurrentCopyingCollection);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002382 CheckEmptyMarkStack();
Roland Levillainb1e1dc32018-07-10 19:19:31 +01002383 TimingLogger::ScopedTiming t("SweepArray", GetTimings());
2384 Thread* self = Thread::Current();
2385 mirror::Object** chunk_free_buffer = reinterpret_cast<mirror::Object**>(
2386 sweep_array_free_buffer_mem_map_.BaseBegin());
2387 size_t chunk_free_pos = 0;
2388 ObjectBytePair freed;
2389 ObjectBytePair freed_los;
2390 // How many objects are left in the array, modified after each space is swept.
2391 StackReference<mirror::Object>* objects = allocations->Begin();
2392 size_t count = allocations->Size();
2393 // Start by sweeping the continuous spaces.
2394 for (space::ContinuousSpace* space : heap_->GetContinuousSpaces()) {
2395 if (!space->IsAllocSpace() ||
2396 space == region_space_ ||
2397 immune_spaces_.ContainsSpace(space) ||
2398 space->GetLiveBitmap() == nullptr) {
2399 continue;
2400 }
2401 space::AllocSpace* alloc_space = space->AsAllocSpace();
2402 accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
2403 accounting::ContinuousSpaceBitmap* mark_bitmap = space->GetMarkBitmap();
2404 if (swap_bitmaps) {
2405 std::swap(live_bitmap, mark_bitmap);
2406 }
2407 StackReference<mirror::Object>* out = objects;
2408 for (size_t i = 0; i < count; ++i) {
2409 mirror::Object* const obj = objects[i].AsMirrorPtr();
2410 if (kUseThreadLocalAllocationStack && obj == nullptr) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002411 continue;
2412 }
Roland Levillainb1e1dc32018-07-10 19:19:31 +01002413 if (space->HasAddress(obj)) {
2414 // This object is in the space, remove it from the array and add it to the sweep buffer
2415 // if needed.
2416 if (!mark_bitmap->Test(obj)) {
2417 if (chunk_free_pos >= kSweepArrayChunkFreeSize) {
2418 TimingLogger::ScopedTiming t2("FreeList", GetTimings());
2419 freed.objects += chunk_free_pos;
2420 freed.bytes += alloc_space->FreeList(self, chunk_free_pos, chunk_free_buffer);
2421 chunk_free_pos = 0;
2422 }
2423 chunk_free_buffer[chunk_free_pos++] = obj;
2424 }
2425 } else {
2426 (out++)->Assign(obj);
2427 }
2428 }
2429 if (chunk_free_pos > 0) {
2430 TimingLogger::ScopedTiming t2("FreeList", GetTimings());
2431 freed.objects += chunk_free_pos;
2432 freed.bytes += alloc_space->FreeList(self, chunk_free_pos, chunk_free_buffer);
2433 chunk_free_pos = 0;
2434 }
2435 // All of the references which space contained are no longer in the allocation stack, update
2436 // the count.
2437 count = out - objects;
2438 }
2439 // Handle the large object space.
2440 space::LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
2441 if (large_object_space != nullptr) {
2442 accounting::LargeObjectBitmap* large_live_objects = large_object_space->GetLiveBitmap();
2443 accounting::LargeObjectBitmap* large_mark_objects = large_object_space->GetMarkBitmap();
2444 if (swap_bitmaps) {
2445 std::swap(large_live_objects, large_mark_objects);
2446 }
2447 for (size_t i = 0; i < count; ++i) {
2448 mirror::Object* const obj = objects[i].AsMirrorPtr();
2449 // Handle large objects.
2450 if (kUseThreadLocalAllocationStack && obj == nullptr) {
2451 continue;
2452 }
2453 if (!large_mark_objects->Test(obj)) {
2454 ++freed_los.objects;
2455 freed_los.bytes += large_object_space->Free(self, obj);
2456 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002457 }
2458 }
Roland Levillainb1e1dc32018-07-10 19:19:31 +01002459 {
2460 TimingLogger::ScopedTiming t2("RecordFree", GetTimings());
2461 RecordFree(freed);
2462 RecordFreeLOS(freed_los);
2463 t2.NewTiming("ResetStack");
2464 allocations->Reset();
2465 }
2466 sweep_array_free_buffer_mem_map_.MadviseDontNeedAndZero();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002467}
2468
Mathieu Chartier962cd7a2016-08-16 12:15:59 -07002469void ConcurrentCopying::MarkZygoteLargeObjects() {
2470 TimingLogger::ScopedTiming split(__FUNCTION__, GetTimings());
2471 Thread* const self = Thread::Current();
2472 WriterMutexLock rmu(self, *Locks::heap_bitmap_lock_);
2473 space::LargeObjectSpace* const los = heap_->GetLargeObjectsSpace();
Nicolas Geoffray7acddd82017-05-03 15:04:55 +01002474 if (los != nullptr) {
2475 // Pick the current live bitmap (mark bitmap if swapped).
2476 accounting::LargeObjectBitmap* const live_bitmap = los->GetLiveBitmap();
2477 accounting::LargeObjectBitmap* const mark_bitmap = los->GetMarkBitmap();
2478 // Walk through all of the objects and explicitly mark the zygote ones so they don't get swept.
2479 std::pair<uint8_t*, uint8_t*> range = los->GetBeginEndAtomic();
2480 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(range.first),
2481 reinterpret_cast<uintptr_t>(range.second),
2482 [mark_bitmap, los, self](mirror::Object* obj)
2483 REQUIRES(Locks::heap_bitmap_lock_)
2484 REQUIRES_SHARED(Locks::mutator_lock_) {
2485 if (los->IsZygoteLargeObject(self, obj)) {
2486 mark_bitmap->Set(obj);
2487 }
2488 });
2489 }
Mathieu Chartier962cd7a2016-08-16 12:15:59 -07002490}
2491
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002492void ConcurrentCopying::SweepLargeObjects(bool swap_bitmaps) {
2493 TimingLogger::ScopedTiming split("SweepLargeObjects", GetTimings());
Nicolas Geoffray7acddd82017-05-03 15:04:55 +01002494 if (heap_->GetLargeObjectsSpace() != nullptr) {
2495 RecordFreeLOS(heap_->GetLargeObjectsSpace()->Sweep(swap_bitmaps));
2496 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002497}
2498
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002499void ConcurrentCopying::ReclaimPhase() {
2500 TimingLogger::ScopedTiming split("ReclaimPhase", GetTimings());
2501 if (kVerboseMode) {
2502 LOG(INFO) << "GC ReclaimPhase";
2503 }
2504 Thread* self = Thread::Current();
2505
2506 {
2507 // Double-check that the mark stack is empty.
2508 // Note: need to set this after VerifyNoFromSpaceRef().
2509 is_asserting_to_space_invariant_ = false;
2510 QuasiAtomic::ThreadFenceForConstructor();
2511 if (kVerboseMode) {
2512 LOG(INFO) << "Issue an empty check point. ";
2513 }
2514 IssueEmptyCheckpoint();
2515 // Disable the check.
Orion Hodson88591fe2018-03-06 13:35:43 +00002516 is_mark_stack_push_disallowed_.store(0, std::memory_order_seq_cst);
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002517 if (kUseBakerReadBarrier) {
Orion Hodson88591fe2018-03-06 13:35:43 +00002518 updated_all_immune_objects_.store(false, std::memory_order_seq_cst);
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002519 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002520 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002521 }
2522
2523 {
2524 // Record freed objects.
2525 TimingLogger::ScopedTiming split2("RecordFree", GetTimings());
2526 // Don't include thread-locals that are in the to-space.
Mathieu Chartier371b0472017-02-27 16:37:21 -08002527 const uint64_t from_bytes = region_space_->GetBytesAllocatedInFromSpace();
2528 const uint64_t from_objects = region_space_->GetObjectsAllocatedInFromSpace();
2529 const uint64_t unevac_from_bytes = region_space_->GetBytesAllocatedInUnevacFromSpace();
2530 const uint64_t unevac_from_objects = region_space_->GetObjectsAllocatedInUnevacFromSpace();
Hans Boehmfb8b4e22018-09-05 16:45:42 -07002531 uint64_t to_bytes = bytes_moved_.load(std::memory_order_relaxed) + bytes_moved_gc_thread_;
Orion Hodson88591fe2018-03-06 13:35:43 +00002532 cumulative_bytes_moved_.fetch_add(to_bytes, std::memory_order_relaxed);
Hans Boehmfb8b4e22018-09-05 16:45:42 -07002533 uint64_t to_objects = objects_moved_.load(std::memory_order_relaxed) + objects_moved_gc_thread_;
Orion Hodson88591fe2018-03-06 13:35:43 +00002534 cumulative_objects_moved_.fetch_add(to_objects, std::memory_order_relaxed);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002535 if (kEnableFromSpaceAccountingCheck) {
2536 CHECK_EQ(from_space_num_objects_at_first_pause_, from_objects + unevac_from_objects);
2537 CHECK_EQ(from_space_num_bytes_at_first_pause_, from_bytes + unevac_from_bytes);
2538 }
2539 CHECK_LE(to_objects, from_objects);
2540 CHECK_LE(to_bytes, from_bytes);
Albert Mingkun Yange260e542018-11-05 13:45:59 +00002541 if (from_bytes > 0) {
2542 copied_live_bytes_ratio_sum_ += static_cast<float>(to_bytes) / from_bytes;
2543 gc_count_++;
2544 }
2545
Roland Levillain8f7ea9a2018-01-26 17:27:59 +00002546 // Cleared bytes and objects, populated by the call to RegionSpace::ClearFromSpace below.
Mathieu Chartier371b0472017-02-27 16:37:21 -08002547 uint64_t cleared_bytes;
2548 uint64_t cleared_objects;
2549 {
2550 TimingLogger::ScopedTiming split4("ClearFromSpace", GetTimings());
Lokesh Gidra2a9824c2018-11-07 15:57:17 -08002551 region_space_->ClearFromSpace(&cleared_bytes, &cleared_objects, /*clear_bitmap*/ !young_gen_);
Roland Levillain8f7ea9a2018-01-26 17:27:59 +00002552 // `cleared_bytes` and `cleared_objects` may be greater than the from space equivalents since
2553 // RegionSpace::ClearFromSpace may clear empty unevac regions.
Mathieu Chartier371b0472017-02-27 16:37:21 -08002554 CHECK_GE(cleared_bytes, from_bytes);
2555 CHECK_GE(cleared_objects, from_objects);
2556 }
2557 int64_t freed_bytes = cleared_bytes - to_bytes;
2558 int64_t freed_objects = cleared_objects - to_objects;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002559 if (kVerboseMode) {
2560 LOG(INFO) << "RecordFree:"
2561 << " from_bytes=" << from_bytes << " from_objects=" << from_objects
Roland Levillain2ae376f2018-01-30 11:35:11 +00002562 << " unevac_from_bytes=" << unevac_from_bytes
2563 << " unevac_from_objects=" << unevac_from_objects
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002564 << " to_bytes=" << to_bytes << " to_objects=" << to_objects
2565 << " freed_bytes=" << freed_bytes << " freed_objects=" << freed_objects
2566 << " from_space size=" << region_space_->FromSpaceSize()
2567 << " unevac_from_space size=" << region_space_->UnevacFromSpaceSize()
2568 << " to_space size=" << region_space_->ToSpaceSize();
Roland Levillain2ae376f2018-01-30 11:35:11 +00002569 LOG(INFO) << "(before) num_bytes_allocated="
Hans Boehmfb8b4e22018-09-05 16:45:42 -07002570 << heap_->num_bytes_allocated_.load();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002571 }
2572 RecordFree(ObjectBytePair(freed_objects, freed_bytes));
2573 if (kVerboseMode) {
Roland Levillain2ae376f2018-01-30 11:35:11 +00002574 LOG(INFO) << "(after) num_bytes_allocated="
Hans Boehmfb8b4e22018-09-05 16:45:42 -07002575 << heap_->num_bytes_allocated_.load();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002576 }
Albert Mingkun Yang66937422018-11-30 17:52:01 +00002577
2578 float reclaimed_bytes_ratio = static_cast<float>(freed_bytes) / num_bytes_allocated_before_gc_;
2579 reclaimed_bytes_ratio_sum_ += reclaimed_bytes_ratio;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002580 }
2581
2582 {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002583 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Andreas Gampe98ea9d92018-10-19 14:06:15 -07002584 Sweep(/* swap_bitmaps= */ false);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002585 SwapBitmaps();
2586 heap_->UnBindBitmaps();
2587
Mathieu Chartier7ec38dc2016-10-07 15:24:46 -07002588 // 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 -07002589 DCHECK(region_space_bitmap_ != nullptr);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002590 region_space_bitmap_ = nullptr;
2591 }
2592
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002593 CheckEmptyMarkStack();
2594
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002595 if (kVerboseMode) {
2596 LOG(INFO) << "GC end of ReclaimPhase";
2597 }
2598}
2599
Roland Levillain001eff92018-01-24 14:24:33 +00002600std::string ConcurrentCopying::DumpReferenceInfo(mirror::Object* ref,
2601 const char* ref_name,
Andreas Gampebc802de2018-06-20 17:24:11 -07002602 const char* indent) {
Roland Levillain001eff92018-01-24 14:24:33 +00002603 std::ostringstream oss;
2604 oss << indent << heap_->GetVerification()->DumpObjectInfo(ref, ref_name) << '\n';
2605 if (ref != nullptr) {
2606 if (kUseBakerReadBarrier) {
2607 oss << indent << ref_name << "->GetMarkBit()=" << ref->GetMarkBit() << '\n';
2608 oss << indent << ref_name << "->GetReadBarrierState()=" << ref->GetReadBarrierState() << '\n';
2609 }
2610 }
2611 if (region_space_->HasAddress(ref)) {
2612 oss << indent << "Region containing " << ref_name << ":" << '\n';
2613 region_space_->DumpRegionForObject(oss, ref);
2614 if (region_space_bitmap_ != nullptr) {
2615 oss << indent << "region_space_bitmap_->Test(" << ref_name << ")="
2616 << std::boolalpha << region_space_bitmap_->Test(ref) << std::noboolalpha;
2617 }
2618 }
2619 return oss.str();
2620}
2621
2622std::string ConcurrentCopying::DumpHeapReference(mirror::Object* obj,
2623 MemberOffset offset,
2624 mirror::Object* ref) {
2625 std::ostringstream oss;
Andreas Gampebc802de2018-06-20 17:24:11 -07002626 constexpr const char* kIndent = " ";
2627 oss << kIndent << "Invalid reference: ref=" << ref
Roland Levillain001eff92018-01-24 14:24:33 +00002628 << " referenced from: object=" << obj << " offset= " << offset << '\n';
2629 // Information about `obj`.
Andreas Gampebc802de2018-06-20 17:24:11 -07002630 oss << DumpReferenceInfo(obj, "obj", kIndent) << '\n';
Roland Levillain001eff92018-01-24 14:24:33 +00002631 // Information about `ref`.
Andreas Gampebc802de2018-06-20 17:24:11 -07002632 oss << DumpReferenceInfo(ref, "ref", kIndent);
Roland Levillain001eff92018-01-24 14:24:33 +00002633 return oss.str();
2634}
2635
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07002636void ConcurrentCopying::AssertToSpaceInvariant(mirror::Object* obj,
2637 MemberOffset offset,
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002638 mirror::Object* ref) {
Roland Levillain001eff92018-01-24 14:24:33 +00002639 CHECK_EQ(heap_->collector_type_, kCollectorTypeCC) << static_cast<size_t>(heap_->collector_type_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002640 if (is_asserting_to_space_invariant_) {
Lokesh Gidra519c1c72018-11-09 17:10:47 -08002641 if (ref == nullptr) {
2642 // OK.
2643 return;
2644 } else if (region_space_->HasAddress(ref)) {
Roland Levillain001eff92018-01-24 14:24:33 +00002645 // Check to-space invariant in region space (moving space).
2646 using RegionType = space::RegionSpace::RegionType;
Roland Levillain2dd2e1e2018-02-28 16:24:51 +00002647 space::RegionSpace::RegionType type = region_space_->GetRegionTypeUnsafe(ref);
Roland Levillain001eff92018-01-24 14:24:33 +00002648 if (type == RegionType::kRegionTypeToSpace) {
2649 // OK.
2650 return;
2651 } else if (type == RegionType::kRegionTypeUnevacFromSpace) {
2652 if (!IsMarkedInUnevacFromSpace(ref)) {
2653 LOG(FATAL_WITHOUT_ABORT) << "Found unmarked reference in unevac from-space:";
Roland Levillainca3dded2018-08-10 15:35:17 +01002654 // Remove memory protection from the region space and log debugging information.
2655 region_space_->Unprotect();
Roland Levillain001eff92018-01-24 14:24:33 +00002656 LOG(FATAL_WITHOUT_ABORT) << DumpHeapReference(obj, offset, ref);
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002657 Thread::Current()->DumpJavaStack(LOG_STREAM(FATAL_WITHOUT_ABORT));
Roland Levillain001eff92018-01-24 14:24:33 +00002658 }
2659 CHECK(IsMarkedInUnevacFromSpace(ref)) << ref;
2660 } else {
2661 // Not OK: either a from-space ref or a reference in an unused region.
Roland Levillain001eff92018-01-24 14:24:33 +00002662 if (type == RegionType::kRegionTypeFromSpace) {
2663 LOG(FATAL_WITHOUT_ABORT) << "Found from-space reference:";
2664 } else {
2665 LOG(FATAL_WITHOUT_ABORT) << "Found reference in region with type " << type << ":";
2666 }
Roland Levillainca3dded2018-08-10 15:35:17 +01002667 // Remove memory protection from the region space and log debugging information.
2668 region_space_->Unprotect();
Roland Levillain001eff92018-01-24 14:24:33 +00002669 LOG(FATAL_WITHOUT_ABORT) << DumpHeapReference(obj, offset, ref);
2670 if (obj != nullptr) {
2671 LogFromSpaceRefHolder(obj, offset);
Roland Levillain57ce0542018-08-07 16:20:31 +01002672 LOG(FATAL_WITHOUT_ABORT) << "UNEVAC " << region_space_->IsInUnevacFromSpace(obj) << " "
2673 << obj << " " << obj->GetMarkBit();
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002674 if (region_space_->HasAddress(obj)) {
Roland Levillain57ce0542018-08-07 16:20:31 +01002675 region_space_->DumpRegionForObject(LOG_STREAM(FATAL_WITHOUT_ABORT), obj);
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002676 }
Roland Levillain57ce0542018-08-07 16:20:31 +01002677 LOG(FATAL_WITHOUT_ABORT) << "CARD " << static_cast<size_t>(
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002678 *Runtime::Current()->GetHeap()->GetCardTable()->CardFromAddr(
2679 reinterpret_cast<uint8_t*>(obj)));
Roland Levillain57ce0542018-08-07 16:20:31 +01002680 if (region_space_->HasAddress(obj)) {
2681 LOG(FATAL_WITHOUT_ABORT) << "BITMAP " << region_space_bitmap_->Test(obj);
2682 } else {
2683 accounting::ContinuousSpaceBitmap* mark_bitmap =
2684 heap_mark_bitmap_->GetContinuousSpaceBitmap(obj);
2685 if (mark_bitmap != nullptr) {
2686 LOG(FATAL_WITHOUT_ABORT) << "BITMAP " << mark_bitmap->Test(obj);
2687 } else {
2688 accounting::LargeObjectBitmap* los_bitmap =
2689 heap_mark_bitmap_->GetLargeObjectBitmap(obj);
2690 LOG(FATAL_WITHOUT_ABORT) << "BITMAP " << los_bitmap->Test(obj);
2691 }
2692 }
Roland Levillain001eff92018-01-24 14:24:33 +00002693 }
2694 ref->GetLockWord(false).Dump(LOG_STREAM(FATAL_WITHOUT_ABORT));
2695 LOG(FATAL_WITHOUT_ABORT) << "Non-free regions:";
2696 region_space_->DumpNonFreeRegions(LOG_STREAM(FATAL_WITHOUT_ABORT));
2697 PrintFileToLog("/proc/self/maps", LogSeverity::FATAL_WITHOUT_ABORT);
Andreas Gampe98ea9d92018-10-19 14:06:15 -07002698 MemMap::DumpMaps(LOG_STREAM(FATAL_WITHOUT_ABORT), /* terse= */ true);
Roland Levillain001eff92018-01-24 14:24:33 +00002699 LOG(FATAL) << "Invalid reference " << ref
2700 << " referenced from object " << obj << " at offset " << offset;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002701 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002702 } else {
Roland Levillain001eff92018-01-24 14:24:33 +00002703 // Check to-space invariant in non-moving space.
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002704 AssertToSpaceInvariantInNonMovingSpace(obj, ref);
2705 }
2706 }
2707}
2708
2709class RootPrinter {
2710 public:
2711 RootPrinter() { }
2712
2713 template <class MirrorType>
2714 ALWAYS_INLINE void VisitRootIfNonNull(mirror::CompressedReference<MirrorType>* root)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002715 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002716 if (!root->IsNull()) {
2717 VisitRoot(root);
2718 }
2719 }
2720
2721 template <class MirrorType>
2722 void VisitRoot(mirror::Object** root)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002723 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07002724 LOG(FATAL_WITHOUT_ABORT) << "root=" << root << " ref=" << *root;
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002725 }
2726
2727 template <class MirrorType>
2728 void VisitRoot(mirror::CompressedReference<MirrorType>* root)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002729 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07002730 LOG(FATAL_WITHOUT_ABORT) << "root=" << root << " ref=" << root->AsMirrorPtr();
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002731 }
2732};
2733
Roland Levillain001eff92018-01-24 14:24:33 +00002734std::string ConcurrentCopying::DumpGcRoot(mirror::Object* ref) {
2735 std::ostringstream oss;
Andreas Gampebc802de2018-06-20 17:24:11 -07002736 constexpr const char* kIndent = " ";
2737 oss << kIndent << "Invalid GC root: ref=" << ref << '\n';
Roland Levillain001eff92018-01-24 14:24:33 +00002738 // Information about `ref`.
Andreas Gampebc802de2018-06-20 17:24:11 -07002739 oss << DumpReferenceInfo(ref, "ref", kIndent);
Roland Levillain001eff92018-01-24 14:24:33 +00002740 return oss.str();
2741}
2742
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002743void ConcurrentCopying::AssertToSpaceInvariant(GcRootSource* gc_root_source,
2744 mirror::Object* ref) {
Roland Levillain001eff92018-01-24 14:24:33 +00002745 CHECK_EQ(heap_->collector_type_, kCollectorTypeCC) << static_cast<size_t>(heap_->collector_type_);
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002746 if (is_asserting_to_space_invariant_) {
Lokesh Gidra519c1c72018-11-09 17:10:47 -08002747 if (ref == nullptr) {
2748 // OK.
2749 return;
2750 } else if (region_space_->HasAddress(ref)) {
Roland Levillain001eff92018-01-24 14:24:33 +00002751 // Check to-space invariant in region space (moving space).
2752 using RegionType = space::RegionSpace::RegionType;
Roland Levillain2dd2e1e2018-02-28 16:24:51 +00002753 space::RegionSpace::RegionType type = region_space_->GetRegionTypeUnsafe(ref);
Roland Levillain001eff92018-01-24 14:24:33 +00002754 if (type == RegionType::kRegionTypeToSpace) {
2755 // OK.
2756 return;
2757 } else if (type == RegionType::kRegionTypeUnevacFromSpace) {
2758 if (!IsMarkedInUnevacFromSpace(ref)) {
2759 LOG(FATAL_WITHOUT_ABORT) << "Found unmarked reference in unevac from-space:";
Roland Levillainca3dded2018-08-10 15:35:17 +01002760 // Remove memory protection from the region space and log debugging information.
2761 region_space_->Unprotect();
Roland Levillain001eff92018-01-24 14:24:33 +00002762 LOG(FATAL_WITHOUT_ABORT) << DumpGcRoot(ref);
2763 }
2764 CHECK(IsMarkedInUnevacFromSpace(ref)) << ref;
2765 } else {
2766 // Not OK: either a from-space ref or a reference in an unused region.
Roland Levillain001eff92018-01-24 14:24:33 +00002767 if (type == RegionType::kRegionTypeFromSpace) {
2768 LOG(FATAL_WITHOUT_ABORT) << "Found from-space reference:";
2769 } else {
2770 LOG(FATAL_WITHOUT_ABORT) << "Found reference in region with type " << type << ":";
2771 }
Roland Levillainca3dded2018-08-10 15:35:17 +01002772 // Remove memory protection from the region space and log debugging information.
2773 region_space_->Unprotect();
Roland Levillain001eff92018-01-24 14:24:33 +00002774 LOG(FATAL_WITHOUT_ABORT) << DumpGcRoot(ref);
2775 if (gc_root_source == nullptr) {
2776 // No info.
2777 } else if (gc_root_source->HasArtField()) {
2778 ArtField* field = gc_root_source->GetArtField();
2779 LOG(FATAL_WITHOUT_ABORT) << "gc root in field " << field << " "
2780 << ArtField::PrettyField(field);
2781 RootPrinter root_printer;
2782 field->VisitRoots(root_printer);
2783 } else if (gc_root_source->HasArtMethod()) {
2784 ArtMethod* method = gc_root_source->GetArtMethod();
2785 LOG(FATAL_WITHOUT_ABORT) << "gc root in method " << method << " "
2786 << ArtMethod::PrettyMethod(method);
2787 RootPrinter root_printer;
2788 method->VisitRoots(root_printer, kRuntimePointerSize);
2789 }
2790 ref->GetLockWord(false).Dump(LOG_STREAM(FATAL_WITHOUT_ABORT));
2791 LOG(FATAL_WITHOUT_ABORT) << "Non-free regions:";
2792 region_space_->DumpNonFreeRegions(LOG_STREAM(FATAL_WITHOUT_ABORT));
2793 PrintFileToLog("/proc/self/maps", LogSeverity::FATAL_WITHOUT_ABORT);
Andreas Gampe98ea9d92018-10-19 14:06:15 -07002794 MemMap::DumpMaps(LOG_STREAM(FATAL_WITHOUT_ABORT), /* terse= */ true);
Roland Levillain001eff92018-01-24 14:24:33 +00002795 LOG(FATAL) << "Invalid reference " << ref;
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002796 }
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002797 } else {
Roland Levillain001eff92018-01-24 14:24:33 +00002798 // Check to-space invariant in non-moving space.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07002799 AssertToSpaceInvariantInNonMovingSpace(/* obj= */ nullptr, ref);
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002800 }
2801 }
2802}
2803
2804void ConcurrentCopying::LogFromSpaceRefHolder(mirror::Object* obj, MemberOffset offset) {
2805 if (kUseBakerReadBarrier) {
David Sehr709b0702016-10-13 09:12:37 -07002806 LOG(INFO) << "holder=" << obj << " " << obj->PrettyTypeOf()
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002807 << " holder rb_state=" << obj->GetReadBarrierState();
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002808 } else {
David Sehr709b0702016-10-13 09:12:37 -07002809 LOG(INFO) << "holder=" << obj << " " << obj->PrettyTypeOf();
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002810 }
2811 if (region_space_->IsInFromSpace(obj)) {
2812 LOG(INFO) << "holder is in the from-space.";
2813 } else if (region_space_->IsInToSpace(obj)) {
2814 LOG(INFO) << "holder is in the to-space.";
2815 } else if (region_space_->IsInUnevacFromSpace(obj)) {
2816 LOG(INFO) << "holder is in the unevac from-space.";
Mathieu Chartierc381c362016-08-23 13:27:53 -07002817 if (IsMarkedInUnevacFromSpace(obj)) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002818 LOG(INFO) << "holder is marked in the region space bitmap.";
2819 } else {
2820 LOG(INFO) << "holder is not marked in the region space bitmap.";
2821 }
2822 } else {
2823 // In a non-moving space.
Mathieu Chartier763a31e2015-11-16 16:05:55 -08002824 if (immune_spaces_.ContainsObject(obj)) {
2825 LOG(INFO) << "holder is in an immune image or the zygote space.";
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002826 } else {
Mathieu Chartier763a31e2015-11-16 16:05:55 -08002827 LOG(INFO) << "holder is in a non-immune, non-moving (or main) space.";
Lokesh Gidra519c1c72018-11-09 17:10:47 -08002828 accounting::ContinuousSpaceBitmap* mark_bitmap = heap_->GetNonMovingSpace()->GetMarkBitmap();
2829 accounting::LargeObjectBitmap* los_bitmap = nullptr;
2830 const bool is_los = !mark_bitmap->HasAddress(obj);
2831 if (is_los) {
2832 DCHECK(heap_->GetLargeObjectsSpace() && heap_->GetLargeObjectsSpace()->Contains(obj))
2833 << "obj=" << obj
2834 << " LOS bit map covers the entire lower 4GB address range";
2835 los_bitmap = heap_->GetLargeObjectsSpace()->GetMarkBitmap();
2836 }
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002837 if (!is_los && mark_bitmap->Test(obj)) {
Lokesh Gidra519c1c72018-11-09 17:10:47 -08002838 LOG(INFO) << "holder is marked in the non-moving space mark bit map.";
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002839 } else if (is_los && los_bitmap->Test(obj)) {
2840 LOG(INFO) << "holder is marked in the los bit map.";
2841 } else {
2842 // If ref is on the allocation stack, then it is considered
2843 // mark/alive (but not necessarily on the live stack.)
2844 if (IsOnAllocStack(obj)) {
2845 LOG(INFO) << "holder is on the alloc stack.";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002846 } else {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002847 LOG(INFO) << "holder is not marked or on the alloc stack.";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002848 }
2849 }
2850 }
2851 }
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002852 LOG(INFO) << "offset=" << offset.SizeValue();
2853}
2854
Lokesh Gidra519c1c72018-11-09 17:10:47 -08002855bool ConcurrentCopying::IsMarkedInNonMovingSpace(mirror::Object* from_ref) {
2856 DCHECK(!region_space_->HasAddress(from_ref)) << "ref=" << from_ref;
2857 DCHECK(!immune_spaces_.ContainsObject(from_ref)) << "ref=" << from_ref;
2858 if (kUseBakerReadBarrier && from_ref->GetReadBarrierStateAcquire() == ReadBarrier::GrayState()) {
2859 return true;
Lokesh Gidra2a9824c2018-11-07 15:57:17 -08002860 } else if (!kEnableGenerationalConcurrentCopyingCollection
Lokesh Gidra519c1c72018-11-09 17:10:47 -08002861 || done_scanning_.load(std::memory_order_acquire)) {
2862 // Read the comment in IsMarkedInUnevacFromSpace()
2863 accounting::ContinuousSpaceBitmap* mark_bitmap = heap_->GetNonMovingSpace()->GetMarkBitmap();
2864 accounting::LargeObjectBitmap* los_bitmap = nullptr;
2865 const bool is_los = !mark_bitmap->HasAddress(from_ref);
2866 if (is_los) {
2867 DCHECK(heap_->GetLargeObjectsSpace() && heap_->GetLargeObjectsSpace()->Contains(from_ref))
2868 << "ref=" << from_ref
2869 << " doesn't belong to non-moving space and large object space doesn't exist";
2870 los_bitmap = heap_->GetLargeObjectsSpace()->GetMarkBitmap();
2871 }
2872 if (is_los ? los_bitmap->Test(from_ref) : mark_bitmap->Test(from_ref)) {
2873 return true;
2874 }
2875 }
2876 return IsOnAllocStack(from_ref);
2877}
2878
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002879void ConcurrentCopying::AssertToSpaceInvariantInNonMovingSpace(mirror::Object* obj,
2880 mirror::Object* ref) {
Roland Levillainbe4b8fd2018-09-03 14:38:37 +01002881 CHECK(ref != nullptr);
Roland Levillain001eff92018-01-24 14:24:33 +00002882 CHECK(!region_space_->HasAddress(ref)) << "obj=" << obj << " ref=" << ref;
Roland Levillainef012222017-06-21 16:28:06 +01002883 // In a non-moving space. Check that the ref is marked.
Mathieu Chartier763a31e2015-11-16 16:05:55 -08002884 if (immune_spaces_.ContainsObject(ref)) {
Roland Levillain8def52a2018-09-05 15:31:19 +01002885 // Immune space case.
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002886 if (kUseBakerReadBarrier) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002887 // Immune object may not be gray if called from the GC.
2888 if (Thread::Current() == thread_running_gc_ && !gc_grays_immune_objects_) {
2889 return;
2890 }
Orion Hodson88591fe2018-03-06 13:35:43 +00002891 bool updated_all_immune_objects = updated_all_immune_objects_.load(std::memory_order_seq_cst);
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002892 CHECK(updated_all_immune_objects || ref->GetReadBarrierState() == ReadBarrier::GrayState())
2893 << "Unmarked immune space ref. obj=" << obj << " rb_state="
2894 << (obj != nullptr ? obj->GetReadBarrierState() : 0U)
2895 << " ref=" << ref << " ref rb_state=" << ref->GetReadBarrierState()
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002896 << " updated_all_immune_objects=" << updated_all_immune_objects;
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002897 }
2898 } else {
Roland Levillain8def52a2018-09-05 15:31:19 +01002899 // Non-moving space and large-object space (LOS) cases.
Roland Levillain8def52a2018-09-05 15:31:19 +01002900 // If `ref` is on the allocation stack, then it may not be
2901 // marked live, but considered marked/alive (but not
2902 // necessarily on the live stack).
Lokesh Gidra519c1c72018-11-09 17:10:47 -08002903 CHECK(IsMarkedInNonMovingSpace(ref))
Roland Levillain8def52a2018-09-05 15:31:19 +01002904 << "Unmarked ref that's not on the allocation stack."
2905 << " obj=" << obj
2906 << " ref=" << ref
2907 << " rb_state=" << ref->GetReadBarrierState()
Roland Levillain8def52a2018-09-05 15:31:19 +01002908 << " is_marking=" << std::boolalpha << is_marking_ << std::noboolalpha
2909 << " young_gen=" << std::boolalpha << young_gen_ << std::noboolalpha
2910 << " done_scanning="
2911 << std::boolalpha << done_scanning_.load(std::memory_order_acquire) << std::noboolalpha
2912 << " self=" << Thread::Current();
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002913 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002914}
2915
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002916// Used to scan ref fields of an object.
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002917template <bool kNoUnEvac>
Mathieu Chartiera07f5592016-06-16 11:44:28 -07002918class ConcurrentCopying::RefFieldsVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002919 public:
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002920 explicit RefFieldsVisitor(ConcurrentCopying* collector, Thread* const thread)
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002921 : collector_(collector), thread_(thread) {
2922 // Cannot have `kNoUnEvac` when Generational CC collection is disabled.
2923 DCHECK(kEnableGenerationalConcurrentCopyingCollection || !kNoUnEvac);
2924 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002925
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07002926 void operator()(mirror::Object* obj, MemberOffset offset, bool /* is_static */)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002927 const ALWAYS_INLINE REQUIRES_SHARED(Locks::mutator_lock_)
2928 REQUIRES_SHARED(Locks::heap_bitmap_lock_) {
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002929 collector_->Process<kNoUnEvac>(obj, offset);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002930 }
2931
Mathieu Chartier31e88222016-10-14 18:43:19 -07002932 void operator()(ObjPtr<mirror::Class> klass, ObjPtr<mirror::Reference> ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002933 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002934 CHECK(klass->IsTypeOfReferenceClass());
2935 collector_->DelayReferenceReferent(klass, ref);
2936 }
2937
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002938 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002939 ALWAYS_INLINE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002940 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002941 if (!root->IsNull()) {
2942 VisitRoot(root);
2943 }
2944 }
2945
2946 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002947 ALWAYS_INLINE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002948 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe98ea9d92018-10-19 14:06:15 -07002949 collector_->MarkRoot</*kGrayImmuneObject=*/false>(thread_, root);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002950 }
2951
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002952 private:
2953 ConcurrentCopying* const collector_;
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002954 Thread* const thread_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002955};
2956
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002957template <bool kNoUnEvac>
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002958inline void ConcurrentCopying::Scan(mirror::Object* to_ref) {
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002959 // Cannot have `kNoUnEvac` when Generational CC collection is disabled.
2960 DCHECK(kEnableGenerationalConcurrentCopyingCollection || !kNoUnEvac);
Hiroshi Yamauchi9b60d502017-02-03 15:09:26 -08002961 if (kDisallowReadBarrierDuringScan && !Runtime::Current()->IsActiveTransaction()) {
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07002962 // Avoid all read barriers during visit references to help performance.
Hiroshi Yamauchi9b60d502017-02-03 15:09:26 -08002963 // Don't do this in transaction mode because we may read the old value of an field which may
2964 // trigger read barriers.
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07002965 Thread::Current()->ModifyDebugDisallowReadBarrier(1);
2966 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002967 DCHECK(!region_space_->IsInFromSpace(to_ref));
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002968 DCHECK_EQ(Thread::Current(), thread_running_gc_);
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002969 RefFieldsVisitor<kNoUnEvac> visitor(this, thread_running_gc_);
Hiroshi Yamauchi5496f692016-02-17 13:29:59 -08002970 // Disable the read barrier for a performance reason.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07002971 to_ref->VisitReferences</*kVisitNativeRoots=*/true, kDefaultVerifyFlags, kWithoutReadBarrier>(
Hiroshi Yamauchi5496f692016-02-17 13:29:59 -08002972 visitor, visitor);
Hiroshi Yamauchi9b60d502017-02-03 15:09:26 -08002973 if (kDisallowReadBarrierDuringScan && !Runtime::Current()->IsActiveTransaction()) {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002974 thread_running_gc_->ModifyDebugDisallowReadBarrier(-1);
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07002975 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002976}
2977
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002978template <bool kNoUnEvac>
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002979inline void ConcurrentCopying::Process(mirror::Object* obj, MemberOffset offset) {
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002980 // Cannot have `kNoUnEvac` when Generational CC collection is disabled.
2981 DCHECK(kEnableGenerationalConcurrentCopyingCollection || !kNoUnEvac);
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002982 DCHECK_EQ(Thread::Current(), thread_running_gc_);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002983 mirror::Object* ref = obj->GetFieldObject<
2984 mirror::Object, kVerifyNone, kWithoutReadBarrier, false>(offset);
Andreas Gampe98ea9d92018-10-19 14:06:15 -07002985 mirror::Object* to_ref = Mark</*kGrayImmuneObject=*/false, kNoUnEvac, /*kFromGCThread=*/true>(
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002986 thread_running_gc_,
Mathieu Chartier4ce0c762017-05-18 10:01:07 -07002987 ref,
Andreas Gampe98ea9d92018-10-19 14:06:15 -07002988 /*holder=*/ obj,
Mathieu Chartier4ce0c762017-05-18 10:01:07 -07002989 offset);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002990 if (to_ref == ref) {
2991 return;
2992 }
2993 // This may fail if the mutator writes to the field at the same time. But it's ok.
2994 mirror::Object* expected_ref = ref;
2995 mirror::Object* new_ref = to_ref;
2996 do {
2997 if (expected_ref !=
2998 obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier, false>(offset)) {
2999 // It was updated by the mutator.
3000 break;
3001 }
Roland Levillain2ae376f2018-01-30 11:35:11 +00003002 // Use release CAS to make sure threads reading the reference see contents of copied objects.
Mathieu Chartiera9746b92018-06-22 10:25:40 -07003003 } while (!obj->CasFieldObjectWithoutWriteBarrier<false, false, kVerifyNone>(
Mathieu Chartierfdd513d2017-06-01 11:26:50 -07003004 offset,
3005 expected_ref,
Mathieu Chartiera9746b92018-06-22 10:25:40 -07003006 new_ref,
3007 CASMode::kWeak,
3008 std::memory_order_release));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003009}
3010
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07003011// Process some roots.
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07003012inline void ConcurrentCopying::VisitRoots(
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07003013 mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED) {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08003014 Thread* const self = Thread::Current();
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07003015 for (size_t i = 0; i < count; ++i) {
3016 mirror::Object** root = roots[i];
3017 mirror::Object* ref = *root;
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08003018 mirror::Object* to_ref = Mark(self, ref);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07003019 if (to_ref == ref) {
Mathieu Chartier4809d0a2015-04-07 10:39:04 -07003020 continue;
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07003021 }
3022 Atomic<mirror::Object*>* addr = reinterpret_cast<Atomic<mirror::Object*>*>(root);
3023 mirror::Object* expected_ref = ref;
3024 mirror::Object* new_ref = to_ref;
3025 do {
Orion Hodson88591fe2018-03-06 13:35:43 +00003026 if (expected_ref != addr->load(std::memory_order_relaxed)) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07003027 // It was updated by the mutator.
3028 break;
3029 }
Orion Hodson4557b382018-01-03 11:47:54 +00003030 } while (!addr->CompareAndSetWeakRelaxed(expected_ref, new_ref));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07003031 }
3032}
3033
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07003034template<bool kGrayImmuneObject>
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08003035inline void ConcurrentCopying::MarkRoot(Thread* const self,
3036 mirror::CompressedReference<mirror::Object>* root) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07003037 DCHECK(!root->IsNull());
3038 mirror::Object* const ref = root->AsMirrorPtr();
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08003039 mirror::Object* to_ref = Mark<kGrayImmuneObject>(self, ref);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07003040 if (to_ref != ref) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07003041 auto* addr = reinterpret_cast<Atomic<mirror::CompressedReference<mirror::Object>>*>(root);
3042 auto expected_ref = mirror::CompressedReference<mirror::Object>::FromMirrorPtr(ref);
3043 auto new_ref = mirror::CompressedReference<mirror::Object>::FromMirrorPtr(to_ref);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07003044 // If the cas fails, then it was updated by the mutator.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07003045 do {
Orion Hodson88591fe2018-03-06 13:35:43 +00003046 if (ref != addr->load(std::memory_order_relaxed).AsMirrorPtr()) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07003047 // It was updated by the mutator.
3048 break;
3049 }
Orion Hodson4557b382018-01-03 11:47:54 +00003050 } while (!addr->CompareAndSetWeakRelaxed(expected_ref, new_ref));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07003051 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003052}
3053
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07003054inline void ConcurrentCopying::VisitRoots(
Mathieu Chartierda7c6502015-07-23 16:01:26 -07003055 mirror::CompressedReference<mirror::Object>** roots, size_t count,
3056 const RootInfo& info ATTRIBUTE_UNUSED) {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08003057 Thread* const self = Thread::Current();
Mathieu Chartierda7c6502015-07-23 16:01:26 -07003058 for (size_t i = 0; i < count; ++i) {
3059 mirror::CompressedReference<mirror::Object>* const root = roots[i];
3060 if (!root->IsNull()) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07003061 // kGrayImmuneObject is true because this is used for the thread flip.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07003062 MarkRoot</*kGrayImmuneObject=*/true>(self, root);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07003063 }
3064 }
3065}
3066
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07003067// Temporary set gc_grays_immune_objects_ to true in a scope if the current thread is GC.
3068class ConcurrentCopying::ScopedGcGraysImmuneObjects {
3069 public:
3070 explicit ScopedGcGraysImmuneObjects(ConcurrentCopying* collector)
3071 : collector_(collector), enabled_(false) {
3072 if (kUseBakerReadBarrier &&
3073 collector_->thread_running_gc_ == Thread::Current() &&
3074 !collector_->gc_grays_immune_objects_) {
3075 collector_->gc_grays_immune_objects_ = true;
3076 enabled_ = true;
3077 }
3078 }
3079
3080 ~ScopedGcGraysImmuneObjects() {
3081 if (kUseBakerReadBarrier &&
3082 collector_->thread_running_gc_ == Thread::Current() &&
3083 enabled_) {
3084 DCHECK(collector_->gc_grays_immune_objects_);
3085 collector_->gc_grays_immune_objects_ = false;
3086 }
3087 }
3088
3089 private:
3090 ConcurrentCopying* const collector_;
3091 bool enabled_;
3092};
3093
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003094// Fill the given memory block with a dummy object. Used to fill in a
3095// copy of objects that was lost in race.
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08003096void ConcurrentCopying::FillWithDummyObject(Thread* const self,
3097 mirror::Object* dummy_obj,
3098 size_t byte_size) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07003099 // GC doesn't gray immune objects while scanning immune objects. But we need to trigger the read
3100 // barriers here because we need the updated reference to the int array class, etc. Temporary set
3101 // gc_grays_immune_objects_ to true so that we won't cause a DCHECK failure in MarkImmuneSpace().
3102 ScopedGcGraysImmuneObjects scoped_gc_gray_immune_objects(this);
Roland Levillain14d90572015-07-16 10:52:26 +01003103 CHECK_ALIGNED(byte_size, kObjectAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003104 memset(dummy_obj, 0, byte_size);
Mathieu Chartierd6636d32016-07-28 11:02:38 -07003105 // Avoid going through read barrier for since kDisallowReadBarrierDuringScan may be enabled.
3106 // Explicitly mark to make sure to get an object in the to-space.
3107 mirror::Class* int_array_class = down_cast<mirror::Class*>(
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08003108 Mark(self, GetClassRoot<mirror::IntArray, kWithoutReadBarrier>().Ptr()));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003109 CHECK(int_array_class != nullptr);
Andreas Gampe6c578712017-10-19 13:00:34 -07003110 if (ReadBarrier::kEnableToSpaceInvariantChecks) {
3111 AssertToSpaceInvariant(nullptr, MemberOffset(0), int_array_class);
3112 }
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07003113 size_t component_size = int_array_class->GetComponentSize<kWithoutReadBarrier>();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003114 CHECK_EQ(component_size, sizeof(int32_t));
3115 size_t data_offset = mirror::Array::DataOffset(component_size).SizeValue();
3116 if (data_offset > byte_size) {
3117 // An int array is too big. Use java.lang.Object.
Mathieu Chartier9aef9922017-04-23 13:53:50 -07003118 CHECK(java_lang_Object_ != nullptr);
Andreas Gampe6c578712017-10-19 13:00:34 -07003119 if (ReadBarrier::kEnableToSpaceInvariantChecks) {
3120 AssertToSpaceInvariant(nullptr, MemberOffset(0), java_lang_Object_);
3121 }
Vladimir Marko98db89c2018-09-07 11:45:46 +01003122 CHECK_EQ(byte_size, java_lang_Object_->GetObjectSize<kVerifyNone>());
Mathieu Chartier3ed8ec12017-04-20 19:28:54 -07003123 dummy_obj->SetClass(java_lang_Object_);
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07003124 CHECK_EQ(byte_size, (dummy_obj->SizeOf<kVerifyNone>()));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003125 } else {
3126 // Use an int array.
3127 dummy_obj->SetClass(int_array_class);
Vladimir Marko98db89c2018-09-07 11:45:46 +01003128 CHECK(dummy_obj->IsArrayInstance<kVerifyNone>());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003129 int32_t length = (byte_size - data_offset) / component_size;
Vladimir Marko98db89c2018-09-07 11:45:46 +01003130 mirror::Array* dummy_arr = dummy_obj->AsArray<kVerifyNone>();
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07003131 dummy_arr->SetLength(length);
3132 CHECK_EQ(dummy_arr->GetLength(), length)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003133 << "byte_size=" << byte_size << " length=" << length
3134 << " component_size=" << component_size << " data_offset=" << data_offset;
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07003135 CHECK_EQ(byte_size, (dummy_obj->SizeOf<kVerifyNone>()))
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003136 << "byte_size=" << byte_size << " length=" << length
3137 << " component_size=" << component_size << " data_offset=" << data_offset;
3138 }
3139}
3140
3141// Reuse the memory blocks that were copy of objects that were lost in race.
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08003142mirror::Object* ConcurrentCopying::AllocateInSkippedBlock(Thread* const self, size_t alloc_size) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003143 // Try to reuse the blocks that were unused due to CAS failures.
Roland Levillain14d90572015-07-16 10:52:26 +01003144 CHECK_ALIGNED(alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003145 size_t min_object_size = RoundUp(sizeof(mirror::Object), space::RegionSpace::kAlignment);
Mathieu Chartierd6636d32016-07-28 11:02:38 -07003146 size_t byte_size;
3147 uint8_t* addr;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003148 {
Mathieu Chartierd6636d32016-07-28 11:02:38 -07003149 MutexLock mu(self, skipped_blocks_lock_);
3150 auto it = skipped_blocks_map_.lower_bound(alloc_size);
3151 if (it == skipped_blocks_map_.end()) {
3152 // Not found.
3153 return nullptr;
3154 }
3155 byte_size = it->first;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003156 CHECK_GE(byte_size, alloc_size);
3157 if (byte_size > alloc_size && byte_size - alloc_size < min_object_size) {
3158 // If remainder would be too small for a dummy object, retry with a larger request size.
3159 it = skipped_blocks_map_.lower_bound(alloc_size + min_object_size);
3160 if (it == skipped_blocks_map_.end()) {
3161 // Not found.
3162 return nullptr;
3163 }
Roland Levillain14d90572015-07-16 10:52:26 +01003164 CHECK_ALIGNED(it->first - alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003165 CHECK_GE(it->first - alloc_size, min_object_size)
3166 << "byte_size=" << byte_size << " it->first=" << it->first << " alloc_size=" << alloc_size;
3167 }
Mathieu Chartierd6636d32016-07-28 11:02:38 -07003168 // Found a block.
3169 CHECK(it != skipped_blocks_map_.end());
3170 byte_size = it->first;
3171 addr = it->second;
3172 CHECK_GE(byte_size, alloc_size);
3173 CHECK(region_space_->IsInToSpace(reinterpret_cast<mirror::Object*>(addr)));
3174 CHECK_ALIGNED(byte_size, space::RegionSpace::kAlignment);
3175 if (kVerboseMode) {
3176 LOG(INFO) << "Reusing skipped bytes : " << reinterpret_cast<void*>(addr) << ", " << byte_size;
3177 }
3178 skipped_blocks_map_.erase(it);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003179 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003180 memset(addr, 0, byte_size);
3181 if (byte_size > alloc_size) {
3182 // Return the remainder to the map.
Roland Levillain14d90572015-07-16 10:52:26 +01003183 CHECK_ALIGNED(byte_size - alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003184 CHECK_GE(byte_size - alloc_size, min_object_size);
Mathieu Chartierd6636d32016-07-28 11:02:38 -07003185 // FillWithDummyObject may mark an object, avoid holding skipped_blocks_lock_ to prevent lock
3186 // violation and possible deadlock. The deadlock case is a recursive case:
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003187 // FillWithDummyObject -> Mark(IntArray.class) -> Copy -> AllocateInSkippedBlock.
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08003188 FillWithDummyObject(self,
3189 reinterpret_cast<mirror::Object*>(addr + alloc_size),
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003190 byte_size - alloc_size);
3191 CHECK(region_space_->IsInToSpace(reinterpret_cast<mirror::Object*>(addr + alloc_size)));
Mathieu Chartierd6636d32016-07-28 11:02:38 -07003192 {
3193 MutexLock mu(self, skipped_blocks_lock_);
3194 skipped_blocks_map_.insert(std::make_pair(byte_size - alloc_size, addr + alloc_size));
3195 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003196 }
3197 return reinterpret_cast<mirror::Object*>(addr);
3198}
3199
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08003200mirror::Object* ConcurrentCopying::Copy(Thread* const self,
3201 mirror::Object* from_ref,
Mathieu Chartieref496d92017-04-28 18:58:59 -07003202 mirror::Object* holder,
3203 MemberOffset offset) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003204 DCHECK(region_space_->IsInFromSpace(from_ref));
Mathieu Chartieref496d92017-04-28 18:58:59 -07003205 // If the class pointer is null, the object is invalid. This could occur for a dangling pointer
3206 // from a previous GC that is either inside or outside the allocated region.
3207 mirror::Class* klass = from_ref->GetClass<kVerifyNone, kWithoutReadBarrier>();
3208 if (UNLIKELY(klass == nullptr)) {
Roland Levillainca3dded2018-08-10 15:35:17 +01003209 // Remove memory protection from the region space and log debugging information.
3210 region_space_->Unprotect();
Andreas Gampe98ea9d92018-10-19 14:06:15 -07003211 heap_->GetVerification()->LogHeapCorruption(holder, offset, from_ref, /* fatal= */ true);
Mathieu Chartieref496d92017-04-28 18:58:59 -07003212 }
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07003213 // There must not be a read barrier to avoid nested RB that might violate the to-space invariant.
3214 // Note that from_ref is a from space ref so the SizeOf() call will access the from-space meta
3215 // objects, but it's ok and necessary.
3216 size_t obj_size = from_ref->SizeOf<kDefaultVerifyFlags>();
Nicolas Geoffray4b361a82017-07-06 15:30:10 +01003217 size_t region_space_alloc_size = (obj_size <= space::RegionSpace::kRegionSize)
3218 ? RoundUp(obj_size, space::RegionSpace::kAlignment)
3219 : RoundUp(obj_size, space::RegionSpace::kRegionSize);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003220 size_t region_space_bytes_allocated = 0U;
3221 size_t non_moving_space_bytes_allocated = 0U;
3222 size_t bytes_allocated = 0U;
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07003223 size_t dummy;
Lokesh Gidraf2a69312018-03-27 18:48:59 -07003224 bool fall_back_to_non_moving = false;
Andreas Gampe98ea9d92018-10-19 14:06:15 -07003225 mirror::Object* to_ref = region_space_->AllocNonvirtual</*kForEvac=*/ true>(
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07003226 region_space_alloc_size, &region_space_bytes_allocated, nullptr, &dummy);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003227 bytes_allocated = region_space_bytes_allocated;
Lokesh Gidraf2a69312018-03-27 18:48:59 -07003228 if (LIKELY(to_ref != nullptr)) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003229 DCHECK_EQ(region_space_alloc_size, region_space_bytes_allocated);
Lokesh Gidraf2a69312018-03-27 18:48:59 -07003230 } else {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003231 // Failed to allocate in the region space. Try the skipped blocks.
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08003232 to_ref = AllocateInSkippedBlock(self, region_space_alloc_size);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003233 if (to_ref != nullptr) {
3234 // Succeeded to allocate in a skipped block.
3235 if (heap_->use_tlab_) {
3236 // This is necessary for the tlab case as it's not accounted in the space.
3237 region_space_->RecordAlloc(to_ref);
3238 }
3239 bytes_allocated = region_space_alloc_size;
Hans Boehmfb8b4e22018-09-05 16:45:42 -07003240 heap_->num_bytes_allocated_.fetch_sub(bytes_allocated, std::memory_order_relaxed);
3241 to_space_bytes_skipped_.fetch_sub(bytes_allocated, std::memory_order_relaxed);
3242 to_space_objects_skipped_.fetch_sub(1, std::memory_order_relaxed);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003243 } else {
3244 // Fall back to the non-moving space.
3245 fall_back_to_non_moving = true;
3246 if (kVerboseMode) {
3247 LOG(INFO) << "Out of memory in the to-space. Fall back to non-moving. skipped_bytes="
Hans Boehmfb8b4e22018-09-05 16:45:42 -07003248 << to_space_bytes_skipped_.load(std::memory_order_relaxed)
Orion Hodson88591fe2018-03-06 13:35:43 +00003249 << " skipped_objects="
Hans Boehmfb8b4e22018-09-05 16:45:42 -07003250 << to_space_objects_skipped_.load(std::memory_order_relaxed);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003251 }
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08003252 to_ref = heap_->non_moving_space_->Alloc(self, obj_size,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07003253 &non_moving_space_bytes_allocated, nullptr, &dummy);
Mathieu Chartierb01335c2017-03-22 13:15:01 -07003254 if (UNLIKELY(to_ref == nullptr)) {
3255 LOG(FATAL_WITHOUT_ABORT) << "Fall-back non-moving space allocation failed for a "
3256 << obj_size << " byte object in region type "
3257 << region_space_->GetRegionType(from_ref);
3258 LOG(FATAL) << "Object address=" << from_ref << " type=" << from_ref->PrettyTypeOf();
3259 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003260 bytes_allocated = non_moving_space_bytes_allocated;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003261 }
3262 }
3263 DCHECK(to_ref != nullptr);
3264
Mathieu Chartierd818adb2016-09-15 13:12:47 -07003265 // Copy the object excluding the lock word since that is handled in the loop.
Mathieu Chartieref496d92017-04-28 18:58:59 -07003266 to_ref->SetClass(klass);
Mathieu Chartierd818adb2016-09-15 13:12:47 -07003267 const size_t kObjectHeaderSize = sizeof(mirror::Object);
3268 DCHECK_GE(obj_size, kObjectHeaderSize);
3269 static_assert(kObjectHeaderSize == sizeof(mirror::HeapReference<mirror::Class>) +
3270 sizeof(LockWord),
3271 "Object header size does not match");
3272 // Memcpy can tear for words since it may do byte copy. It is only safe to do this since the
3273 // object in the from space is immutable other than the lock word. b/31423258
3274 memcpy(reinterpret_cast<uint8_t*>(to_ref) + kObjectHeaderSize,
3275 reinterpret_cast<const uint8_t*>(from_ref) + kObjectHeaderSize,
3276 obj_size - kObjectHeaderSize);
3277
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003278 // Attempt to install the forward pointer. This is in a loop as the
3279 // lock word atomic write can fail.
3280 while (true) {
Mathieu Chartierd818adb2016-09-15 13:12:47 -07003281 LockWord old_lock_word = from_ref->GetLockWord(false);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003282
3283 if (old_lock_word.GetState() == LockWord::kForwardingAddress) {
3284 // Lost the race. Another thread (either GC or mutator) stored
3285 // the forwarding pointer first. Make the lost copy (to_ref)
3286 // look like a valid but dead (dummy) object and keep it for
3287 // future reuse.
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08003288 FillWithDummyObject(self, to_ref, bytes_allocated);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003289 if (!fall_back_to_non_moving) {
3290 DCHECK(region_space_->IsInToSpace(to_ref));
3291 if (bytes_allocated > space::RegionSpace::kRegionSize) {
3292 // Free the large alloc.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07003293 region_space_->FreeLarge</*kForEvac=*/ true>(to_ref, bytes_allocated);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003294 } else {
3295 // Record the lost copy for later reuse.
Hans Boehmfb8b4e22018-09-05 16:45:42 -07003296 heap_->num_bytes_allocated_.fetch_add(bytes_allocated, std::memory_order_relaxed);
3297 to_space_bytes_skipped_.fetch_add(bytes_allocated, std::memory_order_relaxed);
3298 to_space_objects_skipped_.fetch_add(1, std::memory_order_relaxed);
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08003299 MutexLock mu(self, skipped_blocks_lock_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003300 skipped_blocks_map_.insert(std::make_pair(bytes_allocated,
3301 reinterpret_cast<uint8_t*>(to_ref)));
3302 }
3303 } else {
3304 DCHECK(heap_->non_moving_space_->HasAddress(to_ref));
3305 DCHECK_EQ(bytes_allocated, non_moving_space_bytes_allocated);
3306 // Free the non-moving-space chunk.
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08003307 heap_->non_moving_space_->Free(self, to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003308 }
3309
3310 // Get the winner's forward ptr.
3311 mirror::Object* lost_fwd_ptr = to_ref;
3312 to_ref = reinterpret_cast<mirror::Object*>(old_lock_word.ForwardingAddress());
3313 CHECK(to_ref != nullptr);
3314 CHECK_NE(to_ref, lost_fwd_ptr);
Mathieu Chartierdfcd6f42016-09-13 10:02:48 -07003315 CHECK(region_space_->IsInToSpace(to_ref) || heap_->non_moving_space_->HasAddress(to_ref))
3316 << "to_ref=" << to_ref << " " << heap_->DumpSpaces();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003317 CHECK_NE(to_ref->GetLockWord(false).GetState(), LockWord::kForwardingAddress);
3318 return to_ref;
3319 }
3320
Mathieu Chartierd818adb2016-09-15 13:12:47 -07003321 // Copy the old lock word over since we did not copy it yet.
3322 to_ref->SetLockWord(old_lock_word, false);
Hiroshi Yamauchi60f63f52015-04-23 16:12:40 -07003323 // Set the gray ptr.
3324 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07003325 to_ref->SetReadBarrierState(ReadBarrier::GrayState());
Hiroshi Yamauchi60f63f52015-04-23 16:12:40 -07003326 }
3327
Mathieu Chartiera8131262016-11-29 17:55:19 -08003328 // Do a fence to prevent the field CAS in ConcurrentCopying::Process from possibly reordering
3329 // before the object copy.
Orion Hodson27b96762018-03-13 16:06:57 +00003330 std::atomic_thread_fence(std::memory_order_release);
Mathieu Chartiera8131262016-11-29 17:55:19 -08003331
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003332 LockWord new_lock_word = LockWord::FromForwardingAddress(reinterpret_cast<size_t>(to_ref));
3333
3334 // Try to atomically write the fwd ptr.
Mathieu Chartier42c2e502018-06-19 12:30:56 -07003335 bool success = from_ref->CasLockWord(old_lock_word,
3336 new_lock_word,
3337 CASMode::kWeak,
3338 std::memory_order_relaxed);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003339 if (LIKELY(success)) {
3340 // The CAS succeeded.
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08003341 DCHECK(thread_running_gc_ != nullptr);
3342 if (LIKELY(self == thread_running_gc_)) {
3343 objects_moved_gc_thread_ += 1;
3344 bytes_moved_gc_thread_ += region_space_alloc_size;
3345 } else {
3346 objects_moved_.fetch_add(1, std::memory_order_relaxed);
3347 bytes_moved_.fetch_add(region_space_alloc_size, std::memory_order_relaxed);
3348 }
3349
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003350 if (LIKELY(!fall_back_to_non_moving)) {
3351 DCHECK(region_space_->IsInToSpace(to_ref));
3352 } else {
3353 DCHECK(heap_->non_moving_space_->HasAddress(to_ref));
3354 DCHECK_EQ(bytes_allocated, non_moving_space_bytes_allocated);
Lokesh Gidra519c1c72018-11-09 17:10:47 -08003355 if (!kEnableGenerationalConcurrentCopyingCollection || !young_gen_) {
3356 // Mark it in the live bitmap.
3357 CHECK(!heap_->non_moving_space_->GetLiveBitmap()->AtomicTestAndSet(to_ref));
3358 }
3359 if (!kUseBakerReadBarrier) {
3360 // Mark it in the mark bitmap.
3361 CHECK(!heap_->non_moving_space_->GetMarkBitmap()->AtomicTestAndSet(to_ref));
3362 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003363 }
3364 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07003365 DCHECK(to_ref->GetReadBarrierState() == ReadBarrier::GrayState());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003366 }
3367 DCHECK(GetFwdPtr(from_ref) == to_ref);
3368 CHECK_NE(to_ref->GetLockWord(false).GetState(), LockWord::kForwardingAddress);
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08003369 PushOntoMarkStack(self, to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003370 return to_ref;
3371 } else {
3372 // The CAS failed. It may have lost the race or may have failed
3373 // due to monitor/hashcode ops. Either way, retry.
3374 }
3375 }
3376}
3377
3378mirror::Object* ConcurrentCopying::IsMarked(mirror::Object* from_ref) {
3379 DCHECK(from_ref != nullptr);
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08003380 space::RegionSpace::RegionType rtype = region_space_->GetRegionType(from_ref);
3381 if (rtype == space::RegionSpace::RegionType::kRegionTypeToSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003382 // It's already marked.
3383 return from_ref;
3384 }
3385 mirror::Object* to_ref;
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08003386 if (rtype == space::RegionSpace::RegionType::kRegionTypeFromSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003387 to_ref = GetFwdPtr(from_ref);
3388 DCHECK(to_ref == nullptr || region_space_->IsInToSpace(to_ref) ||
3389 heap_->non_moving_space_->HasAddress(to_ref))
3390 << "from_ref=" << from_ref << " to_ref=" << to_ref;
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08003391 } else if (rtype == space::RegionSpace::RegionType::kRegionTypeUnevacFromSpace) {
Mathieu Chartierc381c362016-08-23 13:27:53 -07003392 if (IsMarkedInUnevacFromSpace(from_ref)) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003393 to_ref = from_ref;
3394 } else {
3395 to_ref = nullptr;
3396 }
3397 } else {
Roland Levillain001eff92018-01-24 14:24:33 +00003398 // At this point, `from_ref` should not be in the region space
3399 // (i.e. within an "unused" region).
3400 DCHECK(!region_space_->HasAddress(from_ref)) << from_ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003401 // from_ref is in a non-moving space.
Mathieu Chartier763a31e2015-11-16 16:05:55 -08003402 if (immune_spaces_.ContainsObject(from_ref)) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07003403 // An immune object is alive.
3404 to_ref = from_ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003405 } else {
3406 // Non-immune non-moving space. Use the mark bitmap.
Lokesh Gidra519c1c72018-11-09 17:10:47 -08003407 if (IsMarkedInNonMovingSpace(from_ref)) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003408 // Already marked.
3409 to_ref = from_ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003410 } else {
Lokesh Gidra519c1c72018-11-09 17:10:47 -08003411 to_ref = nullptr;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003412 }
3413 }
3414 }
3415 return to_ref;
3416}
3417
3418bool ConcurrentCopying::IsOnAllocStack(mirror::Object* ref) {
Hans Boehmcc55e1d2017-07-27 15:28:07 -07003419 // TODO: Explain why this is here. What release operation does it pair with?
Orion Hodson27b96762018-03-13 16:06:57 +00003420 std::atomic_thread_fence(std::memory_order_acquire);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003421 accounting::ObjectStack* alloc_stack = GetAllocationStack();
Mathieu Chartiercb535da2015-01-23 13:50:03 -08003422 return alloc_stack->Contains(ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003423}
3424
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08003425mirror::Object* ConcurrentCopying::MarkNonMoving(Thread* const self,
3426 mirror::Object* ref,
Mathieu Chartier1ca68902017-04-18 11:26:22 -07003427 mirror::Object* holder,
3428 MemberOffset offset) {
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07003429 // ref is in a non-moving space (from_ref == to_ref).
3430 DCHECK(!region_space_->HasAddress(ref)) << ref;
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07003431 DCHECK(!immune_spaces_.ContainsObject(ref));
3432 // Use the mark bitmap.
Lokesh Gidra519c1c72018-11-09 17:10:47 -08003433 accounting::ContinuousSpaceBitmap* mark_bitmap = heap_->GetNonMovingSpace()->GetMarkBitmap();
3434 accounting::LargeObjectBitmap* los_bitmap = nullptr;
3435 const bool is_los = !mark_bitmap->HasAddress(ref);
3436 if (is_los) {
3437 if (!IsAligned<kPageSize>(ref)) {
3438 // Ref is a large object that is not aligned, it must be heap
3439 // corruption. Remove memory protection and dump data before
3440 // AtomicSetReadBarrierState since it will fault if the address is not
3441 // valid.
3442 region_space_->Unprotect();
3443 heap_->GetVerification()->LogHeapCorruption(holder, offset, ref, /* fatal= */ true);
3444 }
3445 DCHECK(heap_->GetLargeObjectsSpace())
3446 << "ref=" << ref
3447 << " doesn't belong to non-moving space and large object space doesn't exist";
3448 los_bitmap = heap_->GetLargeObjectsSpace()->GetMarkBitmap();
3449 DCHECK(los_bitmap->HasAddress(ref));
3450 }
Lokesh Gidra2a9824c2018-11-07 15:57:17 -08003451 if (kEnableGenerationalConcurrentCopyingCollection) {
Roland Levillainade74a62018-08-08 15:55:42 +01003452 // The sticky-bit CC collector is only compatible with Baker-style read barriers.
3453 DCHECK(kUseBakerReadBarrier);
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07003454 // Not done scanning, use AtomicSetReadBarrierPointer.
Roland Levillain2d94e292018-08-15 16:46:30 +01003455 if (!done_scanning_.load(std::memory_order_acquire)) {
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07003456 // Since the mark bitmap is still filled in from last GC, we can not use that or else the
Roland Levillainade74a62018-08-08 15:55:42 +01003457 // mutator may see references to the from space. Instead, use the Baker pointer itself as
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07003458 // the mark bit.
Lokesh Gidra16d82a22018-10-10 22:40:02 -07003459 //
3460 // We need to avoid marking objects that are on allocation stack as that will lead to a
3461 // situation (after this GC cycle is finished) where some object(s) are on both allocation
3462 // stack and live bitmap. This leads to visiting the same object(s) twice during a heapdump
3463 // (b/117426281).
3464 if (!IsOnAllocStack(ref) &&
3465 ref->AtomicSetReadBarrierState(ReadBarrier::NonGrayState(), ReadBarrier::GrayState())) {
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07003466 // TODO: We don't actually need to scan this object later, we just need to clear the gray
3467 // bit.
Lokesh Gidra16d82a22018-10-10 22:40:02 -07003468 // We don't need to mark newly allocated objects (those in allocation stack) as they can
3469 // only point to to-space objects. Also, they are considered live till the next GC cycle.
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07003470 PushOntoMarkStack(self, ref);
3471 }
3472 return ref;
3473 }
3474 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07003475 if (!is_los && mark_bitmap->Test(ref)) {
3476 // Already marked.
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07003477 } else if (is_los && los_bitmap->Test(ref)) {
3478 // Already marked in LOS.
Lokesh Gidra519c1c72018-11-09 17:10:47 -08003479 } else if (IsOnAllocStack(ref)) {
3480 // If it's on the allocation stack, it's considered marked. Keep it white (non-gray).
3481 // Objects on the allocation stack need not be marked.
3482 if (!is_los) {
3483 DCHECK(!mark_bitmap->Test(ref));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003484 } else {
Lokesh Gidra519c1c72018-11-09 17:10:47 -08003485 DCHECK(!los_bitmap->Test(ref));
3486 }
3487 if (kUseBakerReadBarrier) {
3488 DCHECK_EQ(ref->GetReadBarrierState(), ReadBarrier::NonGrayState());
3489 }
3490 } else {
3491 // Not marked nor on the allocation stack. Try to mark it.
3492 // This may or may not succeed, which is ok.
3493 bool success = false;
3494 if (kUseBakerReadBarrier) {
3495 success = ref->AtomicSetReadBarrierState(ReadBarrier::NonGrayState(),
3496 ReadBarrier::GrayState());
3497 } else {
3498 success = is_los ?
3499 !los_bitmap->AtomicTestAndSet(ref) :
3500 !mark_bitmap->AtomicTestAndSet(ref);
3501 }
3502 if (success) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07003503 if (kUseBakerReadBarrier) {
Lokesh Gidra519c1c72018-11-09 17:10:47 -08003504 DCHECK_EQ(ref->GetReadBarrierState(), ReadBarrier::GrayState());
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07003505 }
Lokesh Gidra519c1c72018-11-09 17:10:47 -08003506 PushOntoMarkStack(self, ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003507 }
3508 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07003509 return ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003510}
3511
3512void ConcurrentCopying::FinishPhase() {
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -08003513 Thread* const self = Thread::Current();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07003514 {
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -08003515 MutexLock mu(self, mark_stack_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07003516 CHECK_EQ(pooled_mark_stacks_.size(), kMarkStackPoolSize);
3517 }
Mathieu Chartiera1467d02017-02-22 09:22:50 -08003518 // kVerifyNoMissingCardMarks relies on the region space cards not being cleared to avoid false
3519 // positives.
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07003520 if (!kEnableGenerationalConcurrentCopyingCollection && !kVerifyNoMissingCardMarks) {
Mathieu Chartier6e6078a2016-10-24 15:45:41 -07003521 TimingLogger::ScopedTiming split("ClearRegionSpaceCards", GetTimings());
3522 // We do not currently use the region space cards at all, madvise them away to save ram.
3523 heap_->GetCardTable()->ClearCardRange(region_space_->Begin(), region_space_->Limit());
Lokesh Gidrad0c5b252018-12-05 01:10:40 -08003524 } else if (kEnableGenerationalConcurrentCopyingCollection && !young_gen_) {
3525 inter_region_bitmap_.reset();
Mathieu Chartier6e6078a2016-10-24 15:45:41 -07003526 }
3527 {
3528 MutexLock mu(self, skipped_blocks_lock_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003529 skipped_blocks_map_.clear();
3530 }
Mathieu Chartier56fe2582016-07-14 13:30:03 -07003531 {
3532 ReaderMutexLock mu(self, *Locks::mutator_lock_);
Mathieu Chartier21328a12016-07-22 10:47:45 -07003533 {
3534 WriterMutexLock mu2(self, *Locks::heap_bitmap_lock_);
3535 heap_->ClearMarkedObjects();
3536 }
3537 if (kUseBakerReadBarrier && kFilterModUnionCards) {
3538 TimingLogger::ScopedTiming split("FilterModUnionCards", GetTimings());
3539 ReaderMutexLock mu2(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier21328a12016-07-22 10:47:45 -07003540 for (space::ContinuousSpace* space : immune_spaces_.GetSpaces()) {
3541 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
Mathieu Chartier6e6078a2016-10-24 15:45:41 -07003542 accounting::ModUnionTable* table = heap_->FindModUnionTableFromSpace(space);
Mathieu Chartier21328a12016-07-22 10:47:45 -07003543 // Filter out cards that don't need to be set.
3544 if (table != nullptr) {
3545 table->FilterCards();
3546 }
3547 }
3548 }
Mathieu Chartier36a270a2016-07-28 18:08:51 -07003549 if (kUseBakerReadBarrier) {
3550 TimingLogger::ScopedTiming split("EmptyRBMarkBitStack", GetTimings());
Mathieu Chartier6e6078a2016-10-24 15:45:41 -07003551 DCHECK(rb_mark_bit_stack_ != nullptr);
Mathieu Chartier36a270a2016-07-28 18:08:51 -07003552 const auto* limit = rb_mark_bit_stack_->End();
3553 for (StackReference<mirror::Object>* it = rb_mark_bit_stack_->Begin(); it != limit; ++it) {
Roland Levillain001eff92018-01-24 14:24:33 +00003554 CHECK(it->AsMirrorPtr()->AtomicSetMarkBit(1, 0))
3555 << "rb_mark_bit_stack_->Begin()" << rb_mark_bit_stack_->Begin() << '\n'
3556 << "rb_mark_bit_stack_->End()" << rb_mark_bit_stack_->End() << '\n'
3557 << "rb_mark_bit_stack_->IsFull()"
3558 << std::boolalpha << rb_mark_bit_stack_->IsFull() << std::noboolalpha << '\n'
3559 << DumpReferenceInfo(it->AsMirrorPtr(), "*it");
Mathieu Chartier36a270a2016-07-28 18:08:51 -07003560 }
3561 rb_mark_bit_stack_->Reset();
3562 }
Mathieu Chartier56fe2582016-07-14 13:30:03 -07003563 }
3564 if (measure_read_barrier_slow_path_) {
3565 MutexLock mu(self, rb_slow_path_histogram_lock_);
Orion Hodson88591fe2018-03-06 13:35:43 +00003566 rb_slow_path_time_histogram_.AdjustAndAddValue(
3567 rb_slow_path_ns_.load(std::memory_order_relaxed));
3568 rb_slow_path_count_total_ += rb_slow_path_count_.load(std::memory_order_relaxed);
3569 rb_slow_path_count_gc_total_ += rb_slow_path_count_gc_.load(std::memory_order_relaxed);
Mathieu Chartier56fe2582016-07-14 13:30:03 -07003570 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003571}
3572
Hiroshi Yamauchi65f5f242016-12-19 11:44:47 -08003573bool ConcurrentCopying::IsNullOrMarkedHeapReference(mirror::HeapReference<mirror::Object>* field,
3574 bool do_atomic_update) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003575 mirror::Object* from_ref = field->AsMirrorPtr();
Hiroshi Yamauchi65f5f242016-12-19 11:44:47 -08003576 if (from_ref == nullptr) {
3577 return true;
3578 }
Mathieu Chartier97509952015-07-13 14:35:43 -07003579 mirror::Object* to_ref = IsMarked(from_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003580 if (to_ref == nullptr) {
3581 return false;
3582 }
3583 if (from_ref != to_ref) {
Hiroshi Yamauchi65f5f242016-12-19 11:44:47 -08003584 if (do_atomic_update) {
3585 do {
3586 if (field->AsMirrorPtr() != from_ref) {
3587 // Concurrently overwritten by a mutator.
3588 break;
3589 }
3590 } while (!field->CasWeakRelaxed(from_ref, to_ref));
3591 } else {
Hans Boehmcc55e1d2017-07-27 15:28:07 -07003592 // TODO: Why is this seq_cst when the above is relaxed? Document memory ordering.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07003593 field->Assign</* kIsVolatile= */ true>(to_ref);
Hiroshi Yamauchi65f5f242016-12-19 11:44:47 -08003594 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003595 }
3596 return true;
3597}
3598
Mathieu Chartier97509952015-07-13 14:35:43 -07003599mirror::Object* ConcurrentCopying::MarkObject(mirror::Object* from_ref) {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08003600 return Mark(Thread::Current(), from_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003601}
3602
Mathieu Chartier31e88222016-10-14 18:43:19 -07003603void ConcurrentCopying::DelayReferenceReferent(ObjPtr<mirror::Class> klass,
3604 ObjPtr<mirror::Reference> reference) {
Mathieu Chartier97509952015-07-13 14:35:43 -07003605 heap_->GetReferenceProcessor()->DelayReferenceReferent(klass, reference, this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003606}
3607
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07003608void ConcurrentCopying::ProcessReferences(Thread* self) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003609 TimingLogger::ScopedTiming split("ProcessReferences", GetTimings());
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07003610 // 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 -08003611 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
3612 GetHeap()->GetReferenceProcessor()->ProcessReferences(
Andreas Gampe98ea9d92018-10-19 14:06:15 -07003613 /*concurrent=*/ true, GetTimings(), GetCurrentIteration()->GetClearSoftReferences(), this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003614}
3615
3616void ConcurrentCopying::RevokeAllThreadLocalBuffers() {
3617 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
3618 region_space_->RevokeAllThreadLocalBuffers();
3619}
3620
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08003621mirror::Object* ConcurrentCopying::MarkFromReadBarrierWithMeasurements(Thread* const self,
3622 mirror::Object* from_ref) {
3623 if (self != thread_running_gc_) {
Orion Hodson88591fe2018-03-06 13:35:43 +00003624 rb_slow_path_count_.fetch_add(1u, std::memory_order_relaxed);
Mathieu Chartier56fe2582016-07-14 13:30:03 -07003625 } else {
Orion Hodson88591fe2018-03-06 13:35:43 +00003626 rb_slow_path_count_gc_.fetch_add(1u, std::memory_order_relaxed);
Mathieu Chartier56fe2582016-07-14 13:30:03 -07003627 }
3628 ScopedTrace tr(__FUNCTION__);
3629 const uint64_t start_time = measure_read_barrier_slow_path_ ? NanoTime() : 0u;
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07003630 mirror::Object* ret =
Andreas Gampe98ea9d92018-10-19 14:06:15 -07003631 Mark</*kGrayImmuneObject=*/true, /*kNoUnEvac=*/false, /*kFromGCThread=*/false>(self,
3632 from_ref);
Mathieu Chartier56fe2582016-07-14 13:30:03 -07003633 if (measure_read_barrier_slow_path_) {
Orion Hodson88591fe2018-03-06 13:35:43 +00003634 rb_slow_path_ns_.fetch_add(NanoTime() - start_time, std::memory_order_relaxed);
Mathieu Chartier56fe2582016-07-14 13:30:03 -07003635 }
3636 return ret;
3637}
3638
3639void ConcurrentCopying::DumpPerformanceInfo(std::ostream& os) {
3640 GarbageCollector::DumpPerformanceInfo(os);
Albert Mingkun Yangaf9cce12018-11-07 09:58:35 +00003641 size_t num_gc_cycles = GetCumulativeTimings().GetIterations();
Mathieu Chartier56fe2582016-07-14 13:30:03 -07003642 MutexLock mu(Thread::Current(), rb_slow_path_histogram_lock_);
3643 if (rb_slow_path_time_histogram_.SampleSize() > 0) {
3644 Histogram<uint64_t>::CumulativeData cumulative_data;
3645 rb_slow_path_time_histogram_.CreateHistogram(&cumulative_data);
3646 rb_slow_path_time_histogram_.PrintConfidenceIntervals(os, 0.99, cumulative_data);
3647 }
3648 if (rb_slow_path_count_total_ > 0) {
3649 os << "Slow path count " << rb_slow_path_count_total_ << "\n";
3650 }
3651 if (rb_slow_path_count_gc_total_ > 0) {
3652 os << "GC slow path count " << rb_slow_path_count_gc_total_ << "\n";
3653 }
Albert Mingkun Yange260e542018-11-05 13:45:59 +00003654
Albert Mingkun Yangaf9cce12018-11-07 09:58:35 +00003655 os << "Average " << (young_gen_ ? "minor" : "major") << " GC reclaim bytes ratio "
3656 << (reclaimed_bytes_ratio_sum_ / num_gc_cycles) << " over " << num_gc_cycles
3657 << " GC cycles\n";
3658
3659 os << "Average " << (young_gen_ ? "minor" : "major") << " GC copied live bytes ratio "
3660 << (copied_live_bytes_ratio_sum_ / gc_count_) << " over " << gc_count_
3661 << " " << (young_gen_ ? "minor" : "major") << " GCs\n";
3662
Orion Hodson88591fe2018-03-06 13:35:43 +00003663 os << "Cumulative bytes moved "
3664 << cumulative_bytes_moved_.load(std::memory_order_relaxed) << "\n";
3665 os << "Cumulative objects moved "
3666 << cumulative_objects_moved_.load(std::memory_order_relaxed) << "\n";
Lokesh Gidra29895822017-12-15 15:37:40 -08003667
3668 os << "Peak regions allocated "
Lokesh Gidrab4f15412018-01-05 18:29:34 -08003669 << region_space_->GetMaxPeakNumNonFreeRegions() << " ("
3670 << PrettySize(region_space_->GetMaxPeakNumNonFreeRegions() * space::RegionSpace::kRegionSize)
3671 << ") / " << region_space_->GetNumRegions() / 2 << " ("
3672 << PrettySize(region_space_->GetNumRegions() * space::RegionSpace::kRegionSize / 2)
Lokesh Gidra29895822017-12-15 15:37:40 -08003673 << ")\n";
Mathieu Chartier56fe2582016-07-14 13:30:03 -07003674}
3675
Hiroshi Yamauchid5307ec2014-03-27 21:07:51 -07003676} // namespace collector
3677} // namespace gc
3678} // namespace art