blob: 3ac2486db46c05750c0a293fd48fd201babf2716 [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),
Mathieu Chartier8d1a9962016-08-17 16:39:45 -070096 young_gen_(young_gen),
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080097 skipped_blocks_lock_("concurrent copying bytes blocks lock", kMarkSweepMarkStackLock),
Mathieu Chartier56fe2582016-07-14 13:30:03 -070098 measure_read_barrier_slow_path_(measure_read_barrier_slow_path),
Andreas Gamped9911ee2017-03-27 13:27:24 -070099 mark_from_read_barrier_measurements_(false),
Mathieu Chartier56fe2582016-07-14 13:30:03 -0700100 rb_slow_path_ns_(0),
101 rb_slow_path_count_(0),
102 rb_slow_path_count_gc_(0),
103 rb_slow_path_histogram_lock_("Read barrier histogram lock"),
104 rb_slow_path_time_histogram_("Mutator time in read barrier slow path", 500, 32),
105 rb_slow_path_count_total_(0),
106 rb_slow_path_count_gc_total_(0),
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800107 rb_table_(heap_->GetReadBarrierTable()),
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700108 force_evacuate_all_(false),
Andreas Gamped9911ee2017-03-27 13:27:24 -0700109 gc_grays_immune_objects_(false),
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700110 immune_gray_stack_lock_("concurrent copying immune gray stack lock",
111 kMarkSweepMarkStackLock) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800112 static_assert(space::RegionSpace::kRegionSize == accounting::ReadBarrierTable::kRegionSize,
113 "The region space size and the read barrier table region size must match");
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700114 CHECK(kEnableGenerationalConcurrentCopyingCollection || !young_gen_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700115 Thread* self = Thread::Current();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800116 {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800117 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
118 // Cache this so that we won't have to lock heap_bitmap_lock_ in
119 // Mark() which could cause a nested lock on heap_bitmap_lock_
120 // when GC causes a RB while doing GC or a lock order violation
121 // (class_linker_lock_ and heap_bitmap_lock_).
122 heap_mark_bitmap_ = heap->GetMarkBitmap();
123 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700124 {
125 MutexLock mu(self, mark_stack_lock_);
126 for (size_t i = 0; i < kMarkStackPoolSize; ++i) {
127 accounting::AtomicStack<mirror::Object>* mark_stack =
128 accounting::AtomicStack<mirror::Object>::Create(
129 "thread local mark stack", kMarkStackSize, kMarkStackSize);
130 pooled_mark_stacks_.push_back(mark_stack);
131 }
132 }
Roland Levillainb1e1dc32018-07-10 19:19:31 +0100133 if (kEnableGenerationalConcurrentCopyingCollection) {
134 // Allocate sweep array free buffer.
135 std::string error_msg;
136 sweep_array_free_buffer_mem_map_ = MemMap::MapAnonymous(
137 "concurrent copying sweep array free buffer",
138 /* addr */ nullptr,
139 RoundUp(kSweepArrayChunkFreeSize * sizeof(mirror::Object*), kPageSize),
140 PROT_READ | PROT_WRITE,
141 /* low_4gb */ false,
Roland Levillainb1e1dc32018-07-10 19:19:31 +0100142 &error_msg);
143 CHECK(sweep_array_free_buffer_mem_map_.IsValid())
144 << "Couldn't allocate sweep array free buffer: " << error_msg;
145 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800146}
147
Hiroshi Yamauchi057d9772017-02-17 15:33:23 -0800148void ConcurrentCopying::MarkHeapReference(mirror::HeapReference<mirror::Object>* field,
149 bool do_atomic_update) {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -0800150 Thread* const self = Thread::Current();
Hiroshi Yamauchi057d9772017-02-17 15:33:23 -0800151 if (UNLIKELY(do_atomic_update)) {
152 // Used to mark the referent in DelayReferenceReferent in transaction mode.
153 mirror::Object* from_ref = field->AsMirrorPtr();
154 if (from_ref == nullptr) {
155 return;
156 }
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -0800157 mirror::Object* to_ref = Mark(self, from_ref);
Hiroshi Yamauchi057d9772017-02-17 15:33:23 -0800158 if (from_ref != to_ref) {
159 do {
160 if (field->AsMirrorPtr() != from_ref) {
161 // Concurrently overwritten by a mutator.
162 break;
163 }
164 } while (!field->CasWeakRelaxed(from_ref, to_ref));
165 }
166 } else {
167 // Used for preserving soft references, should be OK to not have a CAS here since there should be
168 // no other threads which can trigger read barriers on the same referent during reference
169 // processing.
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -0800170 field->Assign(Mark(self, field->AsMirrorPtr()));
Hiroshi Yamauchi057d9772017-02-17 15:33:23 -0800171 }
Mathieu Chartier97509952015-07-13 14:35:43 -0700172}
173
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800174ConcurrentCopying::~ConcurrentCopying() {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700175 STLDeleteElements(&pooled_mark_stacks_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800176}
177
178void ConcurrentCopying::RunPhases() {
179 CHECK(kUseBakerReadBarrier || kUseTableLookupReadBarrier);
180 CHECK(!is_active_);
181 is_active_ = true;
182 Thread* self = Thread::Current();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700183 thread_running_gc_ = self;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800184 Locks::mutator_lock_->AssertNotHeld(self);
185 {
186 ReaderMutexLock mu(self, *Locks::mutator_lock_);
187 InitializePhase();
188 }
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700189 if (kUseBakerReadBarrier && kGrayDirtyImmuneObjects) {
190 // Switch to read barrier mark entrypoints before we gray the objects. This is required in case
Roland Levillain97c46462017-05-11 14:04:03 +0100191 // a mutator sees a gray bit and dispatches on the entrypoint. (b/37876887).
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700192 ActivateReadBarrierEntrypoints();
193 // Gray dirty immune objects concurrently to reduce GC pause times. We re-process gray cards in
194 // the pause.
195 ReaderMutexLock mu(self, *Locks::mutator_lock_);
196 GrayAllDirtyImmuneObjects();
197 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800198 FlipThreadRoots();
199 {
200 ReaderMutexLock mu(self, *Locks::mutator_lock_);
201 MarkingPhase();
202 }
203 // Verify no from space refs. This causes a pause.
Andreas Gampee3ce7872017-02-22 13:36:21 -0800204 if (kEnableNoFromSpaceRefsVerification) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800205 TimingLogger::ScopedTiming split("(Paused)VerifyNoFromSpaceReferences", GetTimings());
Andreas Gampe4934eb12017-01-30 13:15:26 -0800206 ScopedPause pause(this, false);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700207 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800208 if (kVerboseMode) {
209 LOG(INFO) << "Verifying no from-space refs";
210 }
211 VerifyNoFromSpaceReferences();
Mathieu Chartier720e71a2015-04-06 17:10:58 -0700212 if (kVerboseMode) {
213 LOG(INFO) << "Done verifying no from-space refs";
214 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700215 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800216 }
217 {
218 ReaderMutexLock mu(self, *Locks::mutator_lock_);
219 ReclaimPhase();
220 }
221 FinishPhase();
222 CHECK(is_active_);
223 is_active_ = false;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700224 thread_running_gc_ = nullptr;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800225}
226
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700227class ConcurrentCopying::ActivateReadBarrierEntrypointsCheckpoint : public Closure {
228 public:
229 explicit ActivateReadBarrierEntrypointsCheckpoint(ConcurrentCopying* concurrent_copying)
230 : concurrent_copying_(concurrent_copying) {}
231
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100232 void Run(Thread* thread) override NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700233 // Note: self is not necessarily equal to thread since thread may be suspended.
234 Thread* self = Thread::Current();
235 DCHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
236 << thread->GetState() << " thread " << thread << " self " << self;
237 // Switch to the read barrier entrypoints.
238 thread->SetReadBarrierEntrypoints();
239 // If thread is a running mutator, then act on behalf of the garbage collector.
240 // See the code in ThreadList::RunCheckpoint.
241 concurrent_copying_->GetBarrier().Pass(self);
242 }
243
244 private:
245 ConcurrentCopying* const concurrent_copying_;
246};
247
248class ConcurrentCopying::ActivateReadBarrierEntrypointsCallback : public Closure {
249 public:
250 explicit ActivateReadBarrierEntrypointsCallback(ConcurrentCopying* concurrent_copying)
251 : concurrent_copying_(concurrent_copying) {}
252
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100253 void Run(Thread* self ATTRIBUTE_UNUSED) override REQUIRES(Locks::thread_list_lock_) {
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700254 // This needs to run under the thread_list_lock_ critical section in ThreadList::RunCheckpoint()
255 // to avoid a race with ThreadList::Register().
256 CHECK(!concurrent_copying_->is_using_read_barrier_entrypoints_);
257 concurrent_copying_->is_using_read_barrier_entrypoints_ = true;
258 }
259
260 private:
261 ConcurrentCopying* const concurrent_copying_;
262};
263
264void ConcurrentCopying::ActivateReadBarrierEntrypoints() {
265 Thread* const self = Thread::Current();
266 ActivateReadBarrierEntrypointsCheckpoint checkpoint(this);
267 ThreadList* thread_list = Runtime::Current()->GetThreadList();
268 gc_barrier_->Init(self, 0);
269 ActivateReadBarrierEntrypointsCallback callback(this);
270 const size_t barrier_count = thread_list->RunCheckpoint(&checkpoint, &callback);
271 // If there are no threads to wait which implies that all the checkpoint functions are finished,
272 // then no need to release the mutator lock.
273 if (barrier_count == 0) {
274 return;
275 }
276 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
277 gc_barrier_->Increment(self, barrier_count);
278}
279
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800280void ConcurrentCopying::BindBitmaps() {
281 Thread* self = Thread::Current();
282 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
283 // Mark all of the spaces we never collect as immune.
284 for (const auto& space : heap_->GetContinuousSpaces()) {
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800285 if (space->GetGcRetentionPolicy() == space::kGcRetentionPolicyNeverCollect ||
286 space->GetGcRetentionPolicy() == space::kGcRetentionPolicyFullCollect) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800287 CHECK(space->IsZygoteSpace() || space->IsImageSpace());
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800288 immune_spaces_.AddSpace(space);
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700289 } else {
290 CHECK(!space->IsZygoteSpace());
291 CHECK(!space->IsImageSpace());
292 if (kEnableGenerationalConcurrentCopyingCollection) {
293 if (space == region_space_) {
294 region_space_bitmap_ = region_space_->GetMarkBitmap();
295 } else if (young_gen_ && space->IsContinuousMemMapAllocSpace()) {
296 DCHECK_EQ(space->GetGcRetentionPolicy(), space::kGcRetentionPolicyAlwaysCollect);
297 space->AsContinuousMemMapAllocSpace()->BindLiveToMarkBitmap();
298 }
299 // Age all of the cards for the region space so that we know which evac regions to scan.
300 Runtime::Current()->GetHeap()->GetCardTable()->ModifyCardsAtomic(
301 space->Begin(),
302 space->End(),
303 AgeCardVisitor(),
304 VoidFunctor());
305 } else {
306 if (space == region_space_) {
307 // It is OK to clear the bitmap with mutators running since the only place it is read is
308 // VisitObjects which has exclusion with CC.
309 region_space_bitmap_ = region_space_->GetMarkBitmap();
310 region_space_bitmap_->Clear();
311 }
312 }
313 }
314 }
315 if (kEnableGenerationalConcurrentCopyingCollection && young_gen_) {
316 for (const auto& space : GetHeap()->GetDiscontinuousSpaces()) {
317 CHECK(space->IsLargeObjectSpace());
318 space->AsLargeObjectSpace()->CopyLiveToMarked();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800319 }
320 }
321}
322
323void ConcurrentCopying::InitializePhase() {
324 TimingLogger::ScopedTiming split("InitializePhase", GetTimings());
325 if (kVerboseMode) {
326 LOG(INFO) << "GC InitializePhase";
327 LOG(INFO) << "Region-space : " << reinterpret_cast<void*>(region_space_->Begin()) << "-"
328 << reinterpret_cast<void*>(region_space_->Limit());
329 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700330 CheckEmptyMarkStack();
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800331 if (kIsDebugBuild) {
332 MutexLock mu(Thread::Current(), mark_stack_lock_);
333 CHECK(false_gray_stack_.empty());
334 }
Mathieu Chartier56fe2582016-07-14 13:30:03 -0700335
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700336 rb_mark_bit_stack_full_ = false;
Mathieu Chartier56fe2582016-07-14 13:30:03 -0700337 mark_from_read_barrier_measurements_ = measure_read_barrier_slow_path_;
338 if (measure_read_barrier_slow_path_) {
Orion Hodson88591fe2018-03-06 13:35:43 +0000339 rb_slow_path_ns_.store(0, std::memory_order_relaxed);
340 rb_slow_path_count_.store(0, std::memory_order_relaxed);
341 rb_slow_path_count_gc_.store(0, std::memory_order_relaxed);
Mathieu Chartier56fe2582016-07-14 13:30:03 -0700342 }
343
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800344 immune_spaces_.Reset();
Orion Hodson88591fe2018-03-06 13:35:43 +0000345 bytes_moved_.store(0, std::memory_order_relaxed);
346 objects_moved_.store(0, std::memory_order_relaxed);
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -0800347 bytes_moved_gc_thread_ = 0;
348 objects_moved_gc_thread_ = 0;
Hiroshi Yamauchi60985b72016-08-24 13:53:12 -0700349 GcCause gc_cause = GetCurrentIteration()->GetGcCause();
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700350
351 force_evacuate_all_ = false;
352 if (!kEnableGenerationalConcurrentCopyingCollection || !young_gen_) {
353 if (gc_cause == kGcCauseExplicit ||
354 gc_cause == kGcCauseCollectorTransition ||
355 GetCurrentIteration()->GetClearSoftReferences()) {
356 force_evacuate_all_ = true;
357 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800358 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700359 if (kUseBakerReadBarrier) {
Orion Hodson88591fe2018-03-06 13:35:43 +0000360 updated_all_immune_objects_.store(false, std::memory_order_relaxed);
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700361 // GC may gray immune objects in the thread flip.
362 gc_grays_immune_objects_ = true;
363 if (kIsDebugBuild) {
364 MutexLock mu(Thread::Current(), immune_gray_stack_lock_);
365 DCHECK(immune_gray_stack_.empty());
366 }
367 }
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700368 if (kEnableGenerationalConcurrentCopyingCollection) {
Roland Levillain2d94e292018-08-15 16:46:30 +0100369 done_scanning_.store(false, std::memory_order_release);
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700370 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800371 BindBitmaps();
372 if (kVerboseMode) {
Roland Levillain57ce0542018-08-07 16:20:31 +0100373 LOG(INFO) << "young_gen=" << std::boolalpha << young_gen_ << std::noboolalpha;
374 LOG(INFO) << "force_evacuate_all=" << std::boolalpha << force_evacuate_all_ << std::noboolalpha;
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800375 LOG(INFO) << "Largest immune region: " << immune_spaces_.GetLargestImmuneRegion().Begin()
376 << "-" << immune_spaces_.GetLargestImmuneRegion().End();
377 for (space::ContinuousSpace* space : immune_spaces_.GetSpaces()) {
378 LOG(INFO) << "Immune space: " << *space;
379 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800380 LOG(INFO) << "GC end of InitializePhase";
381 }
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700382 if (kEnableGenerationalConcurrentCopyingCollection && !young_gen_) {
383 region_space_bitmap_->Clear();
384 }
Mathieu Chartier962cd7a2016-08-16 12:15:59 -0700385 // Mark all of the zygote large objects without graying them.
386 MarkZygoteLargeObjects();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800387}
388
389// Used to switch the thread roots of a thread from from-space refs to to-space refs.
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700390class ConcurrentCopying::ThreadFlipVisitor : public Closure, public RootVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800391 public:
Roland Levillain3887c462015-08-12 18:15:42 +0100392 ThreadFlipVisitor(ConcurrentCopying* concurrent_copying, bool use_tlab)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800393 : concurrent_copying_(concurrent_copying), use_tlab_(use_tlab) {
394 }
395
Roland Levillainf73caca2018-08-24 17:19:07 +0100396 void Run(Thread* thread) override REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800397 // Note: self is not necessarily equal to thread since thread may be suspended.
398 Thread* self = Thread::Current();
399 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
400 << thread->GetState() << " thread " << thread << " self " << self;
Mathieu Chartierfe814e82016-11-09 14:32:49 -0800401 thread->SetIsGcMarkingAndUpdateEntrypoints(true);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800402 if (use_tlab_ && thread->HasTlab()) {
403 if (ConcurrentCopying::kEnableFromSpaceAccountingCheck) {
404 // This must come before the revoke.
405 size_t thread_local_objects = thread->GetThreadLocalObjectsAllocated();
406 concurrent_copying_->region_space_->RevokeThreadLocalBuffers(thread);
Roland Levillain2ae376f2018-01-30 11:35:11 +0000407 reinterpret_cast<Atomic<size_t>*>(
408 &concurrent_copying_->from_space_num_objects_at_first_pause_)->
Orion Hodson88591fe2018-03-06 13:35:43 +0000409 fetch_add(thread_local_objects, std::memory_order_seq_cst);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800410 } else {
411 concurrent_copying_->region_space_->RevokeThreadLocalBuffers(thread);
412 }
413 }
414 if (kUseThreadLocalAllocationStack) {
415 thread->RevokeThreadLocalAllocationStack();
416 }
417 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700418 // We can use the non-CAS VisitRoots functions below because we update thread-local GC roots
419 // only.
Andreas Gampe513061a2017-06-01 09:17:34 -0700420 thread->VisitRoots(this, kVisitRootFlagAllRoots);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800421 concurrent_copying_->GetBarrier().Pass(self);
422 }
423
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700424 void VisitRoots(mirror::Object*** roots,
425 size_t count,
426 const RootInfo& info ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700427 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -0800428 Thread* self = Thread::Current();
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700429 for (size_t i = 0; i < count; ++i) {
430 mirror::Object** root = roots[i];
431 mirror::Object* ref = *root;
432 if (ref != nullptr) {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -0800433 mirror::Object* to_ref = concurrent_copying_->Mark(self, ref);
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700434 if (to_ref != ref) {
435 *root = to_ref;
436 }
437 }
438 }
439 }
440
441 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots,
442 size_t count,
443 const RootInfo& info ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700444 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -0800445 Thread* self = Thread::Current();
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700446 for (size_t i = 0; i < count; ++i) {
447 mirror::CompressedReference<mirror::Object>* const root = roots[i];
448 if (!root->IsNull()) {
449 mirror::Object* ref = root->AsMirrorPtr();
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -0800450 mirror::Object* to_ref = concurrent_copying_->Mark(self, ref);
Hiroshi Yamauchi7e9b2572016-07-20 20:25:27 -0700451 if (to_ref != ref) {
452 root->Assign(to_ref);
453 }
454 }
455 }
456 }
457
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800458 private:
459 ConcurrentCopying* const concurrent_copying_;
460 const bool use_tlab_;
461};
462
463// Called back from Runtime::FlipThreadRoots() during a pause.
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700464class ConcurrentCopying::FlipCallback : public Closure {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800465 public:
466 explicit FlipCallback(ConcurrentCopying* concurrent_copying)
467 : concurrent_copying_(concurrent_copying) {
468 }
469
Roland Levillainf73caca2018-08-24 17:19:07 +0100470 void Run(Thread* thread) override REQUIRES(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800471 ConcurrentCopying* cc = concurrent_copying_;
472 TimingLogger::ScopedTiming split("(Paused)FlipCallback", cc->GetTimings());
473 // Note: self is not necessarily equal to thread since thread may be suspended.
474 Thread* self = Thread::Current();
Mathieu Chartiera1467d02017-02-22 09:22:50 -0800475 if (kVerifyNoMissingCardMarks) {
476 cc->VerifyNoMissingCardMarks();
477 }
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700478 CHECK_EQ(thread, self);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800479 Locks::mutator_lock_->AssertExclusiveHeld(self);
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700480 space::RegionSpace::EvacMode evac_mode = space::RegionSpace::kEvacModeLivePercentNewlyAllocated;
481 if (cc->young_gen_) {
482 CHECK(!cc->force_evacuate_all_);
483 evac_mode = space::RegionSpace::kEvacModeNewlyAllocated;
484 } else if (cc->force_evacuate_all_) {
485 evac_mode = space::RegionSpace::kEvacModeForceAll;
486 }
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700487 {
488 TimingLogger::ScopedTiming split2("(Paused)SetFromSpace", cc->GetTimings());
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700489 // Only change live bytes for full CC.
490 cc->region_space_->SetFromSpace(
491 cc->rb_table_, evac_mode, /*clear_live_bytes*/ !cc->young_gen_);
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700492 }
Mathieu Chartiera4f6af92015-08-11 17:35:25 -0700493 cc->SwapStacks();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800494 if (ConcurrentCopying::kEnableFromSpaceAccountingCheck) {
495 cc->RecordLiveStackFreezeSize(self);
496 cc->from_space_num_objects_at_first_pause_ = cc->region_space_->GetObjectsAllocated();
497 cc->from_space_num_bytes_at_first_pause_ = cc->region_space_->GetBytesAllocated();
498 }
499 cc->is_marking_ = true;
Orion Hodson88591fe2018-03-06 13:35:43 +0000500 cc->mark_stack_mode_.store(ConcurrentCopying::kMarkStackModeThreadLocal,
501 std::memory_order_relaxed);
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700502 if (kIsDebugBuild && !cc->young_gen_) {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -0800503 cc->region_space_->AssertAllRegionLiveBytesZeroOrCleared();
504 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800505 if (UNLIKELY(Runtime::Current()->IsActiveTransaction())) {
Mathieu Chartier184c9dc2015-03-05 13:20:54 -0800506 CHECK(Runtime::Current()->IsAotCompiler());
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700507 TimingLogger::ScopedTiming split3("(Paused)VisitTransactionRoots", cc->GetTimings());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700508 Runtime::Current()->VisitTransactionRoots(cc);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800509 }
Mathieu Chartier21328a12016-07-22 10:47:45 -0700510 if (kUseBakerReadBarrier && kGrayDirtyImmuneObjects) {
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700511 cc->GrayAllNewlyDirtyImmuneObjects();
Mathieu Chartier21328a12016-07-22 10:47:45 -0700512 if (kIsDebugBuild) {
Roland Levillain001eff92018-01-24 14:24:33 +0000513 // Check that all non-gray immune objects only reference immune objects.
Mathieu Chartier21328a12016-07-22 10:47:45 -0700514 cc->VerifyGrayImmuneObjects();
515 }
516 }
Mathieu Chartier9aef9922017-04-23 13:53:50 -0700517 // May be null during runtime creation, in this case leave java_lang_Object null.
518 // This is safe since single threaded behavior should mean FillDummyObject does not
519 // happen when java_lang_Object_ is null.
520 if (WellKnownClasses::java_lang_Object != nullptr) {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -0800521 cc->java_lang_Object_ = down_cast<mirror::Class*>(cc->Mark(thread,
Mathieu Chartier9aef9922017-04-23 13:53:50 -0700522 WellKnownClasses::ToClass(WellKnownClasses::java_lang_Object).Ptr()));
523 } else {
524 cc->java_lang_Object_ = nullptr;
525 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800526 }
527
528 private:
529 ConcurrentCopying* const concurrent_copying_;
530};
531
Mathieu Chartier21328a12016-07-22 10:47:45 -0700532class ConcurrentCopying::VerifyGrayImmuneObjectsVisitor {
533 public:
534 explicit VerifyGrayImmuneObjectsVisitor(ConcurrentCopying* collector)
535 : collector_(collector) {}
536
Mathieu Chartier31e88222016-10-14 18:43:19 -0700537 void operator()(ObjPtr<mirror::Object> obj, MemberOffset offset, bool /* is_static */)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700538 const ALWAYS_INLINE REQUIRES_SHARED(Locks::mutator_lock_)
539 REQUIRES_SHARED(Locks::heap_bitmap_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700540 CheckReference(obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(offset),
541 obj, offset);
542 }
543
Mathieu Chartier31e88222016-10-14 18:43:19 -0700544 void operator()(ObjPtr<mirror::Class> klass, ObjPtr<mirror::Reference> ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700545 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700546 CHECK(klass->IsTypeOfReferenceClass());
547 CheckReference(ref->GetReferent<kWithoutReadBarrier>(),
548 ref,
549 mirror::Reference::ReferentOffset());
550 }
551
552 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
553 ALWAYS_INLINE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700554 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700555 if (!root->IsNull()) {
556 VisitRoot(root);
557 }
558 }
559
560 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
561 ALWAYS_INLINE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700562 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700563 CheckReference(root->AsMirrorPtr(), nullptr, MemberOffset(0));
564 }
565
566 private:
567 ConcurrentCopying* const collector_;
568
Mathieu Chartier31e88222016-10-14 18:43:19 -0700569 void CheckReference(ObjPtr<mirror::Object> ref,
570 ObjPtr<mirror::Object> holder,
571 MemberOffset offset) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700572 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700573 if (ref != nullptr) {
Mathieu Chartier31e88222016-10-14 18:43:19 -0700574 if (!collector_->immune_spaces_.ContainsObject(ref.Ptr())) {
Mathieu Chartier962cd7a2016-08-16 12:15:59 -0700575 // Not immune, must be a zygote large object.
576 CHECK(Runtime::Current()->GetHeap()->GetLargeObjectsSpace()->IsZygoteLargeObject(
Mathieu Chartier31e88222016-10-14 18:43:19 -0700577 Thread::Current(), ref.Ptr()))
Mathieu Chartier962cd7a2016-08-16 12:15:59 -0700578 << "Non gray object references non immune, non zygote large object "<< ref << " "
David Sehr709b0702016-10-13 09:12:37 -0700579 << mirror::Object::PrettyTypeOf(ref) << " in holder " << holder << " "
580 << mirror::Object::PrettyTypeOf(holder) << " offset=" << offset.Uint32Value();
Mathieu Chartier962cd7a2016-08-16 12:15:59 -0700581 } else {
582 // Make sure the large object class is immune since we will never scan the large object.
583 CHECK(collector_->immune_spaces_.ContainsObject(
584 ref->GetClass<kVerifyNone, kWithoutReadBarrier>()));
585 }
Mathieu Chartier21328a12016-07-22 10:47:45 -0700586 }
587 }
588};
589
590void ConcurrentCopying::VerifyGrayImmuneObjects() {
591 TimingLogger::ScopedTiming split(__FUNCTION__, GetTimings());
592 for (auto& space : immune_spaces_.GetSpaces()) {
593 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
594 accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
595 VerifyGrayImmuneObjectsVisitor visitor(this);
596 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()),
597 reinterpret_cast<uintptr_t>(space->Limit()),
598 [&visitor](mirror::Object* obj)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700599 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700600 // If an object is not gray, it should only have references to things in the immune spaces.
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700601 if (obj->GetReadBarrierState() != ReadBarrier::GrayState()) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700602 obj->VisitReferences</*kVisitNativeRoots*/true,
603 kDefaultVerifyFlags,
604 kWithoutReadBarrier>(visitor, visitor);
605 }
606 });
607 }
608}
609
Mathieu Chartiera1467d02017-02-22 09:22:50 -0800610class ConcurrentCopying::VerifyNoMissingCardMarkVisitor {
611 public:
612 VerifyNoMissingCardMarkVisitor(ConcurrentCopying* cc, ObjPtr<mirror::Object> holder)
613 : cc_(cc),
614 holder_(holder) {}
615
616 void operator()(ObjPtr<mirror::Object> obj,
617 MemberOffset offset,
618 bool is_static ATTRIBUTE_UNUSED) const
619 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
620 if (offset.Uint32Value() != mirror::Object::ClassOffset().Uint32Value()) {
621 CheckReference(obj->GetFieldObject<mirror::Object, kDefaultVerifyFlags, kWithoutReadBarrier>(
622 offset), offset.Uint32Value());
623 }
624 }
625 void operator()(ObjPtr<mirror::Class> klass,
626 ObjPtr<mirror::Reference> ref) const
627 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
628 CHECK(klass->IsTypeOfReferenceClass());
629 this->operator()(ref, mirror::Reference::ReferentOffset(), false);
630 }
631
632 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
633 REQUIRES_SHARED(Locks::mutator_lock_) {
634 if (!root->IsNull()) {
635 VisitRoot(root);
636 }
637 }
638
639 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
640 REQUIRES_SHARED(Locks::mutator_lock_) {
641 CheckReference(root->AsMirrorPtr());
642 }
643
644 void CheckReference(mirror::Object* ref, int32_t offset = -1) const
645 REQUIRES_SHARED(Locks::mutator_lock_) {
646 CHECK(ref == nullptr || !cc_->region_space_->IsInNewlyAllocatedRegion(ref))
647 << holder_->PrettyTypeOf() << "(" << holder_.Ptr() << ") references object "
648 << ref->PrettyTypeOf() << "(" << ref << ") in newly allocated region at offset=" << offset;
649 }
650
651 private:
652 ConcurrentCopying* const cc_;
653 ObjPtr<mirror::Object> const holder_;
654};
655
Mathieu Chartiera1467d02017-02-22 09:22:50 -0800656void ConcurrentCopying::VerifyNoMissingCardMarks() {
Andreas Gampe0c183382017-07-13 22:26:24 -0700657 auto visitor = [&](mirror::Object* obj)
658 REQUIRES(Locks::mutator_lock_)
659 REQUIRES(!mark_stack_lock_) {
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700660 // Objects on clean cards should never have references to newly allocated regions. Note
661 // that aged cards are also not clean.
Andreas Gampe0c183382017-07-13 22:26:24 -0700662 if (heap_->GetCardTable()->GetCard(obj) == gc::accounting::CardTable::kCardClean) {
663 VerifyNoMissingCardMarkVisitor internal_visitor(this, /*holder*/ obj);
664 obj->VisitReferences</*kVisitNativeRoots*/true, kVerifyNone, kWithoutReadBarrier>(
665 internal_visitor, internal_visitor);
666 }
667 };
Mathieu Chartiera1467d02017-02-22 09:22:50 -0800668 TimingLogger::ScopedTiming split(__FUNCTION__, GetTimings());
Andreas Gampe0c183382017-07-13 22:26:24 -0700669 region_space_->Walk(visitor);
Mathieu Chartiera1467d02017-02-22 09:22:50 -0800670 {
671 ReaderMutexLock rmu(Thread::Current(), *Locks::heap_bitmap_lock_);
Andreas Gampe0c183382017-07-13 22:26:24 -0700672 heap_->GetLiveBitmap()->Visit(visitor);
Mathieu Chartiera1467d02017-02-22 09:22:50 -0800673 }
674}
675
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800676// Switch threads that from from-space to to-space refs. Forward/mark the thread roots.
677void ConcurrentCopying::FlipThreadRoots() {
678 TimingLogger::ScopedTiming split("FlipThreadRoots", GetTimings());
679 if (kVerboseMode) {
680 LOG(INFO) << "time=" << region_space_->Time();
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700681 region_space_->DumpNonFreeRegions(LOG_STREAM(INFO));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800682 }
683 Thread* self = Thread::Current();
684 Locks::mutator_lock_->AssertNotHeld(self);
685 gc_barrier_->Init(self, 0);
686 ThreadFlipVisitor thread_flip_visitor(this, heap_->use_tlab_);
687 FlipCallback flip_callback(this);
Andreas Gampe4934eb12017-01-30 13:15:26 -0800688
Andreas Gampe6e644452017-05-09 16:30:27 -0700689 size_t barrier_count = Runtime::Current()->GetThreadList()->FlipThreadRoots(
690 &thread_flip_visitor, &flip_callback, this, GetHeap()->GetGcPauseListener());
Andreas Gampe4934eb12017-01-30 13:15:26 -0800691
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800692 {
693 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
694 gc_barrier_->Increment(self, barrier_count);
695 }
696 is_asserting_to_space_invariant_ = true;
697 QuasiAtomic::ThreadFenceForConstructor();
698 if (kVerboseMode) {
699 LOG(INFO) << "time=" << region_space_->Time();
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700700 region_space_->DumpNonFreeRegions(LOG_STREAM(INFO));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800701 LOG(INFO) << "GC end of FlipThreadRoots";
702 }
703}
704
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700705template <bool kConcurrent>
Mathieu Chartier21328a12016-07-22 10:47:45 -0700706class ConcurrentCopying::GrayImmuneObjectVisitor {
707 public:
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700708 explicit GrayImmuneObjectVisitor(Thread* self) : self_(self) {}
Mathieu Chartier21328a12016-07-22 10:47:45 -0700709
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700710 ALWAYS_INLINE void operator()(mirror::Object* obj) const REQUIRES_SHARED(Locks::mutator_lock_) {
Roland Levillain14e5a292018-06-28 12:00:56 +0100711 if (kUseBakerReadBarrier && obj->GetReadBarrierState() == ReadBarrier::NonGrayState()) {
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700712 if (kConcurrent) {
713 Locks::mutator_lock_->AssertSharedHeld(self_);
Roland Levillain14e5a292018-06-28 12:00:56 +0100714 obj->AtomicSetReadBarrierState(ReadBarrier::NonGrayState(), ReadBarrier::GrayState());
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700715 // Mod union table VisitObjects may visit the same object multiple times so we can't check
716 // the result of the atomic set.
717 } else {
718 Locks::mutator_lock_->AssertExclusiveHeld(self_);
719 obj->SetReadBarrierState(ReadBarrier::GrayState());
Mathieu Chartier21328a12016-07-22 10:47:45 -0700720 }
Mathieu Chartier21328a12016-07-22 10:47:45 -0700721 }
722 }
723
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700724 static void Callback(mirror::Object* obj, void* arg) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700725 reinterpret_cast<GrayImmuneObjectVisitor<kConcurrent>*>(arg)->operator()(obj);
Mathieu Chartier21328a12016-07-22 10:47:45 -0700726 }
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700727
728 private:
729 Thread* const self_;
Mathieu Chartier21328a12016-07-22 10:47:45 -0700730};
731
732void ConcurrentCopying::GrayAllDirtyImmuneObjects() {
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700733 TimingLogger::ScopedTiming split("GrayAllDirtyImmuneObjects", GetTimings());
734 accounting::CardTable* const card_table = heap_->GetCardTable();
735 Thread* const self = Thread::Current();
736 using VisitorType = GrayImmuneObjectVisitor</* kIsConcurrent */ true>;
737 VisitorType visitor(self);
738 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier21328a12016-07-22 10:47:45 -0700739 for (space::ContinuousSpace* space : immune_spaces_.GetSpaces()) {
740 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700741 accounting::ModUnionTable* table = heap_->FindModUnionTableFromSpace(space);
Mathieu Chartier21328a12016-07-22 10:47:45 -0700742 // Mark all the objects on dirty cards since these may point to objects in other space.
743 // Once these are marked, the GC will eventually clear them later.
744 // Table is non null for boot image and zygote spaces. It is only null for application image
745 // spaces.
746 if (table != nullptr) {
Mathieu Chartier6e6078a2016-10-24 15:45:41 -0700747 table->ProcessCards();
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700748 table->VisitObjects(&VisitorType::Callback, &visitor);
749 // Don't clear cards here since we need to rescan in the pause. If we cleared the cards here,
750 // there would be races with the mutator marking new cards.
751 } else {
752 // Keep cards aged if we don't have a mod-union table since we may need to scan them in future
753 // GCs. This case is for app images.
754 card_table->ModifyCardsAtomic(
755 space->Begin(),
756 space->End(),
757 [](uint8_t card) {
758 return (card != gc::accounting::CardTable::kCardClean)
759 ? gc::accounting::CardTable::kCardAged
760 : card;
761 },
762 /* card modified visitor */ VoidFunctor());
763 card_table->Scan</* kClearCard */ false>(space->GetMarkBitmap(),
764 space->Begin(),
765 space->End(),
766 visitor,
767 gc::accounting::CardTable::kCardAged);
768 }
769 }
770}
771
772void ConcurrentCopying::GrayAllNewlyDirtyImmuneObjects() {
773 TimingLogger::ScopedTiming split("(Paused)GrayAllNewlyDirtyImmuneObjects", GetTimings());
774 accounting::CardTable* const card_table = heap_->GetCardTable();
775 using VisitorType = GrayImmuneObjectVisitor</* kIsConcurrent */ false>;
776 Thread* const self = Thread::Current();
777 VisitorType visitor(self);
778 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
779 for (space::ContinuousSpace* space : immune_spaces_.GetSpaces()) {
780 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
781 accounting::ModUnionTable* table = heap_->FindModUnionTableFromSpace(space);
782
783 // Don't need to scan aged cards since we did these before the pause. Note that scanning cards
784 // also handles the mod-union table cards.
785 card_table->Scan</* kClearCard */ false>(space->GetMarkBitmap(),
786 space->Begin(),
787 space->End(),
788 visitor,
789 gc::accounting::CardTable::kCardDirty);
790 if (table != nullptr) {
791 // Add the cards to the mod-union table so that we can clear cards to save RAM.
792 table->ProcessCards();
Mathieu Chartier6e6078a2016-10-24 15:45:41 -0700793 TimingLogger::ScopedTiming split2("(Paused)ClearCards", GetTimings());
794 card_table->ClearCardRange(space->Begin(),
795 AlignDown(space->End(), accounting::CardTable::kCardSize));
Mathieu Chartier21328a12016-07-22 10:47:45 -0700796 }
797 }
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700798 // 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 -0700799 // barriers in the immune spaces.
Orion Hodson88591fe2018-03-06 13:35:43 +0000800 updated_all_immune_objects_.store(true, std::memory_order_relaxed);
Mathieu Chartier21328a12016-07-22 10:47:45 -0700801}
802
Mathieu Chartiera4f6af92015-08-11 17:35:25 -0700803void ConcurrentCopying::SwapStacks() {
804 heap_->SwapStacks();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800805}
806
807void ConcurrentCopying::RecordLiveStackFreezeSize(Thread* self) {
808 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
809 live_stack_freeze_size_ = heap_->GetLiveStack()->Size();
810}
811
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700812// Used to visit objects in the immune spaces.
813inline void ConcurrentCopying::ScanImmuneObject(mirror::Object* obj) {
814 DCHECK(obj != nullptr);
815 DCHECK(immune_spaces_.ContainsObject(obj));
816 // Update the fields without graying it or pushing it onto the mark stack.
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700817 if (kEnableGenerationalConcurrentCopyingCollection && young_gen_) {
818 // Young GC does not care about references to unevac space. It is safe to not gray these as
819 // long as scan immune objects happens after scanning the dirty cards.
820 Scan<true>(obj);
821 } else {
822 Scan<false>(obj);
823 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700824}
825
826class ConcurrentCopying::ImmuneSpaceScanObjVisitor {
827 public:
828 explicit ImmuneSpaceScanObjVisitor(ConcurrentCopying* cc)
829 : collector_(cc) {}
830
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700831 ALWAYS_INLINE void operator()(mirror::Object* obj) const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700832 if (kUseBakerReadBarrier && kGrayDirtyImmuneObjects) {
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700833 // Only need to scan gray objects.
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700834 if (obj->GetReadBarrierState() == ReadBarrier::GrayState()) {
Mathieu Chartier21328a12016-07-22 10:47:45 -0700835 collector_->ScanImmuneObject(obj);
Roland Levillain14e5a292018-06-28 12:00:56 +0100836 // Done scanning the object, go back to black (non-gray).
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700837 bool success = obj->AtomicSetReadBarrierState(ReadBarrier::GrayState(),
Roland Levillain14e5a292018-06-28 12:00:56 +0100838 ReadBarrier::NonGrayState());
Mathieu Chartier2af7a3e2017-12-14 18:36:05 -0800839 CHECK(success)
840 << Runtime::Current()->GetHeap()->GetVerification()->DumpObjectInfo(obj, "failed CAS");
Mathieu Chartier21328a12016-07-22 10:47:45 -0700841 }
842 } else {
843 collector_->ScanImmuneObject(obj);
844 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700845 }
846
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700847 static void Callback(mirror::Object* obj, void* arg) REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi5408f232016-07-29 15:07:05 -0700848 reinterpret_cast<ImmuneSpaceScanObjVisitor*>(arg)->operator()(obj);
849 }
850
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700851 private:
852 ConcurrentCopying* const collector_;
853};
854
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800855// Concurrently mark roots that are guarded by read barriers and process the mark stack.
856void ConcurrentCopying::MarkingPhase() {
857 TimingLogger::ScopedTiming split("MarkingPhase", GetTimings());
858 if (kVerboseMode) {
859 LOG(INFO) << "GC MarkingPhase";
860 }
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -0700861 Thread* self = Thread::Current();
862 if (kIsDebugBuild) {
863 MutexLock mu(self, *Locks::thread_list_lock_);
864 CHECK(weak_ref_access_enabled_);
865 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700866
867 // Scan immune spaces.
868 // Update all the fields in the immune spaces first without graying the objects so that we
869 // minimize dirty pages in the immune spaces. Note mutators can concurrently access and gray some
870 // of the objects.
871 if (kUseBakerReadBarrier) {
872 gc_grays_immune_objects_ = false;
Hiroshi Yamauchi16292fc2016-06-20 20:23:34 -0700873 }
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700874 if (kEnableGenerationalConcurrentCopyingCollection && young_gen_) {
Roland Levillain57ce0542018-08-07 16:20:31 +0100875 if (kVerboseMode) {
876 LOG(INFO) << "GC ScanCardsForSpace";
877 }
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700878 TimingLogger::ScopedTiming split2("ScanCardsForSpace", GetTimings());
879 WriterMutexLock rmu(Thread::Current(), *Locks::heap_bitmap_lock_);
Roland Levillain2d94e292018-08-15 16:46:30 +0100880 CHECK(!done_scanning_.load(std::memory_order_relaxed));
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700881 if (kIsDebugBuild) {
882 // Leave some time for mutators to race ahead to try and find races between the GC card
883 // scanning and mutators reading references.
884 usleep(10 * 1000);
885 }
886 for (space::ContinuousSpace* space : GetHeap()->GetContinuousSpaces()) {
887 if (space->IsImageSpace() || space->IsZygoteSpace()) {
888 // Image and zygote spaces are already handled since we gray the objects in the pause.
889 continue;
890 }
891 // Scan all of the objects on dirty cards in unevac from space, and non moving space. These
892 // are from previous GCs and may reference things in the from space.
Roland Levillain4ba92462018-08-15 19:16:24 +0100893 //
894 // Note that we do not need to process the large-object space (the only discontinuous space)
895 // as it contains only large string objects and large primitive array objects, that have no
896 // reference to other objects, except their class. There is no need to scan these large
897 // objects, as the String class and the primitive array classes are expected to never move
898 // during a minor (young-generation) collection:
899 // - In the case where we run with a boot image, these classes are part of the image space,
900 // which is an immune space.
901 // - In the case where we run without a boot image, these classes are allocated in the region
902 // space (main space), but they are not expected to move during a minor collection (this
903 // would only happen if those classes were allocated between a major and a minor
904 // collections, which is unlikely -- we don't expect any GC to happen before these
905 // fundamental classes are initialized). Note that these classes could move during a major
906 // collection though, but this is fine: in that case, the whole heap is traced and the card
907 // table logic below is not used.
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700908 Runtime::Current()->GetHeap()->GetCardTable()->Scan<false>(
909 space->GetMarkBitmap(),
910 space->Begin(),
911 space->End(),
912 [this, space](mirror::Object* obj)
913 REQUIRES(Locks::heap_bitmap_lock_)
914 REQUIRES_SHARED(Locks::mutator_lock_) {
915 // Don't push or gray unevac refs.
916 if (kIsDebugBuild && space == region_space_) {
917 // We may get unevac large objects.
918 if (!region_space_->IsInUnevacFromSpace(obj)) {
919 CHECK(region_space_bitmap_->Test(obj));
920 region_space_->DumpRegionForObject(LOG_STREAM(FATAL_WITHOUT_ABORT), obj);
921 LOG(FATAL) << "Scanning " << obj << " not in unevac space";
922 }
923 }
924 Scan<true>(obj);
925 },
926 accounting::CardTable::kCardDirty - 1);
927 }
928 // Done scanning unevac space.
Roland Levillain2d94e292018-08-15 16:46:30 +0100929 done_scanning_.store(true, std::memory_order_release);
Roland Levillain57ce0542018-08-07 16:20:31 +0100930 if (kVerboseMode) {
931 LOG(INFO) << "GC end of ScanCardsForSpace";
932 }
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700933 }
Mathieu Chartier21328a12016-07-22 10:47:45 -0700934 {
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700935 // For a sticky-bit collection, this phase needs to be after the card scanning since the
936 // mutator may read an unevac space object out of an image object. If the image object is no
937 // longer gray it will trigger a read barrier for the unevac space object.
Mathieu Chartier21328a12016-07-22 10:47:45 -0700938 TimingLogger::ScopedTiming split2("ScanImmuneSpaces", GetTimings());
939 for (auto& space : immune_spaces_.GetSpaces()) {
940 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
941 accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
Hiroshi Yamauchi5408f232016-07-29 15:07:05 -0700942 accounting::ModUnionTable* table = heap_->FindModUnionTableFromSpace(space);
Mathieu Chartier21328a12016-07-22 10:47:45 -0700943 ImmuneSpaceScanObjVisitor visitor(this);
Hiroshi Yamauchi5408f232016-07-29 15:07:05 -0700944 if (kUseBakerReadBarrier && kGrayDirtyImmuneObjects && table != nullptr) {
945 table->VisitObjects(ImmuneSpaceScanObjVisitor::Callback, &visitor);
946 } else {
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700947 // TODO: Scan only the aged cards.
Hiroshi Yamauchi5408f232016-07-29 15:07:05 -0700948 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()),
949 reinterpret_cast<uintptr_t>(space->Limit()),
950 visitor);
951 }
Mathieu Chartier21328a12016-07-22 10:47:45 -0700952 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700953 }
954 if (kUseBakerReadBarrier) {
955 // This release fence makes the field updates in the above loop visible before allowing mutator
956 // getting access to immune objects without graying it first.
Orion Hodson88591fe2018-03-06 13:35:43 +0000957 updated_all_immune_objects_.store(true, std::memory_order_release);
Roland Levillain14e5a292018-06-28 12:00:56 +0100958 // Now "un-gray" (conceptually blacken) immune objects concurrently accessed and grayed by
959 // mutators. We can't do this in the above loop because we would incorrectly disable the read
960 // barrier by un-graying (conceptually blackening) an object which may point to an unscanned,
961 // white object, breaking the to-space invariant (a mutator shall never observe a from-space
962 // (white) object).
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700963 //
Roland Levillain14e5a292018-06-28 12:00:56 +0100964 // Make sure no mutators are in the middle of marking an immune object before un-graying
965 // (blackening) immune objects.
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700966 IssueEmptyCheckpoint();
967 MutexLock mu(Thread::Current(), immune_gray_stack_lock_);
968 if (kVerboseMode) {
969 LOG(INFO) << "immune gray stack size=" << immune_gray_stack_.size();
970 }
971 for (mirror::Object* obj : immune_gray_stack_) {
Roland Levillain14e5a292018-06-28 12:00:56 +0100972 DCHECK_EQ(obj->GetReadBarrierState(), ReadBarrier::GrayState());
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700973 bool success = obj->AtomicSetReadBarrierState(ReadBarrier::GrayState(),
Roland Levillain14e5a292018-06-28 12:00:56 +0100974 ReadBarrier::NonGrayState());
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -0700975 DCHECK(success);
976 }
977 immune_gray_stack_.clear();
978 }
979
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800980 {
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -0700981 TimingLogger::ScopedTiming split2("VisitConcurrentRoots", GetTimings());
982 Runtime::Current()->VisitConcurrentRoots(this, kVisitRootFlagAllRoots);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800983 }
984 {
985 // TODO: don't visit the transaction roots if it's not active.
986 TimingLogger::ScopedTiming split5("VisitNonThreadRoots", GetTimings());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700987 Runtime::Current()->VisitNonThreadRoots(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800988 }
989
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800990 {
Mathieu Chartiera6b1ead2015-10-06 10:32:38 -0700991 TimingLogger::ScopedTiming split7("ProcessMarkStack", GetTimings());
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700992 // We transition through three mark stack modes (thread-local, shared, GC-exclusive). The
993 // primary reasons are the fact that we need to use a checkpoint to process thread-local mark
994 // stacks, but after we disable weak refs accesses, we can't use a checkpoint due to a deadlock
995 // issue because running threads potentially blocking at WaitHoldingLocks, and that once we
996 // reach the point where we process weak references, we can avoid using a lock when accessing
997 // the GC mark stack, which makes mark stack processing more efficient.
998
999 // Process the mark stack once in the thread local stack mode. This marks most of the live
1000 // objects, aside from weak ref accesses with read barriers (Reference::GetReferent() and system
1001 // weaks) that may happen concurrently while we processing the mark stack and newly mark/gray
1002 // objects and push refs on the mark stack.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001003 ProcessMarkStack();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001004 // Switch to the shared mark stack mode. That is, revoke and process thread-local mark stacks
1005 // for the last time before transitioning to the shared mark stack mode, which would process new
1006 // refs that may have been concurrently pushed onto the mark stack during the ProcessMarkStack()
1007 // call above. At the same time, disable weak ref accesses using a per-thread flag. It's
1008 // important to do these together in a single checkpoint so that we can ensure that mutators
1009 // won't newly gray objects and push new refs onto the mark stack due to weak ref accesses and
1010 // mutators safely transition to the shared mark stack mode (without leaving unprocessed refs on
1011 // the thread-local mark stacks), without a race. This is why we use a thread-local weak ref
1012 // access flag Thread::tls32_.weak_ref_access_enabled_ instead of the global ones.
1013 SwitchToSharedMarkStackMode();
1014 CHECK(!self->GetWeakRefAccessEnabled());
1015 // Now that weak refs accesses are disabled, once we exhaust the shared mark stack again here
1016 // (which may be non-empty if there were refs found on thread-local mark stacks during the above
1017 // SwitchToSharedMarkStackMode() call), we won't have new refs to process, that is, mutators
1018 // (via read barriers) have no way to produce any more refs to process. Marking converges once
1019 // before we process weak refs below.
1020 ProcessMarkStack();
1021 CheckEmptyMarkStack();
1022 // Switch to the GC exclusive mark stack mode so that we can process the mark stack without a
1023 // lock from this point on.
1024 SwitchToGcExclusiveMarkStackMode();
1025 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001026 if (kVerboseMode) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001027 LOG(INFO) << "ProcessReferences";
1028 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001029 // Process weak references. This may produce new refs to process and have them processed via
Mathieu Chartier97509952015-07-13 14:35:43 -07001030 // ProcessMarkStack (in the GC exclusive mark stack mode).
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001031 ProcessReferences(self);
1032 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001033 if (kVerboseMode) {
1034 LOG(INFO) << "SweepSystemWeaks";
1035 }
1036 SweepSystemWeaks(self);
1037 if (kVerboseMode) {
1038 LOG(INFO) << "SweepSystemWeaks done";
1039 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001040 // Process the mark stack here one last time because the above SweepSystemWeaks() call may have
1041 // marked some objects (strings alive) as hash_set::Erase() can call the hash function for
1042 // arbitrary elements in the weak intern table in InternTable::Table::SweepWeaks().
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001043 ProcessMarkStack();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001044 CheckEmptyMarkStack();
1045 // Re-enable weak ref accesses.
1046 ReenableWeakRefAccess(self);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07001047 // Free data for class loaders that we unloaded.
1048 Runtime::Current()->GetClassLinker()->CleanupClassLoaders();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001049 // Marking is done. Disable marking.
Hiroshi Yamauchi00370822015-08-18 14:47:25 -07001050 DisableMarking();
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001051 if (kUseBakerReadBarrier) {
1052 ProcessFalseGrayStack();
1053 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001054 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001055 }
1056
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001057 if (kIsDebugBuild) {
1058 MutexLock mu(self, *Locks::thread_list_lock_);
1059 CHECK(weak_ref_access_enabled_);
1060 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001061 if (kVerboseMode) {
1062 LOG(INFO) << "GC end of MarkingPhase";
1063 }
1064}
1065
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001066void ConcurrentCopying::ReenableWeakRefAccess(Thread* self) {
1067 if (kVerboseMode) {
1068 LOG(INFO) << "ReenableWeakRefAccess";
1069 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001070 // Iterate all threads (don't need to or can't use a checkpoint) and re-enable weak ref access.
1071 {
1072 MutexLock mu(self, *Locks::thread_list_lock_);
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001073 weak_ref_access_enabled_ = true; // This is for new threads.
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001074 std::list<Thread*> thread_list = Runtime::Current()->GetThreadList()->GetList();
1075 for (Thread* thread : thread_list) {
1076 thread->SetWeakRefAccessEnabled(true);
1077 }
1078 }
1079 // Unblock blocking threads.
1080 GetHeap()->GetReferenceProcessor()->BroadcastForSlowPath(self);
1081 Runtime::Current()->BroadcastForNewSystemWeaks();
1082}
1083
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001084class ConcurrentCopying::DisableMarkingCheckpoint : public Closure {
Hiroshi Yamauchi00370822015-08-18 14:47:25 -07001085 public:
1086 explicit DisableMarkingCheckpoint(ConcurrentCopying* concurrent_copying)
1087 : concurrent_copying_(concurrent_copying) {
1088 }
1089
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001090 void Run(Thread* thread) override NO_THREAD_SAFETY_ANALYSIS {
Hiroshi Yamauchi00370822015-08-18 14:47:25 -07001091 // Note: self is not necessarily equal to thread since thread may be suspended.
1092 Thread* self = Thread::Current();
1093 DCHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
1094 << thread->GetState() << " thread " << thread << " self " << self;
1095 // Disable the thread-local is_gc_marking flag.
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -07001096 // Note a thread that has just started right before this checkpoint may have already this flag
1097 // set to false, which is ok.
Mathieu Chartierfe814e82016-11-09 14:32:49 -08001098 thread->SetIsGcMarkingAndUpdateEntrypoints(false);
Hiroshi Yamauchi00370822015-08-18 14:47:25 -07001099 // If thread is a running mutator, then act on behalf of the garbage collector.
1100 // See the code in ThreadList::RunCheckpoint.
Mathieu Chartier10d25082015-10-28 18:36:09 -07001101 concurrent_copying_->GetBarrier().Pass(self);
Hiroshi Yamauchi00370822015-08-18 14:47:25 -07001102 }
1103
1104 private:
1105 ConcurrentCopying* const concurrent_copying_;
1106};
1107
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001108class ConcurrentCopying::DisableMarkingCallback : public Closure {
1109 public:
1110 explicit DisableMarkingCallback(ConcurrentCopying* concurrent_copying)
1111 : concurrent_copying_(concurrent_copying) {
1112 }
1113
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001114 void Run(Thread* self ATTRIBUTE_UNUSED) override REQUIRES(Locks::thread_list_lock_) {
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001115 // This needs to run under the thread_list_lock_ critical section in ThreadList::RunCheckpoint()
1116 // to avoid a race with ThreadList::Register().
1117 CHECK(concurrent_copying_->is_marking_);
1118 concurrent_copying_->is_marking_ = false;
Mathieu Chartiera9a4f5f2017-05-03 18:19:13 -07001119 if (kUseBakerReadBarrier && kGrayDirtyImmuneObjects) {
1120 CHECK(concurrent_copying_->is_using_read_barrier_entrypoints_);
1121 concurrent_copying_->is_using_read_barrier_entrypoints_ = false;
1122 } else {
1123 CHECK(!concurrent_copying_->is_using_read_barrier_entrypoints_);
1124 }
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001125 }
1126
1127 private:
1128 ConcurrentCopying* const concurrent_copying_;
1129};
1130
Hiroshi Yamauchi00370822015-08-18 14:47:25 -07001131void ConcurrentCopying::IssueDisableMarkingCheckpoint() {
1132 Thread* self = Thread::Current();
1133 DisableMarkingCheckpoint check_point(this);
1134 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1135 gc_barrier_->Init(self, 0);
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001136 DisableMarkingCallback dmc(this);
1137 size_t barrier_count = thread_list->RunCheckpoint(&check_point, &dmc);
Hiroshi Yamauchi00370822015-08-18 14:47:25 -07001138 // If there are no threads to wait which implies that all the checkpoint functions are finished,
1139 // then no need to release the mutator lock.
1140 if (barrier_count == 0) {
1141 return;
1142 }
1143 // Release locks then wait for all mutator threads to pass the barrier.
1144 Locks::mutator_lock_->SharedUnlock(self);
1145 {
1146 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
1147 gc_barrier_->Increment(self, barrier_count);
1148 }
1149 Locks::mutator_lock_->SharedLock(self);
1150}
1151
1152void ConcurrentCopying::DisableMarking() {
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001153 // Use a checkpoint to turn off the global is_marking and the thread-local is_gc_marking flags and
1154 // to ensure no threads are still in the middle of a read barrier which may have a from-space ref
1155 // cached in a local variable.
Hiroshi Yamauchi00370822015-08-18 14:47:25 -07001156 IssueDisableMarkingCheckpoint();
1157 if (kUseTableLookupReadBarrier) {
1158 heap_->rb_table_->ClearAll();
1159 DCHECK(heap_->rb_table_->IsAllCleared());
1160 }
Orion Hodson88591fe2018-03-06 13:35:43 +00001161 is_mark_stack_push_disallowed_.store(1, std::memory_order_seq_cst);
1162 mark_stack_mode_.store(kMarkStackModeOff, std::memory_order_seq_cst);
Hiroshi Yamauchi00370822015-08-18 14:47:25 -07001163}
1164
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08001165void ConcurrentCopying::PushOntoFalseGrayStack(Thread* const self, mirror::Object* ref) {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001166 CHECK(kUseBakerReadBarrier);
1167 DCHECK(ref != nullptr);
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08001168 MutexLock mu(self, mark_stack_lock_);
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001169 false_gray_stack_.push_back(ref);
1170}
1171
1172void ConcurrentCopying::ProcessFalseGrayStack() {
1173 CHECK(kUseBakerReadBarrier);
Roland Levillain14e5a292018-06-28 12:00:56 +01001174 // Change the objects on the false gray stack from gray to non-gray (conceptually black).
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001175 MutexLock mu(Thread::Current(), mark_stack_lock_);
1176 for (mirror::Object* obj : false_gray_stack_) {
1177 DCHECK(IsMarked(obj));
Roland Levillain14e5a292018-06-28 12:00:56 +01001178 // The object could be non-gray (conceptually black) here if a thread got preempted after a
1179 // success at the AtomicSetReadBarrierState in MarkNonMoving(), GC started marking through it
1180 // (but not finished so still gray), the thread ran to register it onto the false gray stack,
1181 // and then GC eventually marked it black (non-gray) after it finished scanning it.
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001182 if (obj->GetReadBarrierState() == ReadBarrier::GrayState()) {
1183 bool success = obj->AtomicSetReadBarrierState(ReadBarrier::GrayState(),
Roland Levillain14e5a292018-06-28 12:00:56 +01001184 ReadBarrier::NonGrayState());
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001185 DCHECK(success);
1186 }
1187 }
1188 false_gray_stack_.clear();
1189}
1190
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001191void ConcurrentCopying::IssueEmptyCheckpoint() {
1192 Thread* self = Thread::Current();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001193 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001194 // Release locks then wait for all mutator threads to pass the barrier.
1195 Locks::mutator_lock_->SharedUnlock(self);
Hiroshi Yamauchia2224042017-02-08 16:35:45 -08001196 thread_list->RunEmptyCheckpoint();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001197 Locks::mutator_lock_->SharedLock(self);
1198}
1199
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -07001200void ConcurrentCopying::ExpandGcMarkStack() {
1201 DCHECK(gc_mark_stack_->IsFull());
1202 const size_t new_size = gc_mark_stack_->Capacity() * 2;
1203 std::vector<StackReference<mirror::Object>> temp(gc_mark_stack_->Begin(),
1204 gc_mark_stack_->End());
1205 gc_mark_stack_->Resize(new_size);
1206 for (auto& ref : temp) {
1207 gc_mark_stack_->PushBack(ref.AsMirrorPtr());
1208 }
1209 DCHECK(!gc_mark_stack_->IsFull());
1210}
1211
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08001212void ConcurrentCopying::PushOntoMarkStack(Thread* const self, mirror::Object* to_ref) {
Orion Hodson88591fe2018-03-06 13:35:43 +00001213 CHECK_EQ(is_mark_stack_push_disallowed_.load(std::memory_order_relaxed), 0)
David Sehr709b0702016-10-13 09:12:37 -07001214 << " " << to_ref << " " << mirror::Object::PrettyTypeOf(to_ref);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001215 CHECK(thread_running_gc_ != nullptr);
Orion Hodson88591fe2018-03-06 13:35:43 +00001216 MarkStackMode mark_stack_mode = mark_stack_mode_.load(std::memory_order_relaxed);
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001217 if (LIKELY(mark_stack_mode == kMarkStackModeThreadLocal)) {
1218 if (LIKELY(self == thread_running_gc_)) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001219 // If GC-running thread, use the GC mark stack instead of a thread-local mark stack.
1220 CHECK(self->GetThreadLocalMarkStack() == nullptr);
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -07001221 if (UNLIKELY(gc_mark_stack_->IsFull())) {
1222 ExpandGcMarkStack();
1223 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001224 gc_mark_stack_->PushBack(to_ref);
1225 } else {
1226 // Otherwise, use a thread-local mark stack.
1227 accounting::AtomicStack<mirror::Object>* tl_mark_stack = self->GetThreadLocalMarkStack();
1228 if (UNLIKELY(tl_mark_stack == nullptr || tl_mark_stack->IsFull())) {
1229 MutexLock mu(self, mark_stack_lock_);
1230 // Get a new thread local mark stack.
1231 accounting::AtomicStack<mirror::Object>* new_tl_mark_stack;
1232 if (!pooled_mark_stacks_.empty()) {
1233 // Use a pooled mark stack.
1234 new_tl_mark_stack = pooled_mark_stacks_.back();
1235 pooled_mark_stacks_.pop_back();
1236 } else {
1237 // None pooled. Create a new one.
1238 new_tl_mark_stack =
1239 accounting::AtomicStack<mirror::Object>::Create(
1240 "thread local mark stack", 4 * KB, 4 * KB);
1241 }
1242 DCHECK(new_tl_mark_stack != nullptr);
1243 DCHECK(new_tl_mark_stack->IsEmpty());
1244 new_tl_mark_stack->PushBack(to_ref);
1245 self->SetThreadLocalMarkStack(new_tl_mark_stack);
1246 if (tl_mark_stack != nullptr) {
1247 // Store the old full stack into a vector.
1248 revoked_mark_stacks_.push_back(tl_mark_stack);
1249 }
1250 } else {
1251 tl_mark_stack->PushBack(to_ref);
1252 }
1253 }
1254 } else if (mark_stack_mode == kMarkStackModeShared) {
1255 // Access the shared GC mark stack with a lock.
1256 MutexLock mu(self, mark_stack_lock_);
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -07001257 if (UNLIKELY(gc_mark_stack_->IsFull())) {
1258 ExpandGcMarkStack();
1259 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001260 gc_mark_stack_->PushBack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001261 } else {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001262 CHECK_EQ(static_cast<uint32_t>(mark_stack_mode),
Hiroshi Yamauchifa755182015-09-30 20:12:11 -07001263 static_cast<uint32_t>(kMarkStackModeGcExclusive))
1264 << "ref=" << to_ref
1265 << " self->gc_marking=" << self->GetIsGcMarking()
1266 << " cc->is_marking=" << is_marking_;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001267 CHECK(self == thread_running_gc_)
1268 << "Only GC-running thread should access the mark stack "
1269 << "in the GC exclusive mark stack mode";
1270 // Access the GC mark stack without a lock.
Hiroshi Yamauchi19eab402015-10-23 19:59:58 -07001271 if (UNLIKELY(gc_mark_stack_->IsFull())) {
1272 ExpandGcMarkStack();
1273 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001274 gc_mark_stack_->PushBack(to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001275 }
1276}
1277
1278accounting::ObjectStack* ConcurrentCopying::GetAllocationStack() {
1279 return heap_->allocation_stack_.get();
1280}
1281
1282accounting::ObjectStack* ConcurrentCopying::GetLiveStack() {
1283 return heap_->live_stack_.get();
1284}
1285
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001286// The following visitors are used to verify that there's no references to the from-space left after
1287// marking.
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001288class ConcurrentCopying::VerifyNoFromSpaceRefsVisitor : public SingleRootVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001289 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001290 explicit VerifyNoFromSpaceRefsVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001291 : collector_(collector) {}
1292
Mathieu Chartierbc632f02017-04-20 13:31:39 -07001293 void operator()(mirror::Object* ref,
1294 MemberOffset offset = MemberOffset(0),
1295 mirror::Object* holder = nullptr) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001296 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001297 if (ref == nullptr) {
1298 // OK.
1299 return;
1300 }
Mathieu Chartierbc632f02017-04-20 13:31:39 -07001301 collector_->AssertToSpaceInvariant(holder, offset, ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001302 if (kUseBakerReadBarrier) {
Roland Levillain14e5a292018-06-28 12:00:56 +01001303 CHECK_EQ(ref->GetReadBarrierState(), ReadBarrier::NonGrayState())
1304 << "Ref " << ref << " " << ref->PrettyTypeOf() << " has gray rb_state";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001305 }
1306 }
1307
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001308 void VisitRoot(mirror::Object* root, const RootInfo& info ATTRIBUTE_UNUSED)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001309 override REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001310 DCHECK(root != nullptr);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001311 operator()(root);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001312 }
1313
1314 private:
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001315 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001316};
1317
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001318class ConcurrentCopying::VerifyNoFromSpaceRefsFieldVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001319 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001320 explicit VerifyNoFromSpaceRefsFieldVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001321 : collector_(collector) {}
1322
Mathieu Chartier31e88222016-10-14 18:43:19 -07001323 void operator()(ObjPtr<mirror::Object> obj,
1324 MemberOffset offset,
1325 bool is_static ATTRIBUTE_UNUSED) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001326 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001327 mirror::Object* ref =
1328 obj->GetFieldObject<mirror::Object, kDefaultVerifyFlags, kWithoutReadBarrier>(offset);
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001329 VerifyNoFromSpaceRefsVisitor visitor(collector_);
Mathieu Chartierbc632f02017-04-20 13:31:39 -07001330 visitor(ref, offset, obj.Ptr());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001331 }
Mathieu Chartier31e88222016-10-14 18:43:19 -07001332 void operator()(ObjPtr<mirror::Class> klass,
1333 ObjPtr<mirror::Reference> ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001334 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001335 CHECK(klass->IsTypeOfReferenceClass());
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07001336 this->operator()(ObjPtr<mirror::Object>(ref), mirror::Reference::ReferentOffset(), false);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001337 }
1338
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001339 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001340 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001341 if (!root->IsNull()) {
1342 VisitRoot(root);
1343 }
1344 }
1345
1346 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001347 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001348 VerifyNoFromSpaceRefsVisitor visitor(collector_);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001349 visitor(root->AsMirrorPtr());
1350 }
1351
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001352 private:
Mathieu Chartier97509952015-07-13 14:35:43 -07001353 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001354};
1355
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001356// Verify there's no from-space references left after the marking phase.
1357void ConcurrentCopying::VerifyNoFromSpaceReferences() {
1358 Thread* self = Thread::Current();
1359 DCHECK(Locks::mutator_lock_->IsExclusiveHeld(self));
Hiroshi Yamauchi00370822015-08-18 14:47:25 -07001360 // Verify all threads have is_gc_marking to be false
1361 {
1362 MutexLock mu(self, *Locks::thread_list_lock_);
1363 std::list<Thread*> thread_list = Runtime::Current()->GetThreadList()->GetList();
1364 for (Thread* thread : thread_list) {
1365 CHECK(!thread->GetIsGcMarking());
1366 }
1367 }
Andreas Gampe0c183382017-07-13 22:26:24 -07001368
1369 auto verify_no_from_space_refs_visitor = [&](mirror::Object* obj)
1370 REQUIRES_SHARED(Locks::mutator_lock_) {
1371 CHECK(obj != nullptr);
1372 space::RegionSpace* region_space = RegionSpace();
1373 CHECK(!region_space->IsInFromSpace(obj)) << "Scanning object " << obj << " in from space";
1374 VerifyNoFromSpaceRefsFieldVisitor visitor(this);
1375 obj->VisitReferences</*kVisitNativeRoots*/true, kDefaultVerifyFlags, kWithoutReadBarrier>(
1376 visitor,
1377 visitor);
1378 if (kUseBakerReadBarrier) {
Roland Levillain14e5a292018-06-28 12:00:56 +01001379 CHECK_EQ(obj->GetReadBarrierState(), ReadBarrier::NonGrayState())
1380 << "obj=" << obj << " has gray rb_state " << obj->GetReadBarrierState();
Andreas Gampe0c183382017-07-13 22:26:24 -07001381 }
1382 };
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001383 // Roots.
1384 {
1385 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001386 VerifyNoFromSpaceRefsVisitor ref_visitor(this);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001387 Runtime::Current()->VisitRoots(&ref_visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001388 }
1389 // The to-space.
Andreas Gampe0c183382017-07-13 22:26:24 -07001390 region_space_->WalkToSpace(verify_no_from_space_refs_visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001391 // Non-moving spaces.
1392 {
1393 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Andreas Gampe0c183382017-07-13 22:26:24 -07001394 heap_->GetMarkBitmap()->Visit(verify_no_from_space_refs_visitor);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001395 }
1396 // The alloc stack.
1397 {
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001398 VerifyNoFromSpaceRefsVisitor ref_visitor(this);
Mathieu Chartiercb535da2015-01-23 13:50:03 -08001399 for (auto* it = heap_->allocation_stack_->Begin(), *end = heap_->allocation_stack_->End();
1400 it < end; ++it) {
1401 mirror::Object* const obj = it->AsMirrorPtr();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001402 if (obj != nullptr && obj->GetClass() != nullptr) {
1403 // TODO: need to call this only if obj is alive?
1404 ref_visitor(obj);
Andreas Gampe0c183382017-07-13 22:26:24 -07001405 verify_no_from_space_refs_visitor(obj);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001406 }
1407 }
1408 }
1409 // TODO: LOS. But only refs in LOS are classes.
1410}
1411
1412// The following visitors are used to assert the to-space invariant.
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001413class ConcurrentCopying::AssertToSpaceInvariantRefsVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001414 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001415 explicit AssertToSpaceInvariantRefsVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001416 : collector_(collector) {}
1417
1418 void operator()(mirror::Object* ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001419 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001420 if (ref == nullptr) {
1421 // OK.
1422 return;
1423 }
1424 collector_->AssertToSpaceInvariant(nullptr, MemberOffset(0), ref);
1425 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001426
1427 private:
Mathieu Chartier97509952015-07-13 14:35:43 -07001428 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001429};
1430
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001431class ConcurrentCopying::AssertToSpaceInvariantFieldVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001432 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001433 explicit AssertToSpaceInvariantFieldVisitor(ConcurrentCopying* collector)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001434 : collector_(collector) {}
1435
Mathieu Chartier31e88222016-10-14 18:43:19 -07001436 void operator()(ObjPtr<mirror::Object> obj,
1437 MemberOffset offset,
1438 bool is_static ATTRIBUTE_UNUSED) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001439 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001440 mirror::Object* ref =
1441 obj->GetFieldObject<mirror::Object, kDefaultVerifyFlags, kWithoutReadBarrier>(offset);
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001442 AssertToSpaceInvariantRefsVisitor visitor(collector_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001443 visitor(ref);
1444 }
Mathieu Chartier31e88222016-10-14 18:43:19 -07001445 void operator()(ObjPtr<mirror::Class> klass, ObjPtr<mirror::Reference> ref ATTRIBUTE_UNUSED) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001446 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001447 CHECK(klass->IsTypeOfReferenceClass());
1448 }
1449
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001450 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001451 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001452 if (!root->IsNull()) {
1453 VisitRoot(root);
1454 }
1455 }
1456
1457 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001458 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001459 AssertToSpaceInvariantRefsVisitor visitor(collector_);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001460 visitor(root->AsMirrorPtr());
1461 }
1462
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001463 private:
Mathieu Chartier97509952015-07-13 14:35:43 -07001464 ConcurrentCopying* const collector_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001465};
1466
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001467class ConcurrentCopying::RevokeThreadLocalMarkStackCheckpoint : public Closure {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001468 public:
Roland Levillain3887c462015-08-12 18:15:42 +01001469 RevokeThreadLocalMarkStackCheckpoint(ConcurrentCopying* concurrent_copying,
1470 bool disable_weak_ref_access)
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001471 : concurrent_copying_(concurrent_copying),
1472 disable_weak_ref_access_(disable_weak_ref_access) {
1473 }
1474
Roland Levillainf73caca2018-08-24 17:19:07 +01001475 void Run(Thread* thread) override NO_THREAD_SAFETY_ANALYSIS {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001476 // Note: self is not necessarily equal to thread since thread may be suspended.
1477 Thread* self = Thread::Current();
1478 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
1479 << thread->GetState() << " thread " << thread << " self " << self;
1480 // Revoke thread local mark stacks.
1481 accounting::AtomicStack<mirror::Object>* tl_mark_stack = thread->GetThreadLocalMarkStack();
1482 if (tl_mark_stack != nullptr) {
1483 MutexLock mu(self, concurrent_copying_->mark_stack_lock_);
1484 concurrent_copying_->revoked_mark_stacks_.push_back(tl_mark_stack);
1485 thread->SetThreadLocalMarkStack(nullptr);
1486 }
1487 // Disable weak ref access.
1488 if (disable_weak_ref_access_) {
1489 thread->SetWeakRefAccessEnabled(false);
1490 }
1491 // If thread is a running mutator, then act on behalf of the garbage collector.
1492 // See the code in ThreadList::RunCheckpoint.
Mathieu Chartier10d25082015-10-28 18:36:09 -07001493 concurrent_copying_->GetBarrier().Pass(self);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001494 }
1495
1496 private:
1497 ConcurrentCopying* const concurrent_copying_;
1498 const bool disable_weak_ref_access_;
1499};
1500
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001501void ConcurrentCopying::RevokeThreadLocalMarkStacks(bool disable_weak_ref_access,
1502 Closure* checkpoint_callback) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001503 Thread* self = Thread::Current();
1504 RevokeThreadLocalMarkStackCheckpoint check_point(this, disable_weak_ref_access);
1505 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1506 gc_barrier_->Init(self, 0);
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001507 size_t barrier_count = thread_list->RunCheckpoint(&check_point, checkpoint_callback);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001508 // If there are no threads to wait which implys that all the checkpoint functions are finished,
1509 // then no need to release the mutator lock.
1510 if (barrier_count == 0) {
1511 return;
1512 }
1513 Locks::mutator_lock_->SharedUnlock(self);
1514 {
1515 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
1516 gc_barrier_->Increment(self, barrier_count);
1517 }
1518 Locks::mutator_lock_->SharedLock(self);
1519}
1520
1521void ConcurrentCopying::RevokeThreadLocalMarkStack(Thread* thread) {
1522 Thread* self = Thread::Current();
1523 CHECK_EQ(self, thread);
1524 accounting::AtomicStack<mirror::Object>* tl_mark_stack = thread->GetThreadLocalMarkStack();
1525 if (tl_mark_stack != nullptr) {
1526 CHECK(is_marking_);
1527 MutexLock mu(self, mark_stack_lock_);
1528 revoked_mark_stacks_.push_back(tl_mark_stack);
1529 thread->SetThreadLocalMarkStack(nullptr);
1530 }
1531}
1532
1533void ConcurrentCopying::ProcessMarkStack() {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001534 if (kVerboseMode) {
1535 LOG(INFO) << "ProcessMarkStack. ";
1536 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001537 bool empty_prev = false;
1538 while (true) {
1539 bool empty = ProcessMarkStackOnce();
1540 if (empty_prev && empty) {
1541 // Saw empty mark stack for a second time, done.
1542 break;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001543 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001544 empty_prev = empty;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001545 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001546}
1547
1548bool ConcurrentCopying::ProcessMarkStackOnce() {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08001549 DCHECK(thread_running_gc_ != nullptr);
1550 Thread* const self = Thread::Current();
1551 DCHECK(self == thread_running_gc_);
1552 DCHECK(thread_running_gc_->GetThreadLocalMarkStack() == nullptr);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001553 size_t count = 0;
Orion Hodson88591fe2018-03-06 13:35:43 +00001554 MarkStackMode mark_stack_mode = mark_stack_mode_.load(std::memory_order_relaxed);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001555 if (mark_stack_mode == kMarkStackModeThreadLocal) {
1556 // Process the thread-local mark stacks and the GC mark stack.
Roland Levillainaf290312018-02-27 20:02:17 +00001557 count += ProcessThreadLocalMarkStacks(/* disable_weak_ref_access */ false,
1558 /* checkpoint_callback */ nullptr);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001559 while (!gc_mark_stack_->IsEmpty()) {
1560 mirror::Object* to_ref = gc_mark_stack_->PopBack();
1561 ProcessMarkStackRef(to_ref);
1562 ++count;
1563 }
1564 gc_mark_stack_->Reset();
1565 } else if (mark_stack_mode == kMarkStackModeShared) {
Hiroshi Yamauchi30493242016-11-03 13:06:52 -07001566 // Do an empty checkpoint to avoid a race with a mutator preempted in the middle of a read
1567 // barrier but before pushing onto the mark stack. b/32508093. Note the weak ref access is
1568 // disabled at this point.
1569 IssueEmptyCheckpoint();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001570 // Process the shared GC mark stack with a lock.
1571 {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08001572 MutexLock mu(thread_running_gc_, mark_stack_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001573 CHECK(revoked_mark_stacks_.empty());
1574 }
1575 while (true) {
1576 std::vector<mirror::Object*> refs;
1577 {
1578 // Copy refs with lock. Note the number of refs should be small.
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08001579 MutexLock mu(thread_running_gc_, mark_stack_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001580 if (gc_mark_stack_->IsEmpty()) {
1581 break;
1582 }
1583 for (StackReference<mirror::Object>* p = gc_mark_stack_->Begin();
1584 p != gc_mark_stack_->End(); ++p) {
1585 refs.push_back(p->AsMirrorPtr());
1586 }
1587 gc_mark_stack_->Reset();
1588 }
1589 for (mirror::Object* ref : refs) {
1590 ProcessMarkStackRef(ref);
1591 ++count;
1592 }
1593 }
1594 } else {
1595 CHECK_EQ(static_cast<uint32_t>(mark_stack_mode),
1596 static_cast<uint32_t>(kMarkStackModeGcExclusive));
1597 {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08001598 MutexLock mu(thread_running_gc_, mark_stack_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001599 CHECK(revoked_mark_stacks_.empty());
1600 }
1601 // Process the GC mark stack in the exclusive mode. No need to take the lock.
1602 while (!gc_mark_stack_->IsEmpty()) {
1603 mirror::Object* to_ref = gc_mark_stack_->PopBack();
1604 ProcessMarkStackRef(to_ref);
1605 ++count;
1606 }
1607 gc_mark_stack_->Reset();
1608 }
1609
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001610 // Return true if the stack was empty.
1611 return count == 0;
1612}
1613
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001614size_t ConcurrentCopying::ProcessThreadLocalMarkStacks(bool disable_weak_ref_access,
1615 Closure* checkpoint_callback) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001616 // Run a checkpoint to collect all thread local mark stacks and iterate over them all.
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001617 RevokeThreadLocalMarkStacks(disable_weak_ref_access, checkpoint_callback);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001618 size_t count = 0;
1619 std::vector<accounting::AtomicStack<mirror::Object>*> mark_stacks;
1620 {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08001621 MutexLock mu(thread_running_gc_, mark_stack_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001622 // Make a copy of the mark stack vector.
1623 mark_stacks = revoked_mark_stacks_;
1624 revoked_mark_stacks_.clear();
1625 }
1626 for (accounting::AtomicStack<mirror::Object>* mark_stack : mark_stacks) {
1627 for (StackReference<mirror::Object>* p = mark_stack->Begin(); p != mark_stack->End(); ++p) {
1628 mirror::Object* to_ref = p->AsMirrorPtr();
1629 ProcessMarkStackRef(to_ref);
1630 ++count;
1631 }
1632 {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08001633 MutexLock mu(thread_running_gc_, mark_stack_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001634 if (pooled_mark_stacks_.size() >= kMarkStackPoolSize) {
1635 // The pool has enough. Delete it.
1636 delete mark_stack;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001637 } else {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001638 // Otherwise, put it into the pool for later reuse.
1639 mark_stack->Reset();
1640 pooled_mark_stacks_.push_back(mark_stack);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001641 }
1642 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001643 }
1644 return count;
1645}
1646
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001647inline void ConcurrentCopying::ProcessMarkStackRef(mirror::Object* to_ref) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001648 DCHECK(!region_space_->IsInFromSpace(to_ref));
1649 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001650 DCHECK(to_ref->GetReadBarrierState() == ReadBarrier::GrayState())
1651 << " " << to_ref << " " << to_ref->GetReadBarrierState()
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001652 << " is_marked=" << IsMarked(to_ref);
1653 }
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07001654 space::RegionSpace::RegionType rtype = region_space_->GetRegionType(to_ref);
Mathieu Chartierc381c362016-08-23 13:27:53 -07001655 bool add_to_live_bytes = false;
Roland Levillain4e751132018-01-15 11:52:58 +00001656 // Invariant: There should be no object from a newly-allocated
1657 // region (either large or non-large) on the mark stack.
1658 DCHECK(!region_space_->IsInNewlyAllocatedRegion(to_ref)) << to_ref;
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07001659 if (rtype == space::RegionSpace::RegionType::kRegionTypeUnevacFromSpace) {
Mathieu Chartierc381c362016-08-23 13:27:53 -07001660 // Mark the bitmap only in the GC thread here so that we don't need a CAS.
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07001661 if (!kUseBakerReadBarrier ||
1662 !region_space_bitmap_->Set(to_ref)) {
Mathieu Chartierc381c362016-08-23 13:27:53 -07001663 // It may be already marked if we accidentally pushed the same object twice due to the racy
1664 // bitmap read in MarkUnevacFromSpaceRegion.
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07001665 if (kEnableGenerationalConcurrentCopyingCollection && young_gen_) {
1666 CHECK(region_space_->IsLargeObject(to_ref));
1667 region_space_->ZeroLiveBytesForLargeObject(to_ref);
1668 Scan<true>(to_ref);
1669 } else {
1670 Scan<false>(to_ref);
1671 }
1672 // Only add to the live bytes if the object was not already marked and we are not the young
1673 // GC.
Mathieu Chartierc381c362016-08-23 13:27:53 -07001674 add_to_live_bytes = true;
1675 }
1676 } else {
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07001677 if (kEnableGenerationalConcurrentCopyingCollection) {
1678 if (rtype == space::RegionSpace::RegionType::kRegionTypeToSpace) {
1679 // Copied to to-space, set the bit so that the next GC can scan objects.
1680 region_space_bitmap_->Set(to_ref);
1681 }
1682 }
1683 if (kEnableGenerationalConcurrentCopyingCollection && young_gen_) {
1684 Scan<true>(to_ref);
1685 } else {
1686 Scan<false>(to_ref);
1687 }
Mathieu Chartierc381c362016-08-23 13:27:53 -07001688 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001689 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001690 DCHECK(to_ref->GetReadBarrierState() == ReadBarrier::GrayState())
1691 << " " << to_ref << " " << to_ref->GetReadBarrierState()
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001692 << " is_marked=" << IsMarked(to_ref);
1693 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001694#ifdef USE_BAKER_OR_BROOKS_READ_BARRIER
Hiroshi Yamauchi39c12d42016-12-06 16:46:37 -08001695 mirror::Object* referent = nullptr;
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001696 if (UNLIKELY((to_ref->GetClass<kVerifyNone, kWithoutReadBarrier>()->IsTypeOfReferenceClass() &&
Hiroshi Yamauchi39c12d42016-12-06 16:46:37 -08001697 (referent = to_ref->AsReference()->GetReferent<kWithoutReadBarrier>()) != nullptr &&
1698 !IsInToSpace(referent)))) {
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001699 // Leave this reference gray in the queue so that GetReferent() will trigger a read barrier. We
Roland Levillain14e5a292018-06-28 12:00:56 +01001700 // will change it to non-gray later in ReferenceQueue::DisableReadBarrierForReference.
Roland Levillain2ae376f2018-01-30 11:35:11 +00001701 DCHECK(to_ref->AsReference()->GetPendingNext() != nullptr)
1702 << "Left unenqueued ref gray " << to_ref;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001703 } else {
Roland Levillain14e5a292018-06-28 12:00:56 +01001704 // We may occasionally leave a reference non-gray in the queue if its referent happens to be
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001705 // concurrently marked after the Scan() call above has enqueued the Reference, in which case the
Roland Levillain14e5a292018-06-28 12:00:56 +01001706 // above IsInToSpace() evaluates to true and we change the color from gray to non-gray here in
1707 // this else block.
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001708 if (kUseBakerReadBarrier) {
Mathieu Chartier42c2e502018-06-19 12:30:56 -07001709 bool success = to_ref->AtomicSetReadBarrierState<std::memory_order_release>(
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001710 ReadBarrier::GrayState(),
Roland Levillain14e5a292018-06-28 12:00:56 +01001711 ReadBarrier::NonGrayState());
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001712 DCHECK(success) << "Must succeed as we won the race.";
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001713 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001714 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07001715#else
1716 DCHECK(!kUseBakerReadBarrier);
1717#endif
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001718
Mathieu Chartierc381c362016-08-23 13:27:53 -07001719 if (add_to_live_bytes) {
Roland Levillain2ae376f2018-01-30 11:35:11 +00001720 // Add to the live bytes per unevacuated from-space. Note this code is always run by the
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001721 // GC-running thread (no synchronization required).
1722 DCHECK(region_space_bitmap_->Test(to_ref));
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07001723 size_t obj_size = to_ref->SizeOf<kDefaultVerifyFlags>();
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08001724 size_t alloc_size = RoundUp(obj_size, space::RegionSpace::kAlignment);
1725 region_space_->AddLiveBytes(to_ref, alloc_size);
1726 }
Andreas Gampee3ce7872017-02-22 13:36:21 -08001727 if (ReadBarrier::kEnableToSpaceInvariantChecks) {
Andreas Gampe0c183382017-07-13 22:26:24 -07001728 CHECK(to_ref != nullptr);
1729 space::RegionSpace* region_space = RegionSpace();
1730 CHECK(!region_space->IsInFromSpace(to_ref)) << "Scanning object " << to_ref << " in from space";
1731 AssertToSpaceInvariant(nullptr, MemberOffset(0), to_ref);
1732 AssertToSpaceInvariantFieldVisitor visitor(this);
1733 to_ref->VisitReferences</*kVisitNativeRoots*/true, kDefaultVerifyFlags, kWithoutReadBarrier>(
1734 visitor,
1735 visitor);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001736 }
1737}
1738
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001739class ConcurrentCopying::DisableWeakRefAccessCallback : public Closure {
1740 public:
1741 explicit DisableWeakRefAccessCallback(ConcurrentCopying* concurrent_copying)
1742 : concurrent_copying_(concurrent_copying) {
1743 }
1744
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001745 void Run(Thread* self ATTRIBUTE_UNUSED) override REQUIRES(Locks::thread_list_lock_) {
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001746 // This needs to run under the thread_list_lock_ critical section in ThreadList::RunCheckpoint()
1747 // to avoid a deadlock b/31500969.
1748 CHECK(concurrent_copying_->weak_ref_access_enabled_);
1749 concurrent_copying_->weak_ref_access_enabled_ = false;
1750 }
1751
1752 private:
1753 ConcurrentCopying* const concurrent_copying_;
1754};
1755
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001756void ConcurrentCopying::SwitchToSharedMarkStackMode() {
1757 Thread* self = Thread::Current();
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08001758 DCHECK(thread_running_gc_ != nullptr);
1759 DCHECK(self == thread_running_gc_);
1760 DCHECK(thread_running_gc_->GetThreadLocalMarkStack() == nullptr);
Orion Hodson88591fe2018-03-06 13:35:43 +00001761 MarkStackMode before_mark_stack_mode = mark_stack_mode_.load(std::memory_order_relaxed);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001762 CHECK_EQ(static_cast<uint32_t>(before_mark_stack_mode),
1763 static_cast<uint32_t>(kMarkStackModeThreadLocal));
Orion Hodson88591fe2018-03-06 13:35:43 +00001764 mark_stack_mode_.store(kMarkStackModeShared, std::memory_order_relaxed);
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001765 DisableWeakRefAccessCallback dwrac(this);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001766 // Process the thread local mark stacks one last time after switching to the shared mark stack
1767 // mode and disable weak ref accesses.
Roland Levillainaf290312018-02-27 20:02:17 +00001768 ProcessThreadLocalMarkStacks(/* disable_weak_ref_access */ true, &dwrac);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001769 if (kVerboseMode) {
1770 LOG(INFO) << "Switched to shared mark stack mode and disabled weak ref access";
1771 }
1772}
1773
1774void ConcurrentCopying::SwitchToGcExclusiveMarkStackMode() {
1775 Thread* self = Thread::Current();
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08001776 DCHECK(thread_running_gc_ != nullptr);
1777 DCHECK(self == thread_running_gc_);
1778 DCHECK(thread_running_gc_->GetThreadLocalMarkStack() == nullptr);
Orion Hodson88591fe2018-03-06 13:35:43 +00001779 MarkStackMode before_mark_stack_mode = mark_stack_mode_.load(std::memory_order_relaxed);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001780 CHECK_EQ(static_cast<uint32_t>(before_mark_stack_mode),
1781 static_cast<uint32_t>(kMarkStackModeShared));
Orion Hodson88591fe2018-03-06 13:35:43 +00001782 mark_stack_mode_.store(kMarkStackModeGcExclusive, std::memory_order_relaxed);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001783 QuasiAtomic::ThreadFenceForConstructor();
1784 if (kVerboseMode) {
1785 LOG(INFO) << "Switched to GC exclusive mark stack mode";
1786 }
1787}
1788
1789void ConcurrentCopying::CheckEmptyMarkStack() {
1790 Thread* self = Thread::Current();
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08001791 DCHECK(thread_running_gc_ != nullptr);
1792 DCHECK(self == thread_running_gc_);
1793 DCHECK(thread_running_gc_->GetThreadLocalMarkStack() == nullptr);
Orion Hodson88591fe2018-03-06 13:35:43 +00001794 MarkStackMode mark_stack_mode = mark_stack_mode_.load(std::memory_order_relaxed);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001795 if (mark_stack_mode == kMarkStackModeThreadLocal) {
1796 // Thread-local mark stack mode.
Hiroshi Yamauchifebd0cf2016-09-14 19:31:25 -07001797 RevokeThreadLocalMarkStacks(false, nullptr);
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08001798 MutexLock mu(thread_running_gc_, mark_stack_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001799 if (!revoked_mark_stacks_.empty()) {
1800 for (accounting::AtomicStack<mirror::Object>* mark_stack : revoked_mark_stacks_) {
1801 while (!mark_stack->IsEmpty()) {
1802 mirror::Object* obj = mark_stack->PopBack();
1803 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001804 uint32_t rb_state = obj->GetReadBarrierState();
1805 LOG(INFO) << "On mark queue : " << obj << " " << obj->PrettyTypeOf() << " rb_state="
1806 << rb_state << " is_marked=" << IsMarked(obj);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001807 } else {
David Sehr709b0702016-10-13 09:12:37 -07001808 LOG(INFO) << "On mark queue : " << obj << " " << obj->PrettyTypeOf()
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001809 << " is_marked=" << IsMarked(obj);
1810 }
1811 }
1812 }
1813 LOG(FATAL) << "mark stack is not empty";
1814 }
1815 } else {
1816 // Shared, GC-exclusive, or off.
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08001817 MutexLock mu(thread_running_gc_, mark_stack_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001818 CHECK(gc_mark_stack_->IsEmpty());
1819 CHECK(revoked_mark_stacks_.empty());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001820 }
1821}
1822
1823void ConcurrentCopying::SweepSystemWeaks(Thread* self) {
1824 TimingLogger::ScopedTiming split("SweepSystemWeaks", GetTimings());
1825 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier97509952015-07-13 14:35:43 -07001826 Runtime::Current()->SweepSystemWeaks(this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001827}
1828
1829void ConcurrentCopying::Sweep(bool swap_bitmaps) {
Roland Levillainb1e1dc32018-07-10 19:19:31 +01001830 if (kEnableGenerationalConcurrentCopyingCollection && young_gen_) {
1831 // Only sweep objects on the live stack.
1832 SweepArray(heap_->GetLiveStack(), /* swap_bitmaps */ false);
1833 } else {
1834 {
1835 TimingLogger::ScopedTiming t("MarkStackAsLive", GetTimings());
1836 accounting::ObjectStack* live_stack = heap_->GetLiveStack();
1837 if (kEnableFromSpaceAccountingCheck) {
1838 // Ensure that nobody inserted items in the live stack after we swapped the stacks.
1839 CHECK_GE(live_stack_freeze_size_, live_stack->Size());
1840 }
1841 heap_->MarkAllocStackAsLive(live_stack);
1842 live_stack->Reset();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001843 }
Roland Levillainb1e1dc32018-07-10 19:19:31 +01001844 CheckEmptyMarkStack();
1845 TimingLogger::ScopedTiming split("Sweep", GetTimings());
1846 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
1847 if (space->IsContinuousMemMapAllocSpace()) {
1848 space::ContinuousMemMapAllocSpace* alloc_space = space->AsContinuousMemMapAllocSpace();
1849 if (space == region_space_ || immune_spaces_.ContainsSpace(space)) {
1850 continue;
1851 }
1852 TimingLogger::ScopedTiming split2(
1853 alloc_space->IsZygoteSpace() ? "SweepZygoteSpace" : "SweepAllocSpace", GetTimings());
1854 RecordFree(alloc_space->Sweep(swap_bitmaps));
1855 }
1856 }
1857 SweepLargeObjects(swap_bitmaps);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001858 }
Roland Levillainb1e1dc32018-07-10 19:19:31 +01001859}
1860
1861// Copied and adapted from MarkSweep::SweepArray.
1862void ConcurrentCopying::SweepArray(accounting::ObjectStack* allocations, bool swap_bitmaps) {
1863 // This method is only used when Generational CC collection is enabled.
1864 DCHECK(kEnableGenerationalConcurrentCopyingCollection);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001865 CheckEmptyMarkStack();
Roland Levillainb1e1dc32018-07-10 19:19:31 +01001866 TimingLogger::ScopedTiming t("SweepArray", GetTimings());
1867 Thread* self = Thread::Current();
1868 mirror::Object** chunk_free_buffer = reinterpret_cast<mirror::Object**>(
1869 sweep_array_free_buffer_mem_map_.BaseBegin());
1870 size_t chunk_free_pos = 0;
1871 ObjectBytePair freed;
1872 ObjectBytePair freed_los;
1873 // How many objects are left in the array, modified after each space is swept.
1874 StackReference<mirror::Object>* objects = allocations->Begin();
1875 size_t count = allocations->Size();
1876 // Start by sweeping the continuous spaces.
1877 for (space::ContinuousSpace* space : heap_->GetContinuousSpaces()) {
1878 if (!space->IsAllocSpace() ||
1879 space == region_space_ ||
1880 immune_spaces_.ContainsSpace(space) ||
1881 space->GetLiveBitmap() == nullptr) {
1882 continue;
1883 }
1884 space::AllocSpace* alloc_space = space->AsAllocSpace();
1885 accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
1886 accounting::ContinuousSpaceBitmap* mark_bitmap = space->GetMarkBitmap();
1887 if (swap_bitmaps) {
1888 std::swap(live_bitmap, mark_bitmap);
1889 }
1890 StackReference<mirror::Object>* out = objects;
1891 for (size_t i = 0; i < count; ++i) {
1892 mirror::Object* const obj = objects[i].AsMirrorPtr();
1893 if (kUseThreadLocalAllocationStack && obj == nullptr) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001894 continue;
1895 }
Roland Levillainb1e1dc32018-07-10 19:19:31 +01001896 if (space->HasAddress(obj)) {
1897 // This object is in the space, remove it from the array and add it to the sweep buffer
1898 // if needed.
1899 if (!mark_bitmap->Test(obj)) {
1900 if (chunk_free_pos >= kSweepArrayChunkFreeSize) {
1901 TimingLogger::ScopedTiming t2("FreeList", GetTimings());
1902 freed.objects += chunk_free_pos;
1903 freed.bytes += alloc_space->FreeList(self, chunk_free_pos, chunk_free_buffer);
1904 chunk_free_pos = 0;
1905 }
1906 chunk_free_buffer[chunk_free_pos++] = obj;
1907 }
1908 } else {
1909 (out++)->Assign(obj);
1910 }
1911 }
1912 if (chunk_free_pos > 0) {
1913 TimingLogger::ScopedTiming t2("FreeList", GetTimings());
1914 freed.objects += chunk_free_pos;
1915 freed.bytes += alloc_space->FreeList(self, chunk_free_pos, chunk_free_buffer);
1916 chunk_free_pos = 0;
1917 }
1918 // All of the references which space contained are no longer in the allocation stack, update
1919 // the count.
1920 count = out - objects;
1921 }
1922 // Handle the large object space.
1923 space::LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
1924 if (large_object_space != nullptr) {
1925 accounting::LargeObjectBitmap* large_live_objects = large_object_space->GetLiveBitmap();
1926 accounting::LargeObjectBitmap* large_mark_objects = large_object_space->GetMarkBitmap();
1927 if (swap_bitmaps) {
1928 std::swap(large_live_objects, large_mark_objects);
1929 }
1930 for (size_t i = 0; i < count; ++i) {
1931 mirror::Object* const obj = objects[i].AsMirrorPtr();
1932 // Handle large objects.
1933 if (kUseThreadLocalAllocationStack && obj == nullptr) {
1934 continue;
1935 }
1936 if (!large_mark_objects->Test(obj)) {
1937 ++freed_los.objects;
1938 freed_los.bytes += large_object_space->Free(self, obj);
1939 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001940 }
1941 }
Roland Levillainb1e1dc32018-07-10 19:19:31 +01001942 {
1943 TimingLogger::ScopedTiming t2("RecordFree", GetTimings());
1944 RecordFree(freed);
1945 RecordFreeLOS(freed_los);
1946 t2.NewTiming("ResetStack");
1947 allocations->Reset();
1948 }
1949 sweep_array_free_buffer_mem_map_.MadviseDontNeedAndZero();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001950}
1951
Mathieu Chartier962cd7a2016-08-16 12:15:59 -07001952void ConcurrentCopying::MarkZygoteLargeObjects() {
1953 TimingLogger::ScopedTiming split(__FUNCTION__, GetTimings());
1954 Thread* const self = Thread::Current();
1955 WriterMutexLock rmu(self, *Locks::heap_bitmap_lock_);
1956 space::LargeObjectSpace* const los = heap_->GetLargeObjectsSpace();
Nicolas Geoffray7acddd82017-05-03 15:04:55 +01001957 if (los != nullptr) {
1958 // Pick the current live bitmap (mark bitmap if swapped).
1959 accounting::LargeObjectBitmap* const live_bitmap = los->GetLiveBitmap();
1960 accounting::LargeObjectBitmap* const mark_bitmap = los->GetMarkBitmap();
1961 // Walk through all of the objects and explicitly mark the zygote ones so they don't get swept.
1962 std::pair<uint8_t*, uint8_t*> range = los->GetBeginEndAtomic();
1963 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(range.first),
1964 reinterpret_cast<uintptr_t>(range.second),
1965 [mark_bitmap, los, self](mirror::Object* obj)
1966 REQUIRES(Locks::heap_bitmap_lock_)
1967 REQUIRES_SHARED(Locks::mutator_lock_) {
1968 if (los->IsZygoteLargeObject(self, obj)) {
1969 mark_bitmap->Set(obj);
1970 }
1971 });
1972 }
Mathieu Chartier962cd7a2016-08-16 12:15:59 -07001973}
1974
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001975void ConcurrentCopying::SweepLargeObjects(bool swap_bitmaps) {
1976 TimingLogger::ScopedTiming split("SweepLargeObjects", GetTimings());
Nicolas Geoffray7acddd82017-05-03 15:04:55 +01001977 if (heap_->GetLargeObjectsSpace() != nullptr) {
1978 RecordFreeLOS(heap_->GetLargeObjectsSpace()->Sweep(swap_bitmaps));
1979 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001980}
1981
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001982void ConcurrentCopying::ReclaimPhase() {
1983 TimingLogger::ScopedTiming split("ReclaimPhase", GetTimings());
1984 if (kVerboseMode) {
1985 LOG(INFO) << "GC ReclaimPhase";
1986 }
1987 Thread* self = Thread::Current();
1988
1989 {
1990 // Double-check that the mark stack is empty.
1991 // Note: need to set this after VerifyNoFromSpaceRef().
1992 is_asserting_to_space_invariant_ = false;
1993 QuasiAtomic::ThreadFenceForConstructor();
1994 if (kVerboseMode) {
1995 LOG(INFO) << "Issue an empty check point. ";
1996 }
1997 IssueEmptyCheckpoint();
1998 // Disable the check.
Orion Hodson88591fe2018-03-06 13:35:43 +00001999 is_mark_stack_push_disallowed_.store(0, std::memory_order_seq_cst);
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002000 if (kUseBakerReadBarrier) {
Orion Hodson88591fe2018-03-06 13:35:43 +00002001 updated_all_immune_objects_.store(false, std::memory_order_seq_cst);
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002002 }
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002003 CheckEmptyMarkStack();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002004 }
2005
2006 {
2007 // Record freed objects.
2008 TimingLogger::ScopedTiming split2("RecordFree", GetTimings());
2009 // Don't include thread-locals that are in the to-space.
Mathieu Chartier371b0472017-02-27 16:37:21 -08002010 const uint64_t from_bytes = region_space_->GetBytesAllocatedInFromSpace();
2011 const uint64_t from_objects = region_space_->GetObjectsAllocatedInFromSpace();
2012 const uint64_t unevac_from_bytes = region_space_->GetBytesAllocatedInUnevacFromSpace();
2013 const uint64_t unevac_from_objects = region_space_->GetObjectsAllocatedInUnevacFromSpace();
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002014 uint64_t to_bytes = bytes_moved_.load(std::memory_order_seq_cst) + bytes_moved_gc_thread_;
Orion Hodson88591fe2018-03-06 13:35:43 +00002015 cumulative_bytes_moved_.fetch_add(to_bytes, std::memory_order_relaxed);
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002016 uint64_t to_objects = objects_moved_.load(std::memory_order_seq_cst) + objects_moved_gc_thread_;
Orion Hodson88591fe2018-03-06 13:35:43 +00002017 cumulative_objects_moved_.fetch_add(to_objects, std::memory_order_relaxed);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002018 if (kEnableFromSpaceAccountingCheck) {
2019 CHECK_EQ(from_space_num_objects_at_first_pause_, from_objects + unevac_from_objects);
2020 CHECK_EQ(from_space_num_bytes_at_first_pause_, from_bytes + unevac_from_bytes);
2021 }
2022 CHECK_LE(to_objects, from_objects);
2023 CHECK_LE(to_bytes, from_bytes);
Roland Levillain8f7ea9a2018-01-26 17:27:59 +00002024 // Cleared bytes and objects, populated by the call to RegionSpace::ClearFromSpace below.
Mathieu Chartier371b0472017-02-27 16:37:21 -08002025 uint64_t cleared_bytes;
2026 uint64_t cleared_objects;
2027 {
2028 TimingLogger::ScopedTiming split4("ClearFromSpace", GetTimings());
2029 region_space_->ClearFromSpace(&cleared_bytes, &cleared_objects);
Roland Levillain8f7ea9a2018-01-26 17:27:59 +00002030 // `cleared_bytes` and `cleared_objects` may be greater than the from space equivalents since
2031 // RegionSpace::ClearFromSpace may clear empty unevac regions.
Mathieu Chartier371b0472017-02-27 16:37:21 -08002032 CHECK_GE(cleared_bytes, from_bytes);
2033 CHECK_GE(cleared_objects, from_objects);
2034 }
2035 int64_t freed_bytes = cleared_bytes - to_bytes;
2036 int64_t freed_objects = cleared_objects - to_objects;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002037 if (kVerboseMode) {
2038 LOG(INFO) << "RecordFree:"
2039 << " from_bytes=" << from_bytes << " from_objects=" << from_objects
Roland Levillain2ae376f2018-01-30 11:35:11 +00002040 << " unevac_from_bytes=" << unevac_from_bytes
2041 << " unevac_from_objects=" << unevac_from_objects
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002042 << " to_bytes=" << to_bytes << " to_objects=" << to_objects
2043 << " freed_bytes=" << freed_bytes << " freed_objects=" << freed_objects
2044 << " from_space size=" << region_space_->FromSpaceSize()
2045 << " unevac_from_space size=" << region_space_->UnevacFromSpaceSize()
2046 << " to_space size=" << region_space_->ToSpaceSize();
Roland Levillain2ae376f2018-01-30 11:35:11 +00002047 LOG(INFO) << "(before) num_bytes_allocated="
Orion Hodson88591fe2018-03-06 13:35:43 +00002048 << heap_->num_bytes_allocated_.load(std::memory_order_seq_cst);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002049 }
2050 RecordFree(ObjectBytePair(freed_objects, freed_bytes));
2051 if (kVerboseMode) {
Roland Levillain2ae376f2018-01-30 11:35:11 +00002052 LOG(INFO) << "(after) num_bytes_allocated="
Orion Hodson88591fe2018-03-06 13:35:43 +00002053 << heap_->num_bytes_allocated_.load(std::memory_order_seq_cst);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002054 }
2055 }
2056
2057 {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002058 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Roland Levillainb1e1dc32018-07-10 19:19:31 +01002059 Sweep(/* swap_bitmaps */ false);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002060 SwapBitmaps();
2061 heap_->UnBindBitmaps();
2062
Mathieu Chartier7ec38dc2016-10-07 15:24:46 -07002063 // 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 -07002064 DCHECK(region_space_bitmap_ != nullptr);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002065 region_space_bitmap_ = nullptr;
2066 }
2067
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002068 CheckEmptyMarkStack();
2069
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002070 if (kVerboseMode) {
2071 LOG(INFO) << "GC end of ReclaimPhase";
2072 }
2073}
2074
Roland Levillain001eff92018-01-24 14:24:33 +00002075std::string ConcurrentCopying::DumpReferenceInfo(mirror::Object* ref,
2076 const char* ref_name,
Andreas Gampebc802de2018-06-20 17:24:11 -07002077 const char* indent) {
Roland Levillain001eff92018-01-24 14:24:33 +00002078 std::ostringstream oss;
2079 oss << indent << heap_->GetVerification()->DumpObjectInfo(ref, ref_name) << '\n';
2080 if (ref != nullptr) {
2081 if (kUseBakerReadBarrier) {
2082 oss << indent << ref_name << "->GetMarkBit()=" << ref->GetMarkBit() << '\n';
2083 oss << indent << ref_name << "->GetReadBarrierState()=" << ref->GetReadBarrierState() << '\n';
2084 }
2085 }
2086 if (region_space_->HasAddress(ref)) {
2087 oss << indent << "Region containing " << ref_name << ":" << '\n';
2088 region_space_->DumpRegionForObject(oss, ref);
2089 if (region_space_bitmap_ != nullptr) {
2090 oss << indent << "region_space_bitmap_->Test(" << ref_name << ")="
2091 << std::boolalpha << region_space_bitmap_->Test(ref) << std::noboolalpha;
2092 }
2093 }
2094 return oss.str();
2095}
2096
2097std::string ConcurrentCopying::DumpHeapReference(mirror::Object* obj,
2098 MemberOffset offset,
2099 mirror::Object* ref) {
2100 std::ostringstream oss;
Andreas Gampebc802de2018-06-20 17:24:11 -07002101 constexpr const char* kIndent = " ";
2102 oss << kIndent << "Invalid reference: ref=" << ref
Roland Levillain001eff92018-01-24 14:24:33 +00002103 << " referenced from: object=" << obj << " offset= " << offset << '\n';
2104 // Information about `obj`.
Andreas Gampebc802de2018-06-20 17:24:11 -07002105 oss << DumpReferenceInfo(obj, "obj", kIndent) << '\n';
Roland Levillain001eff92018-01-24 14:24:33 +00002106 // Information about `ref`.
Andreas Gampebc802de2018-06-20 17:24:11 -07002107 oss << DumpReferenceInfo(ref, "ref", kIndent);
Roland Levillain001eff92018-01-24 14:24:33 +00002108 return oss.str();
2109}
2110
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07002111void ConcurrentCopying::AssertToSpaceInvariant(mirror::Object* obj,
2112 MemberOffset offset,
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002113 mirror::Object* ref) {
Roland Levillain001eff92018-01-24 14:24:33 +00002114 CHECK_EQ(heap_->collector_type_, kCollectorTypeCC) << static_cast<size_t>(heap_->collector_type_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002115 if (is_asserting_to_space_invariant_) {
Roland Levillain001eff92018-01-24 14:24:33 +00002116 if (region_space_->HasAddress(ref)) {
2117 // Check to-space invariant in region space (moving space).
2118 using RegionType = space::RegionSpace::RegionType;
Roland Levillain2dd2e1e2018-02-28 16:24:51 +00002119 space::RegionSpace::RegionType type = region_space_->GetRegionTypeUnsafe(ref);
Roland Levillain001eff92018-01-24 14:24:33 +00002120 if (type == RegionType::kRegionTypeToSpace) {
2121 // OK.
2122 return;
2123 } else if (type == RegionType::kRegionTypeUnevacFromSpace) {
2124 if (!IsMarkedInUnevacFromSpace(ref)) {
2125 LOG(FATAL_WITHOUT_ABORT) << "Found unmarked reference in unevac from-space:";
Roland Levillainca3dded2018-08-10 15:35:17 +01002126 // Remove memory protection from the region space and log debugging information.
2127 region_space_->Unprotect();
Roland Levillain001eff92018-01-24 14:24:33 +00002128 LOG(FATAL_WITHOUT_ABORT) << DumpHeapReference(obj, offset, ref);
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002129 Thread::Current()->DumpJavaStack(LOG_STREAM(FATAL_WITHOUT_ABORT));
Roland Levillain001eff92018-01-24 14:24:33 +00002130 }
2131 CHECK(IsMarkedInUnevacFromSpace(ref)) << ref;
2132 } else {
2133 // Not OK: either a from-space ref or a reference in an unused region.
Roland Levillain001eff92018-01-24 14:24:33 +00002134 if (type == RegionType::kRegionTypeFromSpace) {
2135 LOG(FATAL_WITHOUT_ABORT) << "Found from-space reference:";
2136 } else {
2137 LOG(FATAL_WITHOUT_ABORT) << "Found reference in region with type " << type << ":";
2138 }
Roland Levillainca3dded2018-08-10 15:35:17 +01002139 // Remove memory protection from the region space and log debugging information.
2140 region_space_->Unprotect();
Roland Levillain001eff92018-01-24 14:24:33 +00002141 LOG(FATAL_WITHOUT_ABORT) << DumpHeapReference(obj, offset, ref);
2142 if (obj != nullptr) {
2143 LogFromSpaceRefHolder(obj, offset);
Roland Levillain57ce0542018-08-07 16:20:31 +01002144 LOG(FATAL_WITHOUT_ABORT) << "UNEVAC " << region_space_->IsInUnevacFromSpace(obj) << " "
2145 << obj << " " << obj->GetMarkBit();
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002146 if (region_space_->HasAddress(obj)) {
Roland Levillain57ce0542018-08-07 16:20:31 +01002147 region_space_->DumpRegionForObject(LOG_STREAM(FATAL_WITHOUT_ABORT), obj);
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002148 }
Roland Levillain57ce0542018-08-07 16:20:31 +01002149 LOG(FATAL_WITHOUT_ABORT) << "CARD " << static_cast<size_t>(
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002150 *Runtime::Current()->GetHeap()->GetCardTable()->CardFromAddr(
2151 reinterpret_cast<uint8_t*>(obj)));
Roland Levillain57ce0542018-08-07 16:20:31 +01002152 if (region_space_->HasAddress(obj)) {
2153 LOG(FATAL_WITHOUT_ABORT) << "BITMAP " << region_space_bitmap_->Test(obj);
2154 } else {
2155 accounting::ContinuousSpaceBitmap* mark_bitmap =
2156 heap_mark_bitmap_->GetContinuousSpaceBitmap(obj);
2157 if (mark_bitmap != nullptr) {
2158 LOG(FATAL_WITHOUT_ABORT) << "BITMAP " << mark_bitmap->Test(obj);
2159 } else {
2160 accounting::LargeObjectBitmap* los_bitmap =
2161 heap_mark_bitmap_->GetLargeObjectBitmap(obj);
2162 LOG(FATAL_WITHOUT_ABORT) << "BITMAP " << los_bitmap->Test(obj);
2163 }
2164 }
Roland Levillain001eff92018-01-24 14:24:33 +00002165 }
2166 ref->GetLockWord(false).Dump(LOG_STREAM(FATAL_WITHOUT_ABORT));
2167 LOG(FATAL_WITHOUT_ABORT) << "Non-free regions:";
2168 region_space_->DumpNonFreeRegions(LOG_STREAM(FATAL_WITHOUT_ABORT));
2169 PrintFileToLog("/proc/self/maps", LogSeverity::FATAL_WITHOUT_ABORT);
Roland Levillain680e0992018-08-24 15:41:26 +01002170 MemMap::DumpMaps(LOG_STREAM(FATAL_WITHOUT_ABORT), /* terse */ true);
Roland Levillain001eff92018-01-24 14:24:33 +00002171 LOG(FATAL) << "Invalid reference " << ref
2172 << " referenced from object " << obj << " at offset " << offset;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002173 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002174 } else {
Roland Levillain001eff92018-01-24 14:24:33 +00002175 // Check to-space invariant in non-moving space.
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002176 AssertToSpaceInvariantInNonMovingSpace(obj, ref);
2177 }
2178 }
2179}
2180
2181class RootPrinter {
2182 public:
2183 RootPrinter() { }
2184
2185 template <class MirrorType>
2186 ALWAYS_INLINE void VisitRootIfNonNull(mirror::CompressedReference<MirrorType>* root)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002187 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002188 if (!root->IsNull()) {
2189 VisitRoot(root);
2190 }
2191 }
2192
2193 template <class MirrorType>
2194 void VisitRoot(mirror::Object** root)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002195 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07002196 LOG(FATAL_WITHOUT_ABORT) << "root=" << root << " ref=" << *root;
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002197 }
2198
2199 template <class MirrorType>
2200 void VisitRoot(mirror::CompressedReference<MirrorType>* root)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002201 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07002202 LOG(FATAL_WITHOUT_ABORT) << "root=" << root << " ref=" << root->AsMirrorPtr();
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002203 }
2204};
2205
Roland Levillain001eff92018-01-24 14:24:33 +00002206std::string ConcurrentCopying::DumpGcRoot(mirror::Object* ref) {
2207 std::ostringstream oss;
Andreas Gampebc802de2018-06-20 17:24:11 -07002208 constexpr const char* kIndent = " ";
2209 oss << kIndent << "Invalid GC root: ref=" << ref << '\n';
Roland Levillain001eff92018-01-24 14:24:33 +00002210 // Information about `ref`.
Andreas Gampebc802de2018-06-20 17:24:11 -07002211 oss << DumpReferenceInfo(ref, "ref", kIndent);
Roland Levillain001eff92018-01-24 14:24:33 +00002212 return oss.str();
2213}
2214
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002215void ConcurrentCopying::AssertToSpaceInvariant(GcRootSource* gc_root_source,
2216 mirror::Object* ref) {
Roland Levillain001eff92018-01-24 14:24:33 +00002217 CHECK_EQ(heap_->collector_type_, kCollectorTypeCC) << static_cast<size_t>(heap_->collector_type_);
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002218 if (is_asserting_to_space_invariant_) {
Roland Levillain001eff92018-01-24 14:24:33 +00002219 if (region_space_->HasAddress(ref)) {
2220 // Check to-space invariant in region space (moving space).
2221 using RegionType = space::RegionSpace::RegionType;
Roland Levillain2dd2e1e2018-02-28 16:24:51 +00002222 space::RegionSpace::RegionType type = region_space_->GetRegionTypeUnsafe(ref);
Roland Levillain001eff92018-01-24 14:24:33 +00002223 if (type == RegionType::kRegionTypeToSpace) {
2224 // OK.
2225 return;
2226 } else if (type == RegionType::kRegionTypeUnevacFromSpace) {
2227 if (!IsMarkedInUnevacFromSpace(ref)) {
2228 LOG(FATAL_WITHOUT_ABORT) << "Found unmarked reference in unevac from-space:";
Roland Levillainca3dded2018-08-10 15:35:17 +01002229 // Remove memory protection from the region space and log debugging information.
2230 region_space_->Unprotect();
Roland Levillain001eff92018-01-24 14:24:33 +00002231 LOG(FATAL_WITHOUT_ABORT) << DumpGcRoot(ref);
2232 }
2233 CHECK(IsMarkedInUnevacFromSpace(ref)) << ref;
2234 } else {
2235 // Not OK: either a from-space ref or a reference in an unused region.
Roland Levillain001eff92018-01-24 14:24:33 +00002236 if (type == RegionType::kRegionTypeFromSpace) {
2237 LOG(FATAL_WITHOUT_ABORT) << "Found from-space reference:";
2238 } else {
2239 LOG(FATAL_WITHOUT_ABORT) << "Found reference in region with type " << type << ":";
2240 }
Roland Levillainca3dded2018-08-10 15:35:17 +01002241 // Remove memory protection from the region space and log debugging information.
2242 region_space_->Unprotect();
Roland Levillain001eff92018-01-24 14:24:33 +00002243 LOG(FATAL_WITHOUT_ABORT) << DumpGcRoot(ref);
2244 if (gc_root_source == nullptr) {
2245 // No info.
2246 } else if (gc_root_source->HasArtField()) {
2247 ArtField* field = gc_root_source->GetArtField();
2248 LOG(FATAL_WITHOUT_ABORT) << "gc root in field " << field << " "
2249 << ArtField::PrettyField(field);
2250 RootPrinter root_printer;
2251 field->VisitRoots(root_printer);
2252 } else if (gc_root_source->HasArtMethod()) {
2253 ArtMethod* method = gc_root_source->GetArtMethod();
2254 LOG(FATAL_WITHOUT_ABORT) << "gc root in method " << method << " "
2255 << ArtMethod::PrettyMethod(method);
2256 RootPrinter root_printer;
2257 method->VisitRoots(root_printer, kRuntimePointerSize);
2258 }
2259 ref->GetLockWord(false).Dump(LOG_STREAM(FATAL_WITHOUT_ABORT));
2260 LOG(FATAL_WITHOUT_ABORT) << "Non-free regions:";
2261 region_space_->DumpNonFreeRegions(LOG_STREAM(FATAL_WITHOUT_ABORT));
2262 PrintFileToLog("/proc/self/maps", LogSeverity::FATAL_WITHOUT_ABORT);
Roland Levillain680e0992018-08-24 15:41:26 +01002263 MemMap::DumpMaps(LOG_STREAM(FATAL_WITHOUT_ABORT), /* terse */ true);
Roland Levillain001eff92018-01-24 14:24:33 +00002264 LOG(FATAL) << "Invalid reference " << ref;
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002265 }
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002266 } else {
Roland Levillain001eff92018-01-24 14:24:33 +00002267 // Check to-space invariant in non-moving space.
2268 AssertToSpaceInvariantInNonMovingSpace(/* obj */ nullptr, ref);
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002269 }
2270 }
2271}
2272
2273void ConcurrentCopying::LogFromSpaceRefHolder(mirror::Object* obj, MemberOffset offset) {
2274 if (kUseBakerReadBarrier) {
David Sehr709b0702016-10-13 09:12:37 -07002275 LOG(INFO) << "holder=" << obj << " " << obj->PrettyTypeOf()
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002276 << " holder rb_state=" << obj->GetReadBarrierState();
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002277 } else {
David Sehr709b0702016-10-13 09:12:37 -07002278 LOG(INFO) << "holder=" << obj << " " << obj->PrettyTypeOf();
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002279 }
2280 if (region_space_->IsInFromSpace(obj)) {
2281 LOG(INFO) << "holder is in the from-space.";
2282 } else if (region_space_->IsInToSpace(obj)) {
2283 LOG(INFO) << "holder is in the to-space.";
2284 } else if (region_space_->IsInUnevacFromSpace(obj)) {
2285 LOG(INFO) << "holder is in the unevac from-space.";
Mathieu Chartierc381c362016-08-23 13:27:53 -07002286 if (IsMarkedInUnevacFromSpace(obj)) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002287 LOG(INFO) << "holder is marked in the region space bitmap.";
2288 } else {
2289 LOG(INFO) << "holder is not marked in the region space bitmap.";
2290 }
2291 } else {
2292 // In a non-moving space.
Mathieu Chartier763a31e2015-11-16 16:05:55 -08002293 if (immune_spaces_.ContainsObject(obj)) {
2294 LOG(INFO) << "holder is in an immune image or the zygote space.";
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002295 } else {
Mathieu Chartier763a31e2015-11-16 16:05:55 -08002296 LOG(INFO) << "holder is in a non-immune, non-moving (or main) space.";
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002297 accounting::ContinuousSpaceBitmap* mark_bitmap =
2298 heap_mark_bitmap_->GetContinuousSpaceBitmap(obj);
2299 accounting::LargeObjectBitmap* los_bitmap =
2300 heap_mark_bitmap_->GetLargeObjectBitmap(obj);
2301 CHECK(los_bitmap != nullptr) << "LOS bitmap covers the entire address range";
2302 bool is_los = mark_bitmap == nullptr;
2303 if (!is_los && mark_bitmap->Test(obj)) {
2304 LOG(INFO) << "holder is marked in the mark bit map.";
2305 } else if (is_los && los_bitmap->Test(obj)) {
2306 LOG(INFO) << "holder is marked in the los bit map.";
2307 } else {
2308 // If ref is on the allocation stack, then it is considered
2309 // mark/alive (but not necessarily on the live stack.)
2310 if (IsOnAllocStack(obj)) {
2311 LOG(INFO) << "holder is on the alloc stack.";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002312 } else {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002313 LOG(INFO) << "holder is not marked or on the alloc stack.";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002314 }
2315 }
2316 }
2317 }
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002318 LOG(INFO) << "offset=" << offset.SizeValue();
2319}
2320
2321void ConcurrentCopying::AssertToSpaceInvariantInNonMovingSpace(mirror::Object* obj,
2322 mirror::Object* ref) {
Roland Levillainbe4b8fd2018-09-03 14:38:37 +01002323 CHECK(ref != nullptr);
Roland Levillain001eff92018-01-24 14:24:33 +00002324 CHECK(!region_space_->HasAddress(ref)) << "obj=" << obj << " ref=" << ref;
Roland Levillainef012222017-06-21 16:28:06 +01002325 // In a non-moving space. Check that the ref is marked.
Mathieu Chartier763a31e2015-11-16 16:05:55 -08002326 if (immune_spaces_.ContainsObject(ref)) {
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002327 if (kUseBakerReadBarrier) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002328 // Immune object may not be gray if called from the GC.
2329 if (Thread::Current() == thread_running_gc_ && !gc_grays_immune_objects_) {
2330 return;
2331 }
Orion Hodson88591fe2018-03-06 13:35:43 +00002332 bool updated_all_immune_objects = updated_all_immune_objects_.load(std::memory_order_seq_cst);
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002333 CHECK(updated_all_immune_objects || ref->GetReadBarrierState() == ReadBarrier::GrayState())
2334 << "Unmarked immune space ref. obj=" << obj << " rb_state="
2335 << (obj != nullptr ? obj->GetReadBarrierState() : 0U)
2336 << " ref=" << ref << " ref rb_state=" << ref->GetReadBarrierState()
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002337 << " updated_all_immune_objects=" << updated_all_immune_objects;
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002338 }
2339 } else {
2340 accounting::ContinuousSpaceBitmap* mark_bitmap =
2341 heap_mark_bitmap_->GetContinuousSpaceBitmap(ref);
2342 accounting::LargeObjectBitmap* los_bitmap =
2343 heap_mark_bitmap_->GetLargeObjectBitmap(ref);
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002344 bool is_los = mark_bitmap == nullptr;
2345 if ((!is_los && mark_bitmap->Test(ref)) ||
2346 (is_los && los_bitmap->Test(ref))) {
2347 // OK.
2348 } else {
Roland Levillain2ae376f2018-01-30 11:35:11 +00002349 // If `ref` is on the allocation stack, then it may not be
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002350 // marked live, but considered marked/alive (but not
2351 // necessarily on the live stack).
Roland Levillaine2f6b492018-08-31 14:12:57 +01002352 CHECK(IsOnAllocStack(ref))
2353 << "Unmarked ref that's not on the allocation stack."
2354 << " obj=" << obj
2355 << " ref=" << ref
Roland Levillainbe4b8fd2018-09-03 14:38:37 +01002356 << " rb_state=" << ref->GetReadBarrierState()
Roland Levillaine2f6b492018-08-31 14:12:57 +01002357 << " is_los=" << std::boolalpha << is_los << std::noboolalpha
2358 << " is_marking=" << std::boolalpha << is_marking_ << std::noboolalpha
Roland Levillainbe4b8fd2018-09-03 14:38:37 +01002359 << " young_gen=" << std::boolalpha << young_gen_ << std::noboolalpha
2360 << " self=" << Thread::Current();
Hiroshi Yamauchi3f64f252015-06-12 18:35:06 -07002361 }
2362 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002363}
2364
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002365// Used to scan ref fields of an object.
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002366template <bool kNoUnEvac>
Mathieu Chartiera07f5592016-06-16 11:44:28 -07002367class ConcurrentCopying::RefFieldsVisitor {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002368 public:
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002369 explicit RefFieldsVisitor(ConcurrentCopying* collector, Thread* const thread)
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002370 : collector_(collector), thread_(thread) {
2371 // Cannot have `kNoUnEvac` when Generational CC collection is disabled.
2372 DCHECK(kEnableGenerationalConcurrentCopyingCollection || !kNoUnEvac);
2373 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002374
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07002375 void operator()(mirror::Object* obj, MemberOffset offset, bool /* is_static */)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002376 const ALWAYS_INLINE REQUIRES_SHARED(Locks::mutator_lock_)
2377 REQUIRES_SHARED(Locks::heap_bitmap_lock_) {
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002378 collector_->Process<kNoUnEvac>(obj, offset);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002379 }
2380
Mathieu Chartier31e88222016-10-14 18:43:19 -07002381 void operator()(ObjPtr<mirror::Class> klass, ObjPtr<mirror::Reference> ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002382 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002383 CHECK(klass->IsTypeOfReferenceClass());
2384 collector_->DelayReferenceReferent(klass, ref);
2385 }
2386
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002387 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002388 ALWAYS_INLINE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002389 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002390 if (!root->IsNull()) {
2391 VisitRoot(root);
2392 }
2393 }
2394
2395 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002396 ALWAYS_INLINE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002397 REQUIRES_SHARED(Locks::mutator_lock_) {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002398 collector_->MarkRoot</*kGrayImmuneObject*/false>(thread_, root);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002399 }
2400
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002401 private:
2402 ConcurrentCopying* const collector_;
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002403 Thread* const thread_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002404};
2405
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002406template <bool kNoUnEvac>
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002407inline void ConcurrentCopying::Scan(mirror::Object* to_ref) {
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002408 // Cannot have `kNoUnEvac` when Generational CC collection is disabled.
2409 DCHECK(kEnableGenerationalConcurrentCopyingCollection || !kNoUnEvac);
Hiroshi Yamauchi9b60d502017-02-03 15:09:26 -08002410 if (kDisallowReadBarrierDuringScan && !Runtime::Current()->IsActiveTransaction()) {
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07002411 // Avoid all read barriers during visit references to help performance.
Hiroshi Yamauchi9b60d502017-02-03 15:09:26 -08002412 // Don't do this in transaction mode because we may read the old value of an field which may
2413 // trigger read barriers.
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07002414 Thread::Current()->ModifyDebugDisallowReadBarrier(1);
2415 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002416 DCHECK(!region_space_->IsInFromSpace(to_ref));
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002417 DCHECK_EQ(Thread::Current(), thread_running_gc_);
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002418 RefFieldsVisitor<kNoUnEvac> visitor(this, thread_running_gc_);
Hiroshi Yamauchi5496f692016-02-17 13:29:59 -08002419 // Disable the read barrier for a performance reason.
2420 to_ref->VisitReferences</*kVisitNativeRoots*/true, kDefaultVerifyFlags, kWithoutReadBarrier>(
2421 visitor, visitor);
Hiroshi Yamauchi9b60d502017-02-03 15:09:26 -08002422 if (kDisallowReadBarrierDuringScan && !Runtime::Current()->IsActiveTransaction()) {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002423 thread_running_gc_->ModifyDebugDisallowReadBarrier(-1);
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07002424 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002425}
2426
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002427template <bool kNoUnEvac>
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002428inline void ConcurrentCopying::Process(mirror::Object* obj, MemberOffset offset) {
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002429 // Cannot have `kNoUnEvac` when Generational CC collection is disabled.
2430 DCHECK(kEnableGenerationalConcurrentCopyingCollection || !kNoUnEvac);
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002431 DCHECK_EQ(Thread::Current(), thread_running_gc_);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002432 mirror::Object* ref = obj->GetFieldObject<
2433 mirror::Object, kVerifyNone, kWithoutReadBarrier, false>(offset);
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002434 mirror::Object* to_ref = Mark</*kGrayImmuneObject*/false, kNoUnEvac, /*kFromGCThread*/true>(
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002435 thread_running_gc_,
Mathieu Chartier4ce0c762017-05-18 10:01:07 -07002436 ref,
2437 /*holder*/ obj,
2438 offset);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002439 if (to_ref == ref) {
2440 return;
2441 }
2442 // This may fail if the mutator writes to the field at the same time. But it's ok.
2443 mirror::Object* expected_ref = ref;
2444 mirror::Object* new_ref = to_ref;
2445 do {
2446 if (expected_ref !=
2447 obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier, false>(offset)) {
2448 // It was updated by the mutator.
2449 break;
2450 }
Roland Levillain2ae376f2018-01-30 11:35:11 +00002451 // Use release CAS to make sure threads reading the reference see contents of copied objects.
Mathieu Chartiera9746b92018-06-22 10:25:40 -07002452 } while (!obj->CasFieldObjectWithoutWriteBarrier<false, false, kVerifyNone>(
Mathieu Chartierfdd513d2017-06-01 11:26:50 -07002453 offset,
2454 expected_ref,
Mathieu Chartiera9746b92018-06-22 10:25:40 -07002455 new_ref,
2456 CASMode::kWeak,
2457 std::memory_order_release));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002458}
2459
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002460// Process some roots.
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002461inline void ConcurrentCopying::VisitRoots(
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002462 mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED) {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002463 Thread* const self = Thread::Current();
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002464 for (size_t i = 0; i < count; ++i) {
2465 mirror::Object** root = roots[i];
2466 mirror::Object* ref = *root;
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002467 mirror::Object* to_ref = Mark(self, ref);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002468 if (to_ref == ref) {
Mathieu Chartier4809d0a2015-04-07 10:39:04 -07002469 continue;
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002470 }
2471 Atomic<mirror::Object*>* addr = reinterpret_cast<Atomic<mirror::Object*>*>(root);
2472 mirror::Object* expected_ref = ref;
2473 mirror::Object* new_ref = to_ref;
2474 do {
Orion Hodson88591fe2018-03-06 13:35:43 +00002475 if (expected_ref != addr->load(std::memory_order_relaxed)) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002476 // It was updated by the mutator.
2477 break;
2478 }
Orion Hodson4557b382018-01-03 11:47:54 +00002479 } while (!addr->CompareAndSetWeakRelaxed(expected_ref, new_ref));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002480 }
2481}
2482
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002483template<bool kGrayImmuneObject>
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002484inline void ConcurrentCopying::MarkRoot(Thread* const self,
2485 mirror::CompressedReference<mirror::Object>* root) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002486 DCHECK(!root->IsNull());
2487 mirror::Object* const ref = root->AsMirrorPtr();
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002488 mirror::Object* to_ref = Mark<kGrayImmuneObject>(self, ref);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002489 if (to_ref != ref) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002490 auto* addr = reinterpret_cast<Atomic<mirror::CompressedReference<mirror::Object>>*>(root);
2491 auto expected_ref = mirror::CompressedReference<mirror::Object>::FromMirrorPtr(ref);
2492 auto new_ref = mirror::CompressedReference<mirror::Object>::FromMirrorPtr(to_ref);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002493 // If the cas fails, then it was updated by the mutator.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002494 do {
Orion Hodson88591fe2018-03-06 13:35:43 +00002495 if (ref != addr->load(std::memory_order_relaxed).AsMirrorPtr()) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002496 // It was updated by the mutator.
2497 break;
2498 }
Orion Hodson4557b382018-01-03 11:47:54 +00002499 } while (!addr->CompareAndSetWeakRelaxed(expected_ref, new_ref));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002500 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002501}
2502
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002503inline void ConcurrentCopying::VisitRoots(
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002504 mirror::CompressedReference<mirror::Object>** roots, size_t count,
2505 const RootInfo& info ATTRIBUTE_UNUSED) {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002506 Thread* const self = Thread::Current();
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002507 for (size_t i = 0; i < count; ++i) {
2508 mirror::CompressedReference<mirror::Object>* const root = roots[i];
2509 if (!root->IsNull()) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002510 // kGrayImmuneObject is true because this is used for the thread flip.
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002511 MarkRoot</*kGrayImmuneObject*/true>(self, root);
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002512 }
2513 }
2514}
2515
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002516// Temporary set gc_grays_immune_objects_ to true in a scope if the current thread is GC.
2517class ConcurrentCopying::ScopedGcGraysImmuneObjects {
2518 public:
2519 explicit ScopedGcGraysImmuneObjects(ConcurrentCopying* collector)
2520 : collector_(collector), enabled_(false) {
2521 if (kUseBakerReadBarrier &&
2522 collector_->thread_running_gc_ == Thread::Current() &&
2523 !collector_->gc_grays_immune_objects_) {
2524 collector_->gc_grays_immune_objects_ = true;
2525 enabled_ = true;
2526 }
2527 }
2528
2529 ~ScopedGcGraysImmuneObjects() {
2530 if (kUseBakerReadBarrier &&
2531 collector_->thread_running_gc_ == Thread::Current() &&
2532 enabled_) {
2533 DCHECK(collector_->gc_grays_immune_objects_);
2534 collector_->gc_grays_immune_objects_ = false;
2535 }
2536 }
2537
2538 private:
2539 ConcurrentCopying* const collector_;
2540 bool enabled_;
2541};
2542
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002543// Fill the given memory block with a dummy object. Used to fill in a
2544// copy of objects that was lost in race.
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002545void ConcurrentCopying::FillWithDummyObject(Thread* const self,
2546 mirror::Object* dummy_obj,
2547 size_t byte_size) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002548 // GC doesn't gray immune objects while scanning immune objects. But we need to trigger the read
2549 // barriers here because we need the updated reference to the int array class, etc. Temporary set
2550 // gc_grays_immune_objects_ to true so that we won't cause a DCHECK failure in MarkImmuneSpace().
2551 ScopedGcGraysImmuneObjects scoped_gc_gray_immune_objects(this);
Roland Levillain14d90572015-07-16 10:52:26 +01002552 CHECK_ALIGNED(byte_size, kObjectAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002553 memset(dummy_obj, 0, byte_size);
Mathieu Chartierd6636d32016-07-28 11:02:38 -07002554 // Avoid going through read barrier for since kDisallowReadBarrierDuringScan may be enabled.
2555 // Explicitly mark to make sure to get an object in the to-space.
2556 mirror::Class* int_array_class = down_cast<mirror::Class*>(
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002557 Mark(self, GetClassRoot<mirror::IntArray, kWithoutReadBarrier>().Ptr()));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002558 CHECK(int_array_class != nullptr);
Andreas Gampe6c578712017-10-19 13:00:34 -07002559 if (ReadBarrier::kEnableToSpaceInvariantChecks) {
2560 AssertToSpaceInvariant(nullptr, MemberOffset(0), int_array_class);
2561 }
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07002562 size_t component_size = int_array_class->GetComponentSize<kWithoutReadBarrier>();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002563 CHECK_EQ(component_size, sizeof(int32_t));
2564 size_t data_offset = mirror::Array::DataOffset(component_size).SizeValue();
2565 if (data_offset > byte_size) {
2566 // An int array is too big. Use java.lang.Object.
Mathieu Chartier9aef9922017-04-23 13:53:50 -07002567 CHECK(java_lang_Object_ != nullptr);
Andreas Gampe6c578712017-10-19 13:00:34 -07002568 if (ReadBarrier::kEnableToSpaceInvariantChecks) {
2569 AssertToSpaceInvariant(nullptr, MemberOffset(0), java_lang_Object_);
2570 }
Mathieu Chartier3ed8ec12017-04-20 19:28:54 -07002571 CHECK_EQ(byte_size, (java_lang_Object_->GetObjectSize<kVerifyNone, kWithoutReadBarrier>()));
2572 dummy_obj->SetClass(java_lang_Object_);
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07002573 CHECK_EQ(byte_size, (dummy_obj->SizeOf<kVerifyNone>()));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002574 } else {
2575 // Use an int array.
2576 dummy_obj->SetClass(int_array_class);
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07002577 CHECK((dummy_obj->IsArrayInstance<kVerifyNone, kWithoutReadBarrier>()));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002578 int32_t length = (byte_size - data_offset) / component_size;
Mathieu Chartier5ffa0782016-07-27 10:45:47 -07002579 mirror::Array* dummy_arr = dummy_obj->AsArray<kVerifyNone, kWithoutReadBarrier>();
2580 dummy_arr->SetLength(length);
2581 CHECK_EQ(dummy_arr->GetLength(), length)
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002582 << "byte_size=" << byte_size << " length=" << length
2583 << " component_size=" << component_size << " data_offset=" << data_offset;
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07002584 CHECK_EQ(byte_size, (dummy_obj->SizeOf<kVerifyNone>()))
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002585 << "byte_size=" << byte_size << " length=" << length
2586 << " component_size=" << component_size << " data_offset=" << data_offset;
2587 }
2588}
2589
2590// Reuse the memory blocks that were copy of objects that were lost in race.
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002591mirror::Object* ConcurrentCopying::AllocateInSkippedBlock(Thread* const self, size_t alloc_size) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002592 // Try to reuse the blocks that were unused due to CAS failures.
Roland Levillain14d90572015-07-16 10:52:26 +01002593 CHECK_ALIGNED(alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002594 size_t min_object_size = RoundUp(sizeof(mirror::Object), space::RegionSpace::kAlignment);
Mathieu Chartierd6636d32016-07-28 11:02:38 -07002595 size_t byte_size;
2596 uint8_t* addr;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002597 {
Mathieu Chartierd6636d32016-07-28 11:02:38 -07002598 MutexLock mu(self, skipped_blocks_lock_);
2599 auto it = skipped_blocks_map_.lower_bound(alloc_size);
2600 if (it == skipped_blocks_map_.end()) {
2601 // Not found.
2602 return nullptr;
2603 }
2604 byte_size = it->first;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002605 CHECK_GE(byte_size, alloc_size);
2606 if (byte_size > alloc_size && byte_size - alloc_size < min_object_size) {
2607 // If remainder would be too small for a dummy object, retry with a larger request size.
2608 it = skipped_blocks_map_.lower_bound(alloc_size + min_object_size);
2609 if (it == skipped_blocks_map_.end()) {
2610 // Not found.
2611 return nullptr;
2612 }
Roland Levillain14d90572015-07-16 10:52:26 +01002613 CHECK_ALIGNED(it->first - alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002614 CHECK_GE(it->first - alloc_size, min_object_size)
2615 << "byte_size=" << byte_size << " it->first=" << it->first << " alloc_size=" << alloc_size;
2616 }
Mathieu Chartierd6636d32016-07-28 11:02:38 -07002617 // Found a block.
2618 CHECK(it != skipped_blocks_map_.end());
2619 byte_size = it->first;
2620 addr = it->second;
2621 CHECK_GE(byte_size, alloc_size);
2622 CHECK(region_space_->IsInToSpace(reinterpret_cast<mirror::Object*>(addr)));
2623 CHECK_ALIGNED(byte_size, space::RegionSpace::kAlignment);
2624 if (kVerboseMode) {
2625 LOG(INFO) << "Reusing skipped bytes : " << reinterpret_cast<void*>(addr) << ", " << byte_size;
2626 }
2627 skipped_blocks_map_.erase(it);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002628 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002629 memset(addr, 0, byte_size);
2630 if (byte_size > alloc_size) {
2631 // Return the remainder to the map.
Roland Levillain14d90572015-07-16 10:52:26 +01002632 CHECK_ALIGNED(byte_size - alloc_size, space::RegionSpace::kAlignment);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002633 CHECK_GE(byte_size - alloc_size, min_object_size);
Mathieu Chartierd6636d32016-07-28 11:02:38 -07002634 // FillWithDummyObject may mark an object, avoid holding skipped_blocks_lock_ to prevent lock
2635 // violation and possible deadlock. The deadlock case is a recursive case:
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002636 // FillWithDummyObject -> Mark(IntArray.class) -> Copy -> AllocateInSkippedBlock.
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002637 FillWithDummyObject(self,
2638 reinterpret_cast<mirror::Object*>(addr + alloc_size),
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002639 byte_size - alloc_size);
2640 CHECK(region_space_->IsInToSpace(reinterpret_cast<mirror::Object*>(addr + alloc_size)));
Mathieu Chartierd6636d32016-07-28 11:02:38 -07002641 {
2642 MutexLock mu(self, skipped_blocks_lock_);
2643 skipped_blocks_map_.insert(std::make_pair(byte_size - alloc_size, addr + alloc_size));
2644 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002645 }
2646 return reinterpret_cast<mirror::Object*>(addr);
2647}
2648
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002649mirror::Object* ConcurrentCopying::Copy(Thread* const self,
2650 mirror::Object* from_ref,
Mathieu Chartieref496d92017-04-28 18:58:59 -07002651 mirror::Object* holder,
2652 MemberOffset offset) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002653 DCHECK(region_space_->IsInFromSpace(from_ref));
Mathieu Chartieref496d92017-04-28 18:58:59 -07002654 // If the class pointer is null, the object is invalid. This could occur for a dangling pointer
2655 // from a previous GC that is either inside or outside the allocated region.
2656 mirror::Class* klass = from_ref->GetClass<kVerifyNone, kWithoutReadBarrier>();
2657 if (UNLIKELY(klass == nullptr)) {
Roland Levillainca3dded2018-08-10 15:35:17 +01002658 // Remove memory protection from the region space and log debugging information.
2659 region_space_->Unprotect();
Mathieu Chartieref496d92017-04-28 18:58:59 -07002660 heap_->GetVerification()->LogHeapCorruption(holder, offset, from_ref, /* fatal */ true);
2661 }
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07002662 // There must not be a read barrier to avoid nested RB that might violate the to-space invariant.
2663 // Note that from_ref is a from space ref so the SizeOf() call will access the from-space meta
2664 // objects, but it's ok and necessary.
2665 size_t obj_size = from_ref->SizeOf<kDefaultVerifyFlags>();
Nicolas Geoffray4b361a82017-07-06 15:30:10 +01002666 size_t region_space_alloc_size = (obj_size <= space::RegionSpace::kRegionSize)
2667 ? RoundUp(obj_size, space::RegionSpace::kAlignment)
2668 : RoundUp(obj_size, space::RegionSpace::kRegionSize);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002669 size_t region_space_bytes_allocated = 0U;
2670 size_t non_moving_space_bytes_allocated = 0U;
2671 size_t bytes_allocated = 0U;
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07002672 size_t dummy;
Lokesh Gidraf2a69312018-03-27 18:48:59 -07002673 bool fall_back_to_non_moving = false;
Lokesh Gidrab4f15412018-01-05 18:29:34 -08002674 mirror::Object* to_ref = region_space_->AllocNonvirtual</*kForEvac*/ true>(
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07002675 region_space_alloc_size, &region_space_bytes_allocated, nullptr, &dummy);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002676 bytes_allocated = region_space_bytes_allocated;
Lokesh Gidraf2a69312018-03-27 18:48:59 -07002677 if (LIKELY(to_ref != nullptr)) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002678 DCHECK_EQ(region_space_alloc_size, region_space_bytes_allocated);
Lokesh Gidraf2a69312018-03-27 18:48:59 -07002679 } else {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002680 // Failed to allocate in the region space. Try the skipped blocks.
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002681 to_ref = AllocateInSkippedBlock(self, region_space_alloc_size);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002682 if (to_ref != nullptr) {
2683 // Succeeded to allocate in a skipped block.
2684 if (heap_->use_tlab_) {
2685 // This is necessary for the tlab case as it's not accounted in the space.
2686 region_space_->RecordAlloc(to_ref);
2687 }
2688 bytes_allocated = region_space_alloc_size;
Lokesh Gidraf2a69312018-03-27 18:48:59 -07002689 heap_->num_bytes_allocated_.fetch_sub(bytes_allocated, std::memory_order_seq_cst);
2690 to_space_bytes_skipped_.fetch_sub(bytes_allocated, std::memory_order_seq_cst);
2691 to_space_objects_skipped_.fetch_sub(1, std::memory_order_seq_cst);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002692 } else {
2693 // Fall back to the non-moving space.
2694 fall_back_to_non_moving = true;
2695 if (kVerboseMode) {
2696 LOG(INFO) << "Out of memory in the to-space. Fall back to non-moving. skipped_bytes="
Orion Hodson88591fe2018-03-06 13:35:43 +00002697 << to_space_bytes_skipped_.load(std::memory_order_seq_cst)
2698 << " skipped_objects="
2699 << to_space_objects_skipped_.load(std::memory_order_seq_cst);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002700 }
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002701 to_ref = heap_->non_moving_space_->Alloc(self, obj_size,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07002702 &non_moving_space_bytes_allocated, nullptr, &dummy);
Mathieu Chartierb01335c2017-03-22 13:15:01 -07002703 if (UNLIKELY(to_ref == nullptr)) {
2704 LOG(FATAL_WITHOUT_ABORT) << "Fall-back non-moving space allocation failed for a "
2705 << obj_size << " byte object in region type "
2706 << region_space_->GetRegionType(from_ref);
2707 LOG(FATAL) << "Object address=" << from_ref << " type=" << from_ref->PrettyTypeOf();
2708 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002709 bytes_allocated = non_moving_space_bytes_allocated;
2710 // Mark it in the mark bitmap.
2711 accounting::ContinuousSpaceBitmap* mark_bitmap =
2712 heap_mark_bitmap_->GetContinuousSpaceBitmap(to_ref);
2713 CHECK(mark_bitmap != nullptr);
Roland Levillain5c54d862018-01-17 14:46:24 +00002714 bool previously_marked_in_bitmap = mark_bitmap->AtomicTestAndSet(to_ref);
2715 CHECK(!previously_marked_in_bitmap);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002716 }
2717 }
2718 DCHECK(to_ref != nullptr);
2719
Mathieu Chartierd818adb2016-09-15 13:12:47 -07002720 // Copy the object excluding the lock word since that is handled in the loop.
Mathieu Chartieref496d92017-04-28 18:58:59 -07002721 to_ref->SetClass(klass);
Mathieu Chartierd818adb2016-09-15 13:12:47 -07002722 const size_t kObjectHeaderSize = sizeof(mirror::Object);
2723 DCHECK_GE(obj_size, kObjectHeaderSize);
2724 static_assert(kObjectHeaderSize == sizeof(mirror::HeapReference<mirror::Class>) +
2725 sizeof(LockWord),
2726 "Object header size does not match");
2727 // Memcpy can tear for words since it may do byte copy. It is only safe to do this since the
2728 // object in the from space is immutable other than the lock word. b/31423258
2729 memcpy(reinterpret_cast<uint8_t*>(to_ref) + kObjectHeaderSize,
2730 reinterpret_cast<const uint8_t*>(from_ref) + kObjectHeaderSize,
2731 obj_size - kObjectHeaderSize);
2732
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002733 // Attempt to install the forward pointer. This is in a loop as the
2734 // lock word atomic write can fail.
2735 while (true) {
Mathieu Chartierd818adb2016-09-15 13:12:47 -07002736 LockWord old_lock_word = from_ref->GetLockWord(false);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002737
2738 if (old_lock_word.GetState() == LockWord::kForwardingAddress) {
2739 // Lost the race. Another thread (either GC or mutator) stored
2740 // the forwarding pointer first. Make the lost copy (to_ref)
2741 // look like a valid but dead (dummy) object and keep it for
2742 // future reuse.
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002743 FillWithDummyObject(self, to_ref, bytes_allocated);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002744 if (!fall_back_to_non_moving) {
2745 DCHECK(region_space_->IsInToSpace(to_ref));
2746 if (bytes_allocated > space::RegionSpace::kRegionSize) {
2747 // Free the large alloc.
Lokesh Gidrab4f15412018-01-05 18:29:34 -08002748 region_space_->FreeLarge</*kForEvac*/ true>(to_ref, bytes_allocated);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002749 } else {
2750 // Record the lost copy for later reuse.
Orion Hodson88591fe2018-03-06 13:35:43 +00002751 heap_->num_bytes_allocated_.fetch_add(bytes_allocated, std::memory_order_seq_cst);
2752 to_space_bytes_skipped_.fetch_add(bytes_allocated, std::memory_order_seq_cst);
2753 to_space_objects_skipped_.fetch_add(1, std::memory_order_seq_cst);
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002754 MutexLock mu(self, skipped_blocks_lock_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002755 skipped_blocks_map_.insert(std::make_pair(bytes_allocated,
2756 reinterpret_cast<uint8_t*>(to_ref)));
2757 }
2758 } else {
2759 DCHECK(heap_->non_moving_space_->HasAddress(to_ref));
2760 DCHECK_EQ(bytes_allocated, non_moving_space_bytes_allocated);
2761 // Free the non-moving-space chunk.
2762 accounting::ContinuousSpaceBitmap* mark_bitmap =
2763 heap_mark_bitmap_->GetContinuousSpaceBitmap(to_ref);
2764 CHECK(mark_bitmap != nullptr);
2765 CHECK(mark_bitmap->Clear(to_ref));
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002766 heap_->non_moving_space_->Free(self, to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002767 }
2768
2769 // Get the winner's forward ptr.
2770 mirror::Object* lost_fwd_ptr = to_ref;
2771 to_ref = reinterpret_cast<mirror::Object*>(old_lock_word.ForwardingAddress());
2772 CHECK(to_ref != nullptr);
2773 CHECK_NE(to_ref, lost_fwd_ptr);
Mathieu Chartierdfcd6f42016-09-13 10:02:48 -07002774 CHECK(region_space_->IsInToSpace(to_ref) || heap_->non_moving_space_->HasAddress(to_ref))
2775 << "to_ref=" << to_ref << " " << heap_->DumpSpaces();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002776 CHECK_NE(to_ref->GetLockWord(false).GetState(), LockWord::kForwardingAddress);
2777 return to_ref;
2778 }
2779
Mathieu Chartierd818adb2016-09-15 13:12:47 -07002780 // Copy the old lock word over since we did not copy it yet.
2781 to_ref->SetLockWord(old_lock_word, false);
Hiroshi Yamauchi60f63f52015-04-23 16:12:40 -07002782 // Set the gray ptr.
2783 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002784 to_ref->SetReadBarrierState(ReadBarrier::GrayState());
Hiroshi Yamauchi60f63f52015-04-23 16:12:40 -07002785 }
2786
Mathieu Chartiera8131262016-11-29 17:55:19 -08002787 // Do a fence to prevent the field CAS in ConcurrentCopying::Process from possibly reordering
2788 // before the object copy.
Orion Hodson27b96762018-03-13 16:06:57 +00002789 std::atomic_thread_fence(std::memory_order_release);
Mathieu Chartiera8131262016-11-29 17:55:19 -08002790
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002791 LockWord new_lock_word = LockWord::FromForwardingAddress(reinterpret_cast<size_t>(to_ref));
2792
2793 // Try to atomically write the fwd ptr.
Mathieu Chartier42c2e502018-06-19 12:30:56 -07002794 bool success = from_ref->CasLockWord(old_lock_word,
2795 new_lock_word,
2796 CASMode::kWeak,
2797 std::memory_order_relaxed);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002798 if (LIKELY(success)) {
2799 // The CAS succeeded.
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002800 DCHECK(thread_running_gc_ != nullptr);
2801 if (LIKELY(self == thread_running_gc_)) {
2802 objects_moved_gc_thread_ += 1;
2803 bytes_moved_gc_thread_ += region_space_alloc_size;
2804 } else {
2805 objects_moved_.fetch_add(1, std::memory_order_relaxed);
2806 bytes_moved_.fetch_add(region_space_alloc_size, std::memory_order_relaxed);
2807 }
2808
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002809 if (LIKELY(!fall_back_to_non_moving)) {
2810 DCHECK(region_space_->IsInToSpace(to_ref));
2811 } else {
2812 DCHECK(heap_->non_moving_space_->HasAddress(to_ref));
2813 DCHECK_EQ(bytes_allocated, non_moving_space_bytes_allocated);
2814 }
2815 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002816 DCHECK(to_ref->GetReadBarrierState() == ReadBarrier::GrayState());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002817 }
2818 DCHECK(GetFwdPtr(from_ref) == to_ref);
2819 CHECK_NE(to_ref->GetLockWord(false).GetState(), LockWord::kForwardingAddress);
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002820 PushOntoMarkStack(self, to_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002821 return to_ref;
2822 } else {
2823 // The CAS failed. It may have lost the race or may have failed
2824 // due to monitor/hashcode ops. Either way, retry.
2825 }
2826 }
2827}
2828
2829mirror::Object* ConcurrentCopying::IsMarked(mirror::Object* from_ref) {
2830 DCHECK(from_ref != nullptr);
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08002831 space::RegionSpace::RegionType rtype = region_space_->GetRegionType(from_ref);
2832 if (rtype == space::RegionSpace::RegionType::kRegionTypeToSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002833 // It's already marked.
2834 return from_ref;
2835 }
2836 mirror::Object* to_ref;
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08002837 if (rtype == space::RegionSpace::RegionType::kRegionTypeFromSpace) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002838 to_ref = GetFwdPtr(from_ref);
2839 DCHECK(to_ref == nullptr || region_space_->IsInToSpace(to_ref) ||
2840 heap_->non_moving_space_->HasAddress(to_ref))
2841 << "from_ref=" << from_ref << " to_ref=" << to_ref;
Hiroshi Yamauchid25f8422015-01-30 16:25:12 -08002842 } else if (rtype == space::RegionSpace::RegionType::kRegionTypeUnevacFromSpace) {
Mathieu Chartierc381c362016-08-23 13:27:53 -07002843 if (IsMarkedInUnevacFromSpace(from_ref)) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002844 to_ref = from_ref;
2845 } else {
2846 to_ref = nullptr;
2847 }
2848 } else {
Roland Levillain001eff92018-01-24 14:24:33 +00002849 // At this point, `from_ref` should not be in the region space
2850 // (i.e. within an "unused" region).
2851 DCHECK(!region_space_->HasAddress(from_ref)) << from_ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002852 // from_ref is in a non-moving space.
Mathieu Chartier763a31e2015-11-16 16:05:55 -08002853 if (immune_spaces_.ContainsObject(from_ref)) {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002854 // An immune object is alive.
2855 to_ref = from_ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002856 } else {
2857 // Non-immune non-moving space. Use the mark bitmap.
2858 accounting::ContinuousSpaceBitmap* mark_bitmap =
2859 heap_mark_bitmap_->GetContinuousSpaceBitmap(from_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002860 bool is_los = mark_bitmap == nullptr;
2861 if (!is_los && mark_bitmap->Test(from_ref)) {
2862 // Already marked.
2863 to_ref = from_ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002864 } else {
Mathieu Chartier47863bb2017-08-04 11:30:27 -07002865 accounting::LargeObjectBitmap* los_bitmap =
2866 heap_mark_bitmap_->GetLargeObjectBitmap(from_ref);
2867 // We may not have a large object space for dex2oat, don't assume it exists.
2868 if (los_bitmap == nullptr) {
2869 CHECK(heap_->GetLargeObjectsSpace() == nullptr)
2870 << "LOS bitmap covers the entire address range " << from_ref
2871 << " " << heap_->DumpSpaces();
2872 }
2873 if (los_bitmap != nullptr && is_los && los_bitmap->Test(from_ref)) {
2874 // Already marked in LOS.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002875 to_ref = from_ref;
2876 } else {
2877 // Not marked.
Mathieu Chartier47863bb2017-08-04 11:30:27 -07002878 if (IsOnAllocStack(from_ref)) {
2879 // If on the allocation stack, it's considered marked.
2880 to_ref = from_ref;
2881 } else {
2882 // Not marked.
2883 to_ref = nullptr;
2884 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002885 }
2886 }
2887 }
2888 }
2889 return to_ref;
2890}
2891
2892bool ConcurrentCopying::IsOnAllocStack(mirror::Object* ref) {
Hans Boehmcc55e1d2017-07-27 15:28:07 -07002893 // TODO: Explain why this is here. What release operation does it pair with?
Orion Hodson27b96762018-03-13 16:06:57 +00002894 std::atomic_thread_fence(std::memory_order_acquire);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002895 accounting::ObjectStack* alloc_stack = GetAllocationStack();
Mathieu Chartiercb535da2015-01-23 13:50:03 -08002896 return alloc_stack->Contains(ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002897}
2898
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002899mirror::Object* ConcurrentCopying::MarkNonMoving(Thread* const self,
2900 mirror::Object* ref,
Mathieu Chartier1ca68902017-04-18 11:26:22 -07002901 mirror::Object* holder,
2902 MemberOffset offset) {
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002903 // ref is in a non-moving space (from_ref == to_ref).
2904 DCHECK(!region_space_->HasAddress(ref)) << ref;
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002905 DCHECK(!immune_spaces_.ContainsObject(ref));
2906 // Use the mark bitmap.
2907 accounting::ContinuousSpaceBitmap* mark_bitmap =
2908 heap_mark_bitmap_->GetContinuousSpaceBitmap(ref);
2909 accounting::LargeObjectBitmap* los_bitmap =
2910 heap_mark_bitmap_->GetLargeObjectBitmap(ref);
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002911 bool is_los = mark_bitmap == nullptr;
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002912 if (kEnableGenerationalConcurrentCopyingCollection && young_gen_) {
Roland Levillainade74a62018-08-08 15:55:42 +01002913 // The sticky-bit CC collector is only compatible with Baker-style read barriers.
2914 DCHECK(kUseBakerReadBarrier);
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002915 // Not done scanning, use AtomicSetReadBarrierPointer.
Roland Levillain2d94e292018-08-15 16:46:30 +01002916 if (!done_scanning_.load(std::memory_order_acquire)) {
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002917 // 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 +01002918 // mutator may see references to the from space. Instead, use the Baker pointer itself as
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002919 // the mark bit.
2920 if (ref->AtomicSetReadBarrierState(ReadBarrier::NonGrayState(), ReadBarrier::GrayState())) {
2921 // TODO: We don't actually need to scan this object later, we just need to clear the gray
2922 // bit.
2923 // Also make sure the object is marked.
2924 if (is_los) {
2925 los_bitmap->AtomicTestAndSet(ref);
2926 } else {
2927 mark_bitmap->AtomicTestAndSet(ref);
2928 }
2929 PushOntoMarkStack(self, ref);
2930 }
2931 return ref;
2932 }
2933 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002934 if (!is_los && mark_bitmap->Test(ref)) {
2935 // Already marked.
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002936 } else if (is_los && los_bitmap->Test(ref)) {
2937 // Already marked in LOS.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002938 } else {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002939 // Not marked.
2940 if (IsOnAllocStack(ref)) {
Roland Levillain14e5a292018-06-28 12:00:56 +01002941 // If it's on the allocation stack, it's considered marked. Keep it white (non-gray).
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002942 // Objects on the allocation stack need not be marked.
2943 if (!is_los) {
2944 DCHECK(!mark_bitmap->Test(ref));
2945 } else {
2946 DCHECK(!los_bitmap->Test(ref));
Nicolas Geoffrayddeb1722016-06-28 08:25:59 +00002947 }
Nicolas Geoffrayddeb1722016-06-28 08:25:59 +00002948 if (kUseBakerReadBarrier) {
Roland Levillain14e5a292018-06-28 12:00:56 +01002949 DCHECK_EQ(ref->GetReadBarrierState(), ReadBarrier::NonGrayState());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002950 }
2951 } else {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002952 // For the baker-style RB, we need to handle 'false-gray' cases. See the
2953 // kRegionTypeUnevacFromSpace-case comment in Mark().
2954 if (kUseBakerReadBarrier) {
2955 // Test the bitmap first to reduce the chance of false gray cases.
2956 if ((!is_los && mark_bitmap->Test(ref)) ||
2957 (is_los && los_bitmap->Test(ref))) {
2958 return ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002959 }
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002960 }
Mathieu Chartier1ca68902017-04-18 11:26:22 -07002961 if (is_los && !IsAligned<kPageSize>(ref)) {
Roland Levillainca3dded2018-08-10 15:35:17 +01002962 // Ref is a large object that is not aligned, it must be heap
2963 // corruption. Remove memory protection and dump data before
2964 // AtomicSetReadBarrierState since it will fault if the address is not
2965 // valid.
2966 region_space_->Unprotect();
Mathieu Chartieref496d92017-04-28 18:58:59 -07002967 heap_->GetVerification()->LogHeapCorruption(holder, offset, ref, /* fatal */ true);
Mathieu Chartier1ca68902017-04-18 11:26:22 -07002968 }
Roland Levillain14e5a292018-06-28 12:00:56 +01002969 // Not marked nor on the allocation stack. Try to mark it.
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002970 // This may or may not succeed, which is ok.
2971 bool cas_success = false;
2972 if (kUseBakerReadBarrier) {
Roland Levillain14e5a292018-06-28 12:00:56 +01002973 cas_success = ref->AtomicSetReadBarrierState(ReadBarrier::NonGrayState(),
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002974 ReadBarrier::GrayState());
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002975 }
2976 if (!is_los && mark_bitmap->AtomicTestAndSet(ref)) {
2977 // Already marked.
Roland Levillain14e5a292018-06-28 12:00:56 +01002978 if (kUseBakerReadBarrier &&
2979 cas_success &&
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002980 ref->GetReadBarrierState() == ReadBarrier::GrayState()) {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002981 PushOntoFalseGrayStack(self, ref);
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002982 }
2983 } else if (is_los && los_bitmap->AtomicTestAndSet(ref)) {
2984 // Already marked in LOS.
Roland Levillain14e5a292018-06-28 12:00:56 +01002985 if (kUseBakerReadBarrier &&
2986 cas_success &&
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002987 ref->GetReadBarrierState() == ReadBarrier::GrayState()) {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002988 PushOntoFalseGrayStack(self, ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002989 }
2990 } else {
Hiroshi Yamauchid8db5a22016-06-28 14:07:41 -07002991 // Newly marked.
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08002992 if (kUseBakerReadBarrier) {
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002993 DCHECK_EQ(ref->GetReadBarrierState(), ReadBarrier::GrayState());
Hiroshi Yamauchi8e674652015-12-22 11:09:18 -08002994 }
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08002995 PushOntoMarkStack(self, ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002996 }
2997 }
2998 }
Hiroshi Yamauchi723e6ce2015-10-28 20:59:47 -07002999 return ref;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003000}
3001
3002void ConcurrentCopying::FinishPhase() {
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -08003003 Thread* const self = Thread::Current();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07003004 {
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -08003005 MutexLock mu(self, mark_stack_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07003006 CHECK_EQ(pooled_mark_stacks_.size(), kMarkStackPoolSize);
3007 }
Mathieu Chartiera1467d02017-02-22 09:22:50 -08003008 // kVerifyNoMissingCardMarks relies on the region space cards not being cleared to avoid false
3009 // positives.
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07003010 if (!kEnableGenerationalConcurrentCopyingCollection && !kVerifyNoMissingCardMarks) {
Mathieu Chartier6e6078a2016-10-24 15:45:41 -07003011 TimingLogger::ScopedTiming split("ClearRegionSpaceCards", GetTimings());
3012 // We do not currently use the region space cards at all, madvise them away to save ram.
3013 heap_->GetCardTable()->ClearCardRange(region_space_->Begin(), region_space_->Limit());
Mathieu Chartier6e6078a2016-10-24 15:45:41 -07003014 }
3015 {
3016 MutexLock mu(self, skipped_blocks_lock_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003017 skipped_blocks_map_.clear();
3018 }
Mathieu Chartier56fe2582016-07-14 13:30:03 -07003019 {
3020 ReaderMutexLock mu(self, *Locks::mutator_lock_);
Mathieu Chartier21328a12016-07-22 10:47:45 -07003021 {
3022 WriterMutexLock mu2(self, *Locks::heap_bitmap_lock_);
3023 heap_->ClearMarkedObjects();
3024 }
3025 if (kUseBakerReadBarrier && kFilterModUnionCards) {
3026 TimingLogger::ScopedTiming split("FilterModUnionCards", GetTimings());
3027 ReaderMutexLock mu2(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier21328a12016-07-22 10:47:45 -07003028 for (space::ContinuousSpace* space : immune_spaces_.GetSpaces()) {
3029 DCHECK(space->IsImageSpace() || space->IsZygoteSpace());
Mathieu Chartier6e6078a2016-10-24 15:45:41 -07003030 accounting::ModUnionTable* table = heap_->FindModUnionTableFromSpace(space);
Mathieu Chartier21328a12016-07-22 10:47:45 -07003031 // Filter out cards that don't need to be set.
3032 if (table != nullptr) {
3033 table->FilterCards();
3034 }
3035 }
3036 }
Mathieu Chartier36a270a2016-07-28 18:08:51 -07003037 if (kUseBakerReadBarrier) {
3038 TimingLogger::ScopedTiming split("EmptyRBMarkBitStack", GetTimings());
Mathieu Chartier6e6078a2016-10-24 15:45:41 -07003039 DCHECK(rb_mark_bit_stack_ != nullptr);
Mathieu Chartier36a270a2016-07-28 18:08:51 -07003040 const auto* limit = rb_mark_bit_stack_->End();
3041 for (StackReference<mirror::Object>* it = rb_mark_bit_stack_->Begin(); it != limit; ++it) {
Roland Levillain001eff92018-01-24 14:24:33 +00003042 CHECK(it->AsMirrorPtr()->AtomicSetMarkBit(1, 0))
3043 << "rb_mark_bit_stack_->Begin()" << rb_mark_bit_stack_->Begin() << '\n'
3044 << "rb_mark_bit_stack_->End()" << rb_mark_bit_stack_->End() << '\n'
3045 << "rb_mark_bit_stack_->IsFull()"
3046 << std::boolalpha << rb_mark_bit_stack_->IsFull() << std::noboolalpha << '\n'
3047 << DumpReferenceInfo(it->AsMirrorPtr(), "*it");
Mathieu Chartier36a270a2016-07-28 18:08:51 -07003048 }
3049 rb_mark_bit_stack_->Reset();
3050 }
Mathieu Chartier56fe2582016-07-14 13:30:03 -07003051 }
3052 if (measure_read_barrier_slow_path_) {
3053 MutexLock mu(self, rb_slow_path_histogram_lock_);
Orion Hodson88591fe2018-03-06 13:35:43 +00003054 rb_slow_path_time_histogram_.AdjustAndAddValue(
3055 rb_slow_path_ns_.load(std::memory_order_relaxed));
3056 rb_slow_path_count_total_ += rb_slow_path_count_.load(std::memory_order_relaxed);
3057 rb_slow_path_count_gc_total_ += rb_slow_path_count_gc_.load(std::memory_order_relaxed);
Mathieu Chartier56fe2582016-07-14 13:30:03 -07003058 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003059}
3060
Hiroshi Yamauchi65f5f242016-12-19 11:44:47 -08003061bool ConcurrentCopying::IsNullOrMarkedHeapReference(mirror::HeapReference<mirror::Object>* field,
3062 bool do_atomic_update) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003063 mirror::Object* from_ref = field->AsMirrorPtr();
Hiroshi Yamauchi65f5f242016-12-19 11:44:47 -08003064 if (from_ref == nullptr) {
3065 return true;
3066 }
Mathieu Chartier97509952015-07-13 14:35:43 -07003067 mirror::Object* to_ref = IsMarked(from_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003068 if (to_ref == nullptr) {
3069 return false;
3070 }
3071 if (from_ref != to_ref) {
Hiroshi Yamauchi65f5f242016-12-19 11:44:47 -08003072 if (do_atomic_update) {
3073 do {
3074 if (field->AsMirrorPtr() != from_ref) {
3075 // Concurrently overwritten by a mutator.
3076 break;
3077 }
3078 } while (!field->CasWeakRelaxed(from_ref, to_ref));
3079 } else {
Hans Boehmcc55e1d2017-07-27 15:28:07 -07003080 // TODO: Why is this seq_cst when the above is relaxed? Document memory ordering.
3081 field->Assign</* kIsVolatile */ true>(to_ref);
Hiroshi Yamauchi65f5f242016-12-19 11:44:47 -08003082 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003083 }
3084 return true;
3085}
3086
Mathieu Chartier97509952015-07-13 14:35:43 -07003087mirror::Object* ConcurrentCopying::MarkObject(mirror::Object* from_ref) {
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08003088 return Mark(Thread::Current(), from_ref);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003089}
3090
Mathieu Chartier31e88222016-10-14 18:43:19 -07003091void ConcurrentCopying::DelayReferenceReferent(ObjPtr<mirror::Class> klass,
3092 ObjPtr<mirror::Reference> reference) {
Mathieu Chartier97509952015-07-13 14:35:43 -07003093 heap_->GetReferenceProcessor()->DelayReferenceReferent(klass, reference, this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003094}
3095
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07003096void ConcurrentCopying::ProcessReferences(Thread* self) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003097 TimingLogger::ScopedTiming split("ProcessReferences", GetTimings());
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07003098 // 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 -08003099 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
3100 GetHeap()->GetReferenceProcessor()->ProcessReferences(
Mathieu Chartier97509952015-07-13 14:35:43 -07003101 true /*concurrent*/, GetTimings(), GetCurrentIteration()->GetClearSoftReferences(), this);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003102}
3103
3104void ConcurrentCopying::RevokeAllThreadLocalBuffers() {
3105 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
3106 region_space_->RevokeAllThreadLocalBuffers();
3107}
3108
Hiroshi Yamauchi7a181542017-03-08 17:34:46 -08003109mirror::Object* ConcurrentCopying::MarkFromReadBarrierWithMeasurements(Thread* const self,
3110 mirror::Object* from_ref) {
3111 if (self != thread_running_gc_) {
Orion Hodson88591fe2018-03-06 13:35:43 +00003112 rb_slow_path_count_.fetch_add(1u, std::memory_order_relaxed);
Mathieu Chartier56fe2582016-07-14 13:30:03 -07003113 } else {
Orion Hodson88591fe2018-03-06 13:35:43 +00003114 rb_slow_path_count_gc_.fetch_add(1u, std::memory_order_relaxed);
Mathieu Chartier56fe2582016-07-14 13:30:03 -07003115 }
3116 ScopedTrace tr(__FUNCTION__);
3117 const uint64_t start_time = measure_read_barrier_slow_path_ ? NanoTime() : 0u;
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07003118 mirror::Object* ret =
3119 Mark</*kGrayImmuneObject*/true, /*kNoUnEvac*/false, /*kFromGCThread*/false>(self, from_ref);
Mathieu Chartier56fe2582016-07-14 13:30:03 -07003120 if (measure_read_barrier_slow_path_) {
Orion Hodson88591fe2018-03-06 13:35:43 +00003121 rb_slow_path_ns_.fetch_add(NanoTime() - start_time, std::memory_order_relaxed);
Mathieu Chartier56fe2582016-07-14 13:30:03 -07003122 }
3123 return ret;
3124}
3125
3126void ConcurrentCopying::DumpPerformanceInfo(std::ostream& os) {
3127 GarbageCollector::DumpPerformanceInfo(os);
3128 MutexLock mu(Thread::Current(), rb_slow_path_histogram_lock_);
3129 if (rb_slow_path_time_histogram_.SampleSize() > 0) {
3130 Histogram<uint64_t>::CumulativeData cumulative_data;
3131 rb_slow_path_time_histogram_.CreateHistogram(&cumulative_data);
3132 rb_slow_path_time_histogram_.PrintConfidenceIntervals(os, 0.99, cumulative_data);
3133 }
3134 if (rb_slow_path_count_total_ > 0) {
3135 os << "Slow path count " << rb_slow_path_count_total_ << "\n";
3136 }
3137 if (rb_slow_path_count_gc_total_ > 0) {
3138 os << "GC slow path count " << rb_slow_path_count_gc_total_ << "\n";
3139 }
Orion Hodson88591fe2018-03-06 13:35:43 +00003140 os << "Cumulative bytes moved "
3141 << cumulative_bytes_moved_.load(std::memory_order_relaxed) << "\n";
3142 os << "Cumulative objects moved "
3143 << cumulative_objects_moved_.load(std::memory_order_relaxed) << "\n";
Lokesh Gidra29895822017-12-15 15:37:40 -08003144
3145 os << "Peak regions allocated "
Lokesh Gidrab4f15412018-01-05 18:29:34 -08003146 << region_space_->GetMaxPeakNumNonFreeRegions() << " ("
3147 << PrettySize(region_space_->GetMaxPeakNumNonFreeRegions() * space::RegionSpace::kRegionSize)
3148 << ") / " << region_space_->GetNumRegions() / 2 << " ("
3149 << PrettySize(region_space_->GetNumRegions() * space::RegionSpace::kRegionSize / 2)
Lokesh Gidra29895822017-12-15 15:37:40 -08003150 << ")\n";
Mathieu Chartier56fe2582016-07-14 13:30:03 -07003151}
3152
Hiroshi Yamauchid5307ec2014-03-27 21:07:51 -07003153} // namespace collector
3154} // namespace gc
3155} // namespace art