blob: 6073fc8a78c08c872ac3d7b622a397e5d4bd4029 [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
2 * Copyright (C) 2011 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 */
Carl Shapiro69759ea2011-07-21 18:13:35 -070016
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070017#include "mark_sweep.h"
Carl Shapiro69759ea2011-07-21 18:13:35 -070018
Yabin Cuic7df66e2015-04-15 15:40:18 -070019#include <atomic>
Mathieu Chartier2b82db42012-11-14 17:29:05 -080020#include <functional>
21#include <numeric>
Carl Shapiro58551df2011-07-24 03:09:51 -070022#include <climits>
23#include <vector>
24
Mathieu Chartier94c32c52013-08-09 11:14:04 -070025#include "base/bounded_fifo.h"
Elliott Hughes07ed66b2012-12-12 18:34:25 -080026#include "base/logging.h"
Elliott Hughes76160052012-12-12 16:31:20 -080027#include "base/macros.h"
Ian Rogers693ff612013-02-01 10:56:12 -080028#include "base/mutex-inl.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080029#include "base/systrace.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010030#include "base/time_utils.h"
Sameer Abu Asala8439542013-02-14 16:06:42 -080031#include "base/timing_logger.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070032#include "gc/accounting/card_table-inl.h"
Mathieu Chartier4aeec172014-03-27 16:09:46 -070033#include "gc/accounting/heap_bitmap-inl.h"
Mathieu Chartier11409ae2013-09-23 11:49:36 -070034#include "gc/accounting/mod_union_table.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070035#include "gc/accounting/space_bitmap-inl.h"
36#include "gc/heap.h"
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -070037#include "gc/reference_processor.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070038#include "gc/space/large_object_space.h"
39#include "gc/space/space-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080040#include "mark_sweep-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080041#include "mirror/object-inl.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070042#include "runtime.h"
Mathieu Chartier4aeec172014-03-27 16:09:46 -070043#include "scoped_thread_state_change.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070044#include "thread-inl.h"
Mathieu Chartier6f1c9492012-10-15 12:08:41 -070045#include "thread_list.h"
Carl Shapiro69759ea2011-07-21 18:13:35 -070046
Carl Shapiro69759ea2011-07-21 18:13:35 -070047namespace art {
Ian Rogers1d54e732013-05-02 21:10:01 -070048namespace gc {
49namespace collector {
Carl Shapiro69759ea2011-07-21 18:13:35 -070050
Mathieu Chartier02b6a782012-10-26 13:51:26 -070051// Performance options.
Mathieu Chartiereb7bbad2014-02-25 15:52:46 -080052static constexpr bool kUseRecursiveMark = false;
53static constexpr bool kUseMarkStackPrefetch = true;
54static constexpr size_t kSweepArrayChunkFreeSize = 1024;
55static constexpr bool kPreCleanCards = true;
Mathieu Chartier94c32c52013-08-09 11:14:04 -070056
57// Parallelism options.
Mathieu Chartiereb7bbad2014-02-25 15:52:46 -080058static constexpr bool kParallelCardScan = true;
59static constexpr bool kParallelRecursiveMark = true;
Mathieu Chartier94c32c52013-08-09 11:14:04 -070060// Don't attempt to parallelize mark stack processing unless the mark stack is at least n
61// elements. This is temporary until we reduce the overhead caused by allocating tasks, etc.. Not
62// having this can add overhead in ProcessReferences since we may end up doing many calls of
63// ProcessMarkStack with very small mark stacks.
Mathieu Chartiereb7bbad2014-02-25 15:52:46 -080064static constexpr size_t kMinimumParallelMarkStackSize = 128;
65static constexpr bool kParallelProcessMarkStack = true;
Mathieu Chartier858f1c52012-10-17 17:45:55 -070066
Mathieu Chartier02b6a782012-10-26 13:51:26 -070067// Profiling and information flags.
Mathieu Chartiereb7bbad2014-02-25 15:52:46 -080068static constexpr bool kProfileLargeObjects = false;
69static constexpr bool kMeasureOverhead = false;
70static constexpr bool kCountTasks = false;
Mathieu Chartier0e54cd02014-03-20 12:41:23 -070071static constexpr bool kCountMarkedObjects = false;
Mathieu Chartier94c32c52013-08-09 11:14:04 -070072
73// Turn off kCheckLocks when profiling the GC since it slows the GC down by up to 40%.
Mathieu Chartiereb7bbad2014-02-25 15:52:46 -080074static constexpr bool kCheckLocks = kDebugLocking;
Mathieu Chartier7bf9f192014-04-04 11:09:41 -070075static constexpr bool kVerifyRootsMarked = kIsDebugBuild;
Mathieu Chartier02b6a782012-10-26 13:51:26 -070076
Hiroshi Yamauchic93c5302014-03-20 16:15:37 -070077// If true, revoke the rosalloc thread-local buffers at the
78// checkpoint, as opposed to during the pause.
79static constexpr bool kRevokeRosAllocThreadLocalBuffersAtCheckpoint = true;
80
Mathieu Chartier2b82db42012-11-14 17:29:05 -080081void MarkSweep::BindBitmaps() {
Mathieu Chartierf5997b42014-06-20 10:37:54 -070082 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Mathieu Chartier2b82db42012-11-14 17:29:05 -080083 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -080084 // Mark all of the spaces we never collect as immune.
Mathieu Chartier94c32c52013-08-09 11:14:04 -070085 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Ian Rogers1d54e732013-05-02 21:10:01 -070086 if (space->GetGcRetentionPolicy() == space::kGcRetentionPolicyNeverCollect) {
Mathieu Chartier763a31e2015-11-16 16:05:55 -080087 immune_spaces_.AddSpace(space);
Mathieu Chartier2b82db42012-11-14 17:29:05 -080088 }
89 }
90}
91
Ian Rogers1d54e732013-05-02 21:10:01 -070092MarkSweep::MarkSweep(Heap* heap, bool is_concurrent, const std::string& name_prefix)
93 : GarbageCollector(heap,
Mathieu Chartier590fee92013-09-13 13:46:47 -070094 name_prefix +
Ian Rogers1d54e732013-05-02 21:10:01 -070095 (is_concurrent ? "concurrent mark sweep": "mark sweep")),
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -070096 current_space_bitmap_(nullptr),
97 mark_bitmap_(nullptr),
98 mark_stack_(nullptr),
Mathieu Chartier2b82db42012-11-14 17:29:05 -080099 gc_barrier_(new Barrier(0)),
Mathieu Chartier958291c2013-08-27 18:14:55 -0700100 mark_stack_lock_("mark sweep mark stack lock", kMarkSweepMarkStackLock),
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -0700101 is_concurrent_(is_concurrent),
102 live_stack_freeze_size_(0) {
Hiroshi Yamauchibbdc5bc2014-05-28 14:04:59 -0700103 std::string error_msg;
104 MemMap* mem_map = MemMap::MapAnonymous(
105 "mark sweep sweep array free buffer", nullptr,
106 RoundUp(kSweepArrayChunkFreeSize * sizeof(mirror::Object*), kPageSize),
Vladimir Marko5c42c292015-02-25 12:02:49 +0000107 PROT_READ | PROT_WRITE, false, false, &error_msg);
Hiroshi Yamauchibbdc5bc2014-05-28 14:04:59 -0700108 CHECK(mem_map != nullptr) << "Couldn't allocate sweep array free buffer: " << error_msg;
109 sweep_array_free_buffer_mem_map_.reset(mem_map);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800110}
111
112void MarkSweep::InitializePhase() {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700113 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700114 mark_stack_ = heap_->GetMarkStack();
Mathieu Chartiere53225c2013-08-19 10:59:11 -0700115 DCHECK(mark_stack_ != nullptr);
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800116 immune_spaces_.Reset();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700117 no_reference_class_count_.StoreRelaxed(0);
118 normal_count_.StoreRelaxed(0);
Ian Rogers3e5cf302014-05-20 16:40:37 -0700119 class_count_.StoreRelaxed(0);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700120 object_array_count_.StoreRelaxed(0);
Ian Rogers3e5cf302014-05-20 16:40:37 -0700121 other_count_.StoreRelaxed(0);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700122 reference_count_.StoreRelaxed(0);
Ian Rogers3e5cf302014-05-20 16:40:37 -0700123 large_object_test_.StoreRelaxed(0);
124 large_object_mark_.StoreRelaxed(0);
125 overhead_time_ .StoreRelaxed(0);
126 work_chunks_created_.StoreRelaxed(0);
127 work_chunks_deleted_.StoreRelaxed(0);
Ian Rogers3e5cf302014-05-20 16:40:37 -0700128 mark_null_count_.StoreRelaxed(0);
129 mark_immune_count_.StoreRelaxed(0);
130 mark_fastpath_count_.StoreRelaxed(0);
131 mark_slowpath_count_.StoreRelaxed(0);
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700132 {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700133 // TODO: I don't think we should need heap bitmap lock to Get the mark bitmap.
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700134 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
135 mark_bitmap_ = heap_->GetMarkBitmap();
136 }
Mathieu Chartier10fb83a2014-06-15 15:15:43 -0700137 if (!GetCurrentIteration()->GetClearSoftReferences()) {
Hiroshi Yamauchidf386c52014-04-08 16:21:52 -0700138 // Always clear soft references if a non-sticky collection.
Mathieu Chartier10fb83a2014-06-15 15:15:43 -0700139 GetCurrentIteration()->SetClearSoftReferences(GetGcType() != collector::kGcTypeSticky);
Hiroshi Yamauchidf386c52014-04-08 16:21:52 -0700140 }
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700141}
142
143void MarkSweep::RunPhases() {
144 Thread* self = Thread::Current();
145 InitializePhase();
146 Locks::mutator_lock_->AssertNotHeld(self);
147 if (IsConcurrent()) {
148 GetHeap()->PreGcVerification(this);
149 {
150 ReaderMutexLock mu(self, *Locks::mutator_lock_);
151 MarkingPhase();
152 }
153 ScopedPause pause(this);
154 GetHeap()->PrePauseRosAllocVerification(this);
155 PausePhase();
156 RevokeAllThreadLocalBuffers();
157 } else {
158 ScopedPause pause(this);
159 GetHeap()->PreGcVerificationPaused(this);
160 MarkingPhase();
161 GetHeap()->PrePauseRosAllocVerification(this);
162 PausePhase();
163 RevokeAllThreadLocalBuffers();
164 }
165 {
166 // Sweeping always done concurrently, even for non concurrent mark sweep.
167 ReaderMutexLock mu(self, *Locks::mutator_lock_);
168 ReclaimPhase();
169 }
170 GetHeap()->PostGcVerification(this);
171 FinishPhase();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800172}
173
174void MarkSweep::ProcessReferences(Thread* self) {
Mathieu Chartier8e56c7e2012-11-20 13:25:50 -0800175 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -0700176 GetHeap()->GetReferenceProcessor()->ProcessReferences(
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -0700177 true,
178 GetTimings(),
179 GetCurrentIteration()->GetClearSoftReferences(),
180 this);
Mathieu Chartier1ad27842014-03-19 17:08:17 -0700181}
182
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -0700183void MarkSweep::PausePhase() {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700184 TimingLogger::ScopedTiming t("(Paused)PausePhase", GetTimings());
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800185 Thread* self = Thread::Current();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800186 Locks::mutator_lock_->AssertExclusiveHeld(self);
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -0700187 if (IsConcurrent()) {
188 // Handle the dirty objects if we are a concurrent GC.
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800189 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800190 // Re-mark root set.
191 ReMarkRoots();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800192 // Scan dirty objects, this is only required if we are not doing concurrent GC.
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700193 RecursiveMarkDirtyObjects(true, accounting::CardTable::kCardDirty);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800194 }
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -0700195 {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700196 TimingLogger::ScopedTiming t2("SwapStacks", GetTimings());
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800197 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartiera4f6af92015-08-11 17:35:25 -0700198 heap_->SwapStacks();
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -0700199 live_stack_freeze_size_ = heap_->GetLiveStack()->Size();
200 // Need to revoke all the thread local allocation stacks since we just swapped the allocation
201 // stacks and don't want anybody to allocate into the live stack.
Mathieu Chartierc22c59e2014-02-24 15:16:06 -0800202 RevokeAllThreadLocalAllocationStacks(self);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800203 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700204 heap_->PreSweepingGcVerification(this);
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700205 // Disallow new system weaks to prevent a race which occurs when someone adds a new system
206 // weak before we sweep them. Since this new system weak may not be marked, the GC may
207 // incorrectly sweep it. This also fixes a race where interning may attempt to return a strong
208 // reference to a string that is about to be swept.
209 Runtime::Current()->DisallowNewSystemWeaks();
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -0700210 // Enable the reference processing slow path, needs to be done with mutators paused since there
211 // is no lock in the GetReferent fast path.
212 GetHeap()->GetReferenceProcessor()->EnableSlowPath();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800213}
214
Mathieu Chartierdda54f52014-02-24 09:58:40 -0800215void MarkSweep::PreCleanCards() {
216 // Don't do this for non concurrent GCs since they don't have any dirty cards.
217 if (kPreCleanCards && IsConcurrent()) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700218 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Mathieu Chartierdda54f52014-02-24 09:58:40 -0800219 Thread* self = Thread::Current();
220 CHECK(!Locks::mutator_lock_->IsExclusiveHeld(self));
221 // Process dirty cards and add dirty cards to mod union tables, also ages cards.
Lei Li4add3b42015-01-15 11:55:26 +0800222 heap_->ProcessCards(GetTimings(), false, true, false);
Mathieu Chartiereb7bbad2014-02-25 15:52:46 -0800223 // The checkpoint root marking is required to avoid a race condition which occurs if the
224 // following happens during a reference write:
225 // 1. mutator dirties the card (write barrier)
226 // 2. GC ages the card (the above ProcessCards call)
227 // 3. GC scans the object (the RecursiveMarkDirtyObjects call below)
228 // 4. mutator writes the value (corresponding to the write barrier in 1.)
229 // This causes the GC to age the card but not necessarily mark the reference which the mutator
230 // wrote into the object stored in the card.
231 // Having the checkpoint fixes this issue since it ensures that the card mark and the
232 // reference write are visible to the GC before the card is scanned (this is due to locks being
233 // acquired / released in the checkpoint code).
234 // The other roots are also marked to help reduce the pause.
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -0700235 MarkRootsCheckpoint(self, false);
Mathieu Chartierdda54f52014-02-24 09:58:40 -0800236 MarkNonThreadRoots();
Mathieu Chartier893263b2014-03-04 11:07:42 -0800237 MarkConcurrentRoots(
238 static_cast<VisitRootFlags>(kVisitRootFlagClearRootLog | kVisitRootFlagNewRoots));
Mathieu Chartierdda54f52014-02-24 09:58:40 -0800239 // Process the newly aged cards.
240 RecursiveMarkDirtyObjects(false, accounting::CardTable::kCardDirty - 1);
241 // TODO: Empty allocation stack to reduce the number of objects we need to test / mark as live
242 // in the next GC.
243 }
244}
245
Mathieu Chartierc22c59e2014-02-24 15:16:06 -0800246void MarkSweep::RevokeAllThreadLocalAllocationStacks(Thread* self) {
247 if (kUseThreadLocalAllocationStack) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700248 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Mathieu Chartierc22c59e2014-02-24 15:16:06 -0800249 Locks::mutator_lock_->AssertExclusiveHeld(self);
250 heap_->RevokeAllThreadLocalAllocationStacks(self);
251 }
252}
253
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800254void MarkSweep::MarkingPhase() {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700255 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800256 Thread* self = Thread::Current();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800257 BindBitmaps();
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700258 FindDefaultSpaceBitmap();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800259 // Process dirty cards and add dirty cards to mod union tables.
Lei Li4add3b42015-01-15 11:55:26 +0800260 // If the GC type is non sticky, then we just clear the cards instead of ageing them.
261 heap_->ProcessCards(GetTimings(), false, true, GetGcType() != kGcTypeSticky);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800262 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier893263b2014-03-04 11:07:42 -0800263 MarkRoots(self);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800264 MarkReachableObjects();
Mathieu Chartierdda54f52014-02-24 09:58:40 -0800265 // Pre-clean dirtied cards to reduce pauses.
266 PreCleanCards();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800267}
268
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800269class ScanObjectVisitor {
270 public:
271 explicit ScanObjectVisitor(MarkSweep* const mark_sweep) ALWAYS_INLINE
272 : mark_sweep_(mark_sweep) {}
273
274 void operator()(mirror::Object* obj) const
275 ALWAYS_INLINE
276 REQUIRES(Locks::heap_bitmap_lock_)
277 SHARED_REQUIRES(Locks::mutator_lock_) {
278 if (kCheckLocks) {
279 Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
280 Locks::heap_bitmap_lock_->AssertExclusiveHeld(Thread::Current());
281 }
282 mark_sweep_->ScanObject(obj);
283 }
284
285 private:
286 MarkSweep* const mark_sweep_;
287};
288
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700289void MarkSweep::UpdateAndMarkModUnion() {
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800290 for (const auto& space : immune_spaces_.GetSpaces()) {
291 const char* name = space->IsZygoteSpace()
292 ? "UpdateAndMarkZygoteModUnionTable"
293 : "UpdateAndMarkImageModUnionTable";
294 DCHECK(space->IsZygoteSpace() || space->IsImageSpace()) << *space;
295 TimingLogger::ScopedTiming t(name, GetTimings());
296 accounting::ModUnionTable* mod_union_table = heap_->FindModUnionTableFromSpace(space);
297 if (mod_union_table != nullptr) {
Mathieu Chartier97509952015-07-13 14:35:43 -0700298 mod_union_table->UpdateAndMarkReferences(this);
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800299 } else {
300 // No mod-union table, scan all the live bits. This can only occur for app images.
301 space->GetLiveBitmap()->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()),
302 reinterpret_cast<uintptr_t>(space->End()),
303 ScanObjectVisitor(this));
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700304 }
305 }
306}
307
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800308void MarkSweep::MarkReachableObjects() {
Mathieu Chartier4aeec172014-03-27 16:09:46 -0700309 UpdateAndMarkModUnion();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800310 // Recursively mark all the non-image bits set in the mark bitmap.
311 RecursiveMark();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800312}
313
314void MarkSweep::ReclaimPhase() {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700315 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Mathieu Chartier951ec2c2015-09-22 08:50:05 -0700316 Thread* const self = Thread::Current();
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -0700317 // Process the references concurrently.
318 ProcessReferences(self);
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -0700319 SweepSystemWeaks(self);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -0700320 Runtime* const runtime = Runtime::Current();
321 runtime->AllowNewSystemWeaks();
322 // Clean up class loaders after system weaks are swept since that is how we know if class
323 // unloading occurred.
324 runtime->GetClassLinker()->CleanupClassLoaders();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800325 {
326 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -0700327 GetHeap()->RecordFreeRevoke();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800328 // Reclaim unmarked objects.
Ian Rogers1d54e732013-05-02 21:10:01 -0700329 Sweep(false);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800330 // Swap the live and mark bitmaps for each space which we modified space. This is an
331 // optimization that enables us to not clear live bits inside of the sweep. Only swaps unbound
332 // bitmaps.
333 SwapBitmaps();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800334 // Unbind the live and mark bitmaps.
Mathieu Chartiera1602f22014-01-13 17:19:19 -0800335 GetHeap()->UnBindBitmaps();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800336 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800337}
338
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700339void MarkSweep::FindDefaultSpaceBitmap() {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700340 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Mathieu Chartier02e25112013-08-14 16:14:24 -0700341 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -0700342 accounting::ContinuousSpaceBitmap* bitmap = space->GetMarkBitmap();
Mathieu Chartierbbd695c2014-04-16 09:48:48 -0700343 // We want to have the main space instead of non moving if possible.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700344 if (bitmap != nullptr &&
345 space->GetGcRetentionPolicy() == space::kGcRetentionPolicyAlwaysCollect) {
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700346 current_space_bitmap_ = bitmap;
Mathieu Chartierbbd695c2014-04-16 09:48:48 -0700347 // If we are not the non moving space exit the loop early since this will be good enough.
348 if (space != heap_->GetNonMovingSpace()) {
349 break;
350 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700351 }
352 }
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -0700353 CHECK(current_space_bitmap_ != nullptr) << "Could not find a default mark bitmap\n"
354 << heap_->DumpSpaces();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700355}
356
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800357void MarkSweep::ExpandMarkStack() {
Mathieu Chartierba311b42013-08-27 13:02:30 -0700358 ResizeMarkStack(mark_stack_->Capacity() * 2);
359}
360
361void MarkSweep::ResizeMarkStack(size_t new_size) {
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800362 // Rare case, no need to have Thread::Current be a parameter.
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800363 if (UNLIKELY(mark_stack_->Size() < mark_stack_->Capacity())) {
364 // Someone else acquired the lock and expanded the mark stack before us.
365 return;
366 }
Mathieu Chartier97509952015-07-13 14:35:43 -0700367 std::vector<StackReference<mirror::Object>> temp(mark_stack_->Begin(), mark_stack_->End());
Mathieu Chartierba311b42013-08-27 13:02:30 -0700368 CHECK_LE(mark_stack_->Size(), new_size);
369 mark_stack_->Resize(new_size);
Mathieu Chartiercb535da2015-01-23 13:50:03 -0800370 for (auto& obj : temp) {
371 mark_stack_->PushBack(obj.AsMirrorPtr());
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800372 }
373}
374
Mathieu Chartiere48a1692015-07-15 19:58:45 -0700375mirror::Object* MarkSweep::MarkObject(mirror::Object* obj) {
376 MarkObject(obj, nullptr, MemberOffset(0));
377 return obj;
378}
379
Mathieu Chartier97509952015-07-13 14:35:43 -0700380inline void MarkSweep::MarkObjectNonNullParallel(mirror::Object* obj) {
Mathieu Chartierbbd695c2014-04-16 09:48:48 -0700381 DCHECK(obj != nullptr);
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800382 if (MarkObjectParallel(obj)) {
Mathieu Chartierba311b42013-08-27 13:02:30 -0700383 MutexLock mu(Thread::Current(), mark_stack_lock_);
384 if (UNLIKELY(mark_stack_->Size() >= mark_stack_->Capacity())) {
Mathieu Chartier184e3222013-08-03 14:02:57 -0700385 ExpandMarkStack();
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800386 }
Mathieu Chartierba311b42013-08-27 13:02:30 -0700387 // The object must be pushed on to the mark stack.
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700388 mark_stack_->PushBack(obj);
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800389 }
390}
391
Mathieu Chartier97509952015-07-13 14:35:43 -0700392bool MarkSweep::IsMarkedHeapReference(mirror::HeapReference<mirror::Object>* ref) {
393 return IsMarked(ref->AsMirrorPtr());
Mathieu Chartier308351a2014-06-15 12:39:02 -0700394}
395
Mathieu Chartierbbd695c2014-04-16 09:48:48 -0700396class MarkSweepMarkObjectSlowPath {
397 public:
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -0700398 explicit MarkSweepMarkObjectSlowPath(MarkSweep* mark_sweep,
399 mirror::Object* holder = nullptr,
Hiroshi Yamauchieb2baaf2015-05-13 21:14:22 -0700400 MemberOffset offset = MemberOffset(0))
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -0700401 : mark_sweep_(mark_sweep), holder_(holder), offset_(offset) {}
Mathieu Chartierbbd695c2014-04-16 09:48:48 -0700402
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700403 void operator()(const mirror::Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartierbbd695c2014-04-16 09:48:48 -0700404 if (kProfileLargeObjects) {
405 // TODO: Differentiate between marking and testing somehow.
406 ++mark_sweep_->large_object_test_;
407 ++mark_sweep_->large_object_mark_;
408 }
409 space::LargeObjectSpace* large_object_space = mark_sweep_->GetHeap()->GetLargeObjectsSpace();
Mathieu Chartiera17288e2014-05-08 17:53:19 -0700410 if (UNLIKELY(obj == nullptr || !IsAligned<kPageSize>(obj) ||
Mathieu Chartier2dbe6272014-09-16 10:43:23 -0700411 (kIsDebugBuild && large_object_space != nullptr &&
412 !large_object_space->Contains(obj)))) {
Mathieu Chartier175746a2015-05-01 13:00:23 -0700413 LOG(INTERNAL_FATAL) << "Tried to mark " << obj << " not contained by any spaces";
Hiroshi Yamauchieb2baaf2015-05-13 21:14:22 -0700414 if (holder_ != nullptr) {
Hiroshi Yamauchid0c84122015-05-15 15:23:30 -0700415 size_t holder_size = holder_->SizeOf();
Hiroshi Yamauchieb2baaf2015-05-13 21:14:22 -0700416 ArtField* field = holder_->FindFieldByOffset(offset_);
Hiroshi Yamauchid0c84122015-05-15 15:23:30 -0700417 LOG(INTERNAL_FATAL) << "Field info: "
418 << " holder=" << holder_
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -0700419 << " holder is "
420 << (mark_sweep_->GetHeap()->IsLiveObjectLocked(holder_)
421 ? "alive" : "dead")
Hiroshi Yamauchid0c84122015-05-15 15:23:30 -0700422 << " holder_size=" << holder_size
Hiroshi Yamauchieb2baaf2015-05-13 21:14:22 -0700423 << " holder_type=" << PrettyTypeOf(holder_)
424 << " offset=" << offset_.Uint32Value()
Hiroshi Yamauchid0c84122015-05-15 15:23:30 -0700425 << " field=" << (field != nullptr ? field->GetName() : "nullptr")
426 << " field_type="
427 << (field != nullptr ? field->GetTypeDescriptor() : "")
428 << " first_ref_field_offset="
429 << (holder_->IsClass()
Mathieu Chartiere401d142015-04-22 13:56:20 -0700430 ? holder_->AsClass()->GetFirstReferenceStaticFieldOffset(
431 sizeof(void*))
Hiroshi Yamauchid0c84122015-05-15 15:23:30 -0700432 : holder_->GetClass()->GetFirstReferenceInstanceFieldOffset())
433 << " num_of_ref_fields="
434 << (holder_->IsClass()
435 ? holder_->AsClass()->NumReferenceStaticFields()
436 : holder_->GetClass()->NumReferenceInstanceFields())
437 << "\n";
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -0700438 // Print the memory content of the holder.
439 for (size_t i = 0; i < holder_size / sizeof(uint32_t); ++i) {
440 uint32_t* p = reinterpret_cast<uint32_t*>(holder_);
441 LOG(INTERNAL_FATAL) << &p[i] << ": " << "holder+" << (i * sizeof(uint32_t)) << " = "
442 << std::hex << p[i];
443 }
Hiroshi Yamauchieb2baaf2015-05-13 21:14:22 -0700444 }
Hiroshi Yamauchid38ec802015-05-01 11:50:24 -0700445 PrintFileToLog("/proc/self/maps", LogSeverity::INTERNAL_FATAL);
Vladimir Marko17a924a2015-05-08 15:17:32 +0100446 MemMap::DumpMaps(LOG(INTERNAL_FATAL), true);
Hiroshi Yamauchid0c84122015-05-15 15:23:30 -0700447 {
448 LOG(INTERNAL_FATAL) << "Attempting see if it's a bad root";
449 Thread* self = Thread::Current();
450 if (Locks::mutator_lock_->IsExclusiveHeld(self)) {
451 mark_sweep_->VerifyRoots();
452 } else {
453 const bool heap_bitmap_exclusive_locked =
454 Locks::heap_bitmap_lock_->IsExclusiveHeld(self);
455 if (heap_bitmap_exclusive_locked) {
456 Locks::heap_bitmap_lock_->ExclusiveUnlock(self);
457 }
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700458 {
459 ScopedThreadSuspension(self, kSuspended);
460 ScopedSuspendAll ssa(__FUNCTION__);
461 mark_sweep_->VerifyRoots();
462 }
Hiroshi Yamauchid0c84122015-05-15 15:23:30 -0700463 if (heap_bitmap_exclusive_locked) {
464 Locks::heap_bitmap_lock_->ExclusiveLock(self);
465 }
466 }
467 }
Mathieu Chartierbbd695c2014-04-16 09:48:48 -0700468 LOG(FATAL) << "Can't mark invalid object";
469 }
470 }
471
472 private:
473 MarkSweep* const mark_sweep_;
Hiroshi Yamauchieb2baaf2015-05-13 21:14:22 -0700474 mirror::Object* const holder_;
475 MemberOffset offset_;
Mathieu Chartierbbd695c2014-04-16 09:48:48 -0700476};
477
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -0700478inline void MarkSweep::MarkObjectNonNull(mirror::Object* obj,
479 mirror::Object* holder,
Mathieu Chartier97509952015-07-13 14:35:43 -0700480 MemberOffset offset) {
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700481 DCHECK(obj != nullptr);
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -0700482 if (kUseBakerOrBrooksReadBarrier) {
483 // Verify all the objects have the correct pointer installed.
484 obj->AssertReadBarrierPointer();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800485 }
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800486 if (immune_spaces_.IsInImmuneRegion(obj)) {
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700487 if (kCountMarkedObjects) {
488 ++mark_immune_count_;
489 }
Mathieu Chartierbbd695c2014-04-16 09:48:48 -0700490 DCHECK(mark_bitmap_->Test(obj));
491 } else if (LIKELY(current_space_bitmap_->HasAddress(obj))) {
492 if (kCountMarkedObjects) {
493 ++mark_fastpath_count_;
494 }
495 if (UNLIKELY(!current_space_bitmap_->Set(obj))) {
496 PushOnMarkStack(obj); // This object was not previously marked.
497 }
498 } else {
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700499 if (kCountMarkedObjects) {
500 ++mark_slowpath_count_;
501 }
Hiroshi Yamauchieb2baaf2015-05-13 21:14:22 -0700502 MarkSweepMarkObjectSlowPath visitor(this, holder, offset);
Mathieu Chartierbbd695c2014-04-16 09:48:48 -0700503 // TODO: We already know that the object is not in the current_space_bitmap_ but MarkBitmap::Set
504 // will check again.
505 if (!mark_bitmap_->Set(obj, visitor)) {
506 PushOnMarkStack(obj); // Was not already marked, push.
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700507 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700508 }
509}
510
Mathieu Chartier97509952015-07-13 14:35:43 -0700511inline void MarkSweep::PushOnMarkStack(mirror::Object* obj) {
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700512 if (UNLIKELY(mark_stack_->Size() >= mark_stack_->Capacity())) {
513 // Lock is not needed but is here anyways to please annotalysis.
514 MutexLock mu(Thread::Current(), mark_stack_lock_);
515 ExpandMarkStack();
516 }
517 // The object must be pushed on to the mark stack.
518 mark_stack_->PushBack(obj);
519}
520
Mathieu Chartier97509952015-07-13 14:35:43 -0700521inline bool MarkSweep::MarkObjectParallel(mirror::Object* obj) {
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700522 DCHECK(obj != nullptr);
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -0700523 if (kUseBakerOrBrooksReadBarrier) {
524 // Verify all the objects have the correct pointer installed.
525 obj->AssertReadBarrierPointer();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800526 }
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800527 if (immune_spaces_.IsInImmuneRegion(obj)) {
Mathieu Chartier97509952015-07-13 14:35:43 -0700528 DCHECK(IsMarked(obj) != nullptr);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700529 return false;
530 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700531 // Try to take advantage of locality of references within a space, failing this find the space
532 // the hard way.
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -0700533 accounting::ContinuousSpaceBitmap* object_bitmap = current_space_bitmap_;
Mathieu Chartierbbd695c2014-04-16 09:48:48 -0700534 if (LIKELY(object_bitmap->HasAddress(obj))) {
535 return !object_bitmap->AtomicTestAndSet(obj);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700536 }
Mathieu Chartierbbd695c2014-04-16 09:48:48 -0700537 MarkSweepMarkObjectSlowPath visitor(this);
538 return !mark_bitmap_->AtomicTestAndSet(obj, visitor);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700539}
540
Mathieu Chartier97509952015-07-13 14:35:43 -0700541void MarkSweep::MarkHeapReference(mirror::HeapReference<mirror::Object>* ref) {
542 MarkObject(ref->AsMirrorPtr(), nullptr, MemberOffset(0));
543}
544
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700545// Used to mark objects when processing the mark stack. If an object is null, it is not marked.
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -0700546inline void MarkSweep::MarkObject(mirror::Object* obj,
547 mirror::Object* holder,
Mathieu Chartier97509952015-07-13 14:35:43 -0700548 MemberOffset offset) {
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700549 if (obj != nullptr) {
Hiroshi Yamauchieb2baaf2015-05-13 21:14:22 -0700550 MarkObjectNonNull(obj, holder, offset);
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700551 } else if (kCountMarkedObjects) {
552 ++mark_null_count_;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700553 }
554}
555
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700556class VerifyRootMarkedVisitor : public SingleRootVisitor {
557 public:
558 explicit VerifyRootMarkedVisitor(MarkSweep* collector) : collector_(collector) { }
559
560 void VisitRoot(mirror::Object* root, const RootInfo& info) OVERRIDE
Mathieu Chartier90443472015-07-16 20:32:27 -0700561 SHARED_REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mathieu Chartier97509952015-07-13 14:35:43 -0700562 CHECK(collector_->IsMarked(root) != nullptr) << info.ToString();
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700563 }
564
565 private:
566 MarkSweep* const collector_;
567};
568
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -0700569void MarkSweep::VisitRoots(mirror::Object*** roots,
570 size_t count,
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700571 const RootInfo& info ATTRIBUTE_UNUSED) {
572 for (size_t i = 0; i < count; ++i) {
573 MarkObjectNonNull(*roots[i]);
574 }
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800575}
576
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -0700577void MarkSweep::VisitRoots(mirror::CompressedReference<mirror::Object>** roots,
578 size_t count,
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700579 const RootInfo& info ATTRIBUTE_UNUSED) {
580 for (size_t i = 0; i < count; ++i) {
581 MarkObjectNonNull(roots[i]->AsMirrorPtr());
582 }
Mathieu Chartier893263b2014-03-04 11:07:42 -0800583}
584
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700585class VerifyRootVisitor : public SingleRootVisitor {
586 public:
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700587 void VisitRoot(mirror::Object* root, const RootInfo& info) OVERRIDE
Mathieu Chartier90443472015-07-16 20:32:27 -0700588 SHARED_REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mathieu Chartier9086b652015-04-14 09:35:18 -0700589 // See if the root is on any space bitmap.
590 auto* heap = Runtime::Current()->GetHeap();
591 if (heap->GetLiveBitmap()->GetContinuousSpaceBitmap(root) == nullptr) {
592 space::LargeObjectSpace* large_object_space = heap->GetLargeObjectsSpace();
593 if (large_object_space != nullptr && !large_object_space->Contains(root)) {
Mathieu Chartier175746a2015-05-01 13:00:23 -0700594 LOG(INTERNAL_FATAL) << "Found invalid root: " << root << " " << info;
Mathieu Chartier9086b652015-04-14 09:35:18 -0700595 }
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700596 }
597 }
Mathieu Chartier9086b652015-04-14 09:35:18 -0700598};
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700599
600void MarkSweep::VerifyRoots() {
Mathieu Chartier9086b652015-04-14 09:35:18 -0700601 VerifyRootVisitor visitor;
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700602 Runtime::Current()->GetThreadList()->VisitRoots(&visitor);
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700603}
604
Mathieu Chartier893263b2014-03-04 11:07:42 -0800605void MarkSweep::MarkRoots(Thread* self) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700606 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Mathieu Chartier893263b2014-03-04 11:07:42 -0800607 if (Locks::mutator_lock_->IsExclusiveHeld(self)) {
608 // If we exclusively hold the mutator lock, all threads must be suspended.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700609 Runtime::Current()->VisitRoots(this);
Mathieu Chartier893263b2014-03-04 11:07:42 -0800610 RevokeAllThreadLocalAllocationStacks(self);
611 } else {
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -0700612 MarkRootsCheckpoint(self, kRevokeRosAllocThreadLocalBuffersAtCheckpoint);
Mathieu Chartier893263b2014-03-04 11:07:42 -0800613 // At this point the live stack should no longer have any mutators which push into it.
614 MarkNonThreadRoots();
615 MarkConcurrentRoots(
616 static_cast<VisitRootFlags>(kVisitRootFlagAllRoots | kVisitRootFlagStartLoggingNewRoots));
617 }
Mathieu Chartier9ebae1f2012-10-15 17:38:16 -0700618}
619
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700620void MarkSweep::MarkNonThreadRoots() {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700621 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700622 Runtime::Current()->VisitNonThreadRoots(this);
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700623}
624
Mathieu Chartier893263b2014-03-04 11:07:42 -0800625void MarkSweep::MarkConcurrentRoots(VisitRootFlags flags) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700626 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Ian Rogers1d54e732013-05-02 21:10:01 -0700627 // Visit all runtime roots and clear dirty flags.
Mathieu Chartier4edd8472015-06-01 10:47:36 -0700628 Runtime::Current()->VisitConcurrentRoots(
629 this, static_cast<VisitRootFlags>(flags | kVisitRootFlagNonMoving));
Carl Shapiro69759ea2011-07-21 18:13:35 -0700630}
631
Mathieu Chartier407f7022014-02-18 14:37:05 -0800632class DelayReferenceReferentVisitor {
633 public:
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -0700634 explicit DelayReferenceReferentVisitor(MarkSweep* collector) : collector_(collector) {}
Mathieu Chartier407f7022014-02-18 14:37:05 -0800635
636 void operator()(mirror::Class* klass, mirror::Reference* ref) const
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -0700637 REQUIRES(Locks::heap_bitmap_lock_)
638 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartier407f7022014-02-18 14:37:05 -0800639 collector_->DelayReferenceReferent(klass, ref);
640 }
641
642 private:
643 MarkSweep* const collector_;
644};
645
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700646template <bool kUseFinger = false>
647class MarkStackTask : public Task {
648 public:
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -0700649 MarkStackTask(ThreadPool* thread_pool,
650 MarkSweep* mark_sweep,
651 size_t mark_stack_size,
Mathieu Chartier97509952015-07-13 14:35:43 -0700652 StackReference<mirror::Object>* mark_stack)
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700653 : mark_sweep_(mark_sweep),
654 thread_pool_(thread_pool),
655 mark_stack_pos_(mark_stack_size) {
656 // We may have to copy part of an existing mark stack when another mark stack overflows.
657 if (mark_stack_size != 0) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700658 DCHECK(mark_stack != nullptr);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700659 // TODO: Check performance?
660 std::copy(mark_stack, mark_stack + mark_stack_size, mark_stack_);
Ian Rogers1d54e732013-05-02 21:10:01 -0700661 }
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700662 if (kCountTasks) {
663 ++mark_sweep_->work_chunks_created_;
664 }
665 }
666
667 static const size_t kMaxSize = 1 * KB;
668
669 protected:
Mathieu Chartier407f7022014-02-18 14:37:05 -0800670 class MarkObjectParallelVisitor {
671 public:
Roland Levillain3887c462015-08-12 18:15:42 +0100672 ALWAYS_INLINE MarkObjectParallelVisitor(MarkStackTask<kUseFinger>* chunk_task,
673 MarkSweep* mark_sweep)
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700674 : chunk_task_(chunk_task), mark_sweep_(mark_sweep) {}
Mathieu Chartier407f7022014-02-18 14:37:05 -0800675
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -0700676 ALWAYS_INLINE void operator()(mirror::Object* obj,
677 MemberOffset offset,
678 bool is_static ATTRIBUTE_UNUSED) const
679 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700680 Mark(obj->GetFieldObject<mirror::Object>(offset));
681 }
682
683 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700684 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700685 if (!root->IsNull()) {
686 VisitRoot(root);
687 }
688 }
689
690 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
691 SHARED_REQUIRES(Locks::mutator_lock_) {
692 if (kCheckLocks) {
693 Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
694 Locks::heap_bitmap_lock_->AssertExclusiveHeld(Thread::Current());
695 }
696 Mark(root->AsMirrorPtr());
697 }
698
699 private:
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -0700700 ALWAYS_INLINE void Mark(mirror::Object* ref) const SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartier407f7022014-02-18 14:37:05 -0800701 if (ref != nullptr && mark_sweep_->MarkObjectParallel(ref)) {
702 if (kUseFinger) {
Yabin Cuic7df66e2015-04-15 15:40:18 -0700703 std::atomic_thread_fence(std::memory_order_seq_cst);
Mathieu Chartier407f7022014-02-18 14:37:05 -0800704 if (reinterpret_cast<uintptr_t>(ref) >=
Ian Rogers3e5cf302014-05-20 16:40:37 -0700705 static_cast<uintptr_t>(mark_sweep_->atomic_finger_.LoadRelaxed())) {
Mathieu Chartier407f7022014-02-18 14:37:05 -0800706 return;
707 }
708 }
709 chunk_task_->MarkStackPush(ref);
710 }
711 }
712
Mathieu Chartier407f7022014-02-18 14:37:05 -0800713 MarkStackTask<kUseFinger>* const chunk_task_;
714 MarkSweep* const mark_sweep_;
715 };
716
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700717 class ScanObjectParallelVisitor {
718 public:
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -0700719 ALWAYS_INLINE explicit ScanObjectParallelVisitor(MarkStackTask<kUseFinger>* chunk_task)
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700720 : chunk_task_(chunk_task) {}
721
Mathieu Chartier407f7022014-02-18 14:37:05 -0800722 // No thread safety analysis since multiple threads will use this visitor.
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -0700723 void operator()(mirror::Object* obj) const
724 REQUIRES(Locks::heap_bitmap_lock_)
725 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartier407f7022014-02-18 14:37:05 -0800726 MarkSweep* const mark_sweep = chunk_task_->mark_sweep_;
727 MarkObjectParallelVisitor mark_visitor(chunk_task_, mark_sweep);
728 DelayReferenceReferentVisitor ref_visitor(mark_sweep);
729 mark_sweep->ScanObjectVisit(obj, mark_visitor, ref_visitor);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700730 }
731
732 private:
733 MarkStackTask<kUseFinger>* const chunk_task_;
734 };
735
736 virtual ~MarkStackTask() {
737 // Make sure that we have cleared our mark stack.
738 DCHECK_EQ(mark_stack_pos_, 0U);
739 if (kCountTasks) {
740 ++mark_sweep_->work_chunks_deleted_;
741 }
742 }
743
744 MarkSweep* const mark_sweep_;
745 ThreadPool* const thread_pool_;
746 // Thread local mark stack for this task.
Mathieu Chartier97509952015-07-13 14:35:43 -0700747 StackReference<mirror::Object> mark_stack_[kMaxSize];
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700748 // Mark stack position.
749 size_t mark_stack_pos_;
750
Mathieu Chartier97509952015-07-13 14:35:43 -0700751 ALWAYS_INLINE void MarkStackPush(mirror::Object* obj)
Mathieu Chartier90443472015-07-16 20:32:27 -0700752 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700753 if (UNLIKELY(mark_stack_pos_ == kMaxSize)) {
754 // Mark stack overflow, give 1/2 the stack to the thread pool as a new work task.
755 mark_stack_pos_ /= 2;
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -0700756 auto* task = new MarkStackTask(thread_pool_,
757 mark_sweep_,
758 kMaxSize - mark_stack_pos_,
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700759 mark_stack_ + mark_stack_pos_);
760 thread_pool_->AddTask(Thread::Current(), task);
761 }
762 DCHECK(obj != nullptr);
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700763 DCHECK_LT(mark_stack_pos_, kMaxSize);
Mathieu Chartiercb535da2015-01-23 13:50:03 -0800764 mark_stack_[mark_stack_pos_++].Assign(obj);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700765 }
766
767 virtual void Finalize() {
768 delete this;
769 }
770
771 // Scans all of the objects
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -0700772 virtual void Run(Thread* self ATTRIBUTE_UNUSED)
773 REQUIRES(Locks::heap_bitmap_lock_)
774 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700775 ScanObjectParallelVisitor visitor(this);
776 // TODO: Tune this.
777 static const size_t kFifoSize = 4;
Mathieu Chartier97509952015-07-13 14:35:43 -0700778 BoundedFifoPowerOfTwo<mirror::Object*, kFifoSize> prefetch_fifo;
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700779 for (;;) {
Mathieu Chartier97509952015-07-13 14:35:43 -0700780 mirror::Object* obj = nullptr;
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700781 if (kUseMarkStackPrefetch) {
782 while (mark_stack_pos_ != 0 && prefetch_fifo.size() < kFifoSize) {
Mathieu Chartier97509952015-07-13 14:35:43 -0700783 mirror::Object* const mark_stack_obj = mark_stack_[--mark_stack_pos_].AsMirrorPtr();
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800784 DCHECK(mark_stack_obj != nullptr);
785 __builtin_prefetch(mark_stack_obj);
786 prefetch_fifo.push_back(mark_stack_obj);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700787 }
788 if (UNLIKELY(prefetch_fifo.empty())) {
789 break;
790 }
791 obj = prefetch_fifo.front();
792 prefetch_fifo.pop_front();
793 } else {
794 if (UNLIKELY(mark_stack_pos_ == 0)) {
795 break;
796 }
Mathieu Chartiercb535da2015-01-23 13:50:03 -0800797 obj = mark_stack_[--mark_stack_pos_].AsMirrorPtr();
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700798 }
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700799 DCHECK(obj != nullptr);
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700800 visitor(obj);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700801 }
802 }
803};
804
805class CardScanTask : public MarkStackTask<false> {
806 public:
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -0700807 CardScanTask(ThreadPool* thread_pool,
808 MarkSweep* mark_sweep,
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -0700809 accounting::ContinuousSpaceBitmap* bitmap,
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -0700810 uint8_t* begin,
811 uint8_t* end,
812 uint8_t minimum_age,
813 size_t mark_stack_size,
814 StackReference<mirror::Object>* mark_stack_obj,
815 bool clear_card)
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700816 : MarkStackTask<false>(thread_pool, mark_sweep, mark_stack_size, mark_stack_obj),
817 bitmap_(bitmap),
818 begin_(begin),
819 end_(end),
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -0700820 minimum_age_(minimum_age),
821 clear_card_(clear_card) {}
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700822
823 protected:
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -0700824 accounting::ContinuousSpaceBitmap* const bitmap_;
Ian Rogers13735952014-10-08 12:43:28 -0700825 uint8_t* const begin_;
826 uint8_t* const end_;
827 const uint8_t minimum_age_;
Lei Li727b2942015-01-15 11:26:34 +0800828 const bool clear_card_;
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700829
830 virtual void Finalize() {
831 delete this;
832 }
833
834 virtual void Run(Thread* self) NO_THREAD_SAFETY_ANALYSIS {
835 ScanObjectParallelVisitor visitor(this);
836 accounting::CardTable* card_table = mark_sweep_->GetHeap()->GetCardTable();
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -0700837 size_t cards_scanned = clear_card_
838 ? card_table->Scan<true>(bitmap_, begin_, end_, visitor, minimum_age_)
839 : card_table->Scan<false>(bitmap_, begin_, end_, visitor, minimum_age_);
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700840 VLOG(heap) << "Parallel scanning cards " << reinterpret_cast<void*>(begin_) << " - "
841 << reinterpret_cast<void*>(end_) << " = " << cards_scanned;
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700842 // Finish by emptying our local mark stack.
843 MarkStackTask::Run(self);
844 }
845};
846
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700847size_t MarkSweep::GetThreadCount(bool paused) const {
848 if (heap_->GetThreadPool() == nullptr || !heap_->CareAboutPauseTimes()) {
Mathieu Chartierbbd695c2014-04-16 09:48:48 -0700849 return 1;
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700850 }
Mathieu Chartier10d68862015-04-15 14:21:33 -0700851 return (paused ? heap_->GetParallelGCThreadCount() : heap_->GetConcGCThreadCount()) + 1;
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700852}
853
Ian Rogers13735952014-10-08 12:43:28 -0700854void MarkSweep::ScanGrayObjects(bool paused, uint8_t minimum_age) {
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700855 accounting::CardTable* card_table = GetHeap()->GetCardTable();
856 ThreadPool* thread_pool = GetHeap()->GetThreadPool();
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700857 size_t thread_count = GetThreadCount(paused);
858 // The parallel version with only one thread is faster for card scanning, TODO: fix.
Mathieu Chartierbbd695c2014-04-16 09:48:48 -0700859 if (kParallelCardScan && thread_count > 1) {
Mathieu Chartier720ef762013-08-17 14:46:54 -0700860 Thread* self = Thread::Current();
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700861 // Can't have a different split for each space since multiple spaces can have their cards being
862 // scanned at the same time.
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700863 TimingLogger::ScopedTiming t(paused ? "(Paused)ScanGrayObjects" : __FUNCTION__,
864 GetTimings());
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700865 // Try to take some of the mark stack since we can pass this off to the worker tasks.
Mathieu Chartier97509952015-07-13 14:35:43 -0700866 StackReference<mirror::Object>* mark_stack_begin = mark_stack_->Begin();
867 StackReference<mirror::Object>* mark_stack_end = mark_stack_->End();
Mathieu Chartier720ef762013-08-17 14:46:54 -0700868 const size_t mark_stack_size = mark_stack_end - mark_stack_begin;
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700869 // Estimated number of work tasks we will create.
870 const size_t mark_stack_tasks = GetHeap()->GetContinuousSpaces().size() * thread_count;
871 DCHECK_NE(mark_stack_tasks, 0U);
872 const size_t mark_stack_delta = std::min(CardScanTask::kMaxSize / 2,
873 mark_stack_size / mark_stack_tasks + 1);
874 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700875 if (space->GetMarkBitmap() == nullptr) {
876 continue;
877 }
Ian Rogers13735952014-10-08 12:43:28 -0700878 uint8_t* card_begin = space->Begin();
879 uint8_t* card_end = space->End();
Hiroshi Yamauchi0941b042013-11-05 11:34:03 -0800880 // Align up the end address. For example, the image space's end
881 // may not be card-size-aligned.
882 card_end = AlignUp(card_end, accounting::CardTable::kCardSize);
Roland Levillain14d90572015-07-16 10:52:26 +0100883 DCHECK_ALIGNED(card_begin, accounting::CardTable::kCardSize);
884 DCHECK_ALIGNED(card_end, accounting::CardTable::kCardSize);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700885 // Calculate how many bytes of heap we will scan,
886 const size_t address_range = card_end - card_begin;
887 // Calculate how much address range each task gets.
888 const size_t card_delta = RoundUp(address_range / thread_count + 1,
889 accounting::CardTable::kCardSize);
Lei Li727b2942015-01-15 11:26:34 +0800890 // If paused and the space is neither zygote nor image space, we could clear the dirty
891 // cards to avoid accumulating them to increase card scanning load in the following GC
892 // cycles. We need to keep dirty cards of image space and zygote space in order to track
893 // references to the other spaces.
894 bool clear_card = paused && !space->IsZygoteSpace() && !space->IsImageSpace();
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700895 // Create the worker tasks for this space.
896 while (card_begin != card_end) {
897 // Add a range of cards.
898 size_t addr_remaining = card_end - card_begin;
899 size_t card_increment = std::min(card_delta, addr_remaining);
900 // Take from the back of the mark stack.
901 size_t mark_stack_remaining = mark_stack_end - mark_stack_begin;
902 size_t mark_stack_increment = std::min(mark_stack_delta, mark_stack_remaining);
903 mark_stack_end -= mark_stack_increment;
904 mark_stack_->PopBackCount(static_cast<int32_t>(mark_stack_increment));
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700905 DCHECK_EQ(mark_stack_end, mark_stack_->End());
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700906 // Add the new task to the thread pool.
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -0700907 auto* task = new CardScanTask(thread_pool,
908 this,
909 space->GetMarkBitmap(),
910 card_begin,
911 card_begin + card_increment,
912 minimum_age,
913 mark_stack_increment,
914 mark_stack_end,
915 clear_card);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700916 thread_pool->AddTask(self, task);
917 card_begin += card_increment;
918 }
919 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700920
Hiroshi Yamauchi0941b042013-11-05 11:34:03 -0800921 // Note: the card scan below may dirty new cards (and scan them)
922 // as a side effect when a Reference object is encountered and
923 // queued during the marking. See b/11465268.
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700924 thread_pool->SetMaxActiveWorkers(thread_count - 1);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700925 thread_pool->StartWorkers(self);
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700926 thread_pool->Wait(self, true, true);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700927 thread_pool->StopWorkers(self);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700928 } else {
929 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700930 if (space->GetMarkBitmap() != nullptr) {
931 // Image spaces are handled properly since live == marked for them.
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700932 const char* name = nullptr;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700933 switch (space->GetGcRetentionPolicy()) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700934 case space::kGcRetentionPolicyNeverCollect:
935 name = paused ? "(Paused)ScanGrayImageSpaceObjects" : "ScanGrayImageSpaceObjects";
936 break;
937 case space::kGcRetentionPolicyFullCollect:
938 name = paused ? "(Paused)ScanGrayZygoteSpaceObjects" : "ScanGrayZygoteSpaceObjects";
939 break;
940 case space::kGcRetentionPolicyAlwaysCollect:
941 name = paused ? "(Paused)ScanGrayAllocSpaceObjects" : "ScanGrayAllocSpaceObjects";
942 break;
943 default:
944 LOG(FATAL) << "Unreachable";
Ian Rogers2c4257b2014-10-24 14:20:06 -0700945 UNREACHABLE();
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700946 }
947 TimingLogger::ScopedTiming t(name, GetTimings());
Mathieu Chartier590fee92013-09-13 13:46:47 -0700948 ScanObjectVisitor visitor(this);
Lei Li727b2942015-01-15 11:26:34 +0800949 bool clear_card = paused && !space->IsZygoteSpace() && !space->IsImageSpace();
950 if (clear_card) {
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -0700951 card_table->Scan<true>(space->GetMarkBitmap(),
952 space->Begin(),
953 space->End(),
954 visitor,
Lei Li727b2942015-01-15 11:26:34 +0800955 minimum_age);
956 } else {
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -0700957 card_table->Scan<false>(space->GetMarkBitmap(),
958 space->Begin(),
959 space->End(),
960 visitor,
Lei Li727b2942015-01-15 11:26:34 +0800961 minimum_age);
962 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700963 }
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700964 }
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700965 }
966}
967
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700968class RecursiveMarkTask : public MarkStackTask<false> {
969 public:
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -0700970 RecursiveMarkTask(ThreadPool* thread_pool,
971 MarkSweep* mark_sweep,
972 accounting::ContinuousSpaceBitmap* bitmap,
973 uintptr_t begin,
974 uintptr_t end)
975 : MarkStackTask<false>(thread_pool, mark_sweep, 0, nullptr),
976 bitmap_(bitmap),
977 begin_(begin),
978 end_(end) {}
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700979
980 protected:
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -0700981 accounting::ContinuousSpaceBitmap* const bitmap_;
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700982 const uintptr_t begin_;
983 const uintptr_t end_;
984
985 virtual void Finalize() {
986 delete this;
987 }
988
989 // Scans all of the objects
990 virtual void Run(Thread* self) NO_THREAD_SAFETY_ANALYSIS {
991 ScanObjectParallelVisitor visitor(this);
992 bitmap_->VisitMarkedRange(begin_, end_, visitor);
993 // Finish by emptying our local mark stack.
994 MarkStackTask::Run(self);
995 }
996};
997
Carl Shapiro58551df2011-07-24 03:09:51 -0700998// Populates the mark stack based on the set of marked objects and
999// recursively marks until the mark stack is emptied.
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001000void MarkSweep::RecursiveMark() {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001001 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Mathieu Chartiera1602f22014-01-13 17:19:19 -08001002 // RecursiveMark will build the lists of known instances of the Reference classes. See
1003 // DelayReferenceReferent for details.
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001004 if (kUseRecursiveMark) {
1005 const bool partial = GetGcType() == kGcTypePartial;
1006 ScanObjectVisitor scan_visitor(this);
1007 auto* self = Thread::Current();
1008 ThreadPool* thread_pool = heap_->GetThreadPool();
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001009 size_t thread_count = GetThreadCount(false);
1010 const bool parallel = kParallelRecursiveMark && thread_count > 1;
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001011 mark_stack_->Reset();
Mathieu Chartier02e25112013-08-14 16:14:24 -07001012 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001013 if ((space->GetGcRetentionPolicy() == space::kGcRetentionPolicyAlwaysCollect) ||
1014 (!partial && space->GetGcRetentionPolicy() == space::kGcRetentionPolicyFullCollect)) {
Mathieu Chartier0e54cd02014-03-20 12:41:23 -07001015 current_space_bitmap_ = space->GetMarkBitmap();
1016 if (current_space_bitmap_ == nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001017 continue;
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001018 }
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001019 if (parallel) {
1020 // We will use the mark stack the future.
1021 // CHECK(mark_stack_->IsEmpty());
1022 // This function does not handle heap end increasing, so we must use the space end.
1023 uintptr_t begin = reinterpret_cast<uintptr_t>(space->Begin());
1024 uintptr_t end = reinterpret_cast<uintptr_t>(space->End());
Ian Rogers3e5cf302014-05-20 16:40:37 -07001025 atomic_finger_.StoreRelaxed(AtomicInteger::MaxValue());
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001026
1027 // Create a few worker tasks.
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001028 const size_t n = thread_count * 2;
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001029 while (begin != end) {
1030 uintptr_t start = begin;
1031 uintptr_t delta = (end - begin) / n;
1032 delta = RoundUp(delta, KB);
1033 if (delta < 16 * KB) delta = end - begin;
1034 begin += delta;
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -07001035 auto* task = new RecursiveMarkTask(thread_pool,
1036 this,
1037 current_space_bitmap_,
1038 start,
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001039 begin);
1040 thread_pool->AddTask(self, task);
1041 }
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001042 thread_pool->SetMaxActiveWorkers(thread_count - 1);
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001043 thread_pool->StartWorkers(self);
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001044 thread_pool->Wait(self, true, true);
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001045 thread_pool->StopWorkers(self);
1046 } else {
1047 // This function does not handle heap end increasing, so we must use the space end.
1048 uintptr_t begin = reinterpret_cast<uintptr_t>(space->Begin());
1049 uintptr_t end = reinterpret_cast<uintptr_t>(space->End());
Mathieu Chartier0e54cd02014-03-20 12:41:23 -07001050 current_space_bitmap_->VisitMarkedRange(begin, end, scan_visitor);
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001051 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001052 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001053 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001054 }
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001055 ProcessMarkStack(false);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001056}
1057
Ian Rogers13735952014-10-08 12:43:28 -07001058void MarkSweep::RecursiveMarkDirtyObjects(bool paused, uint8_t minimum_age) {
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001059 ScanGrayObjects(paused, minimum_age);
1060 ProcessMarkStack(paused);
Mathieu Chartier262e5ff2012-06-01 17:35:38 -07001061}
1062
Carl Shapiro58551df2011-07-24 03:09:51 -07001063void MarkSweep::ReMarkRoots() {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001064 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Mathieu Chartier893263b2014-03-04 11:07:42 -08001065 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001066 Runtime::Current()->VisitRoots(this, static_cast<VisitRootFlags>(
1067 kVisitRootFlagNewRoots | kVisitRootFlagStopLoggingNewRoots | kVisitRootFlagClearRootLog));
Mathieu Chartier7bf9f192014-04-04 11:09:41 -07001068 if (kVerifyRootsMarked) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001069 TimingLogger::ScopedTiming t2("(Paused)VerifyRoots", GetTimings());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001070 VerifyRootMarkedVisitor visitor(this);
1071 Runtime::Current()->VisitRoots(&visitor);
Mathieu Chartier893263b2014-03-04 11:07:42 -08001072 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001073}
1074
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -07001075void MarkSweep::SweepSystemWeaks(Thread* self) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001076 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Mathieu Chartier14c3bf92015-07-13 14:35:43 -07001077 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier97509952015-07-13 14:35:43 -07001078 Runtime::Current()->SweepSystemWeaks(this);
Carl Shapiro58551df2011-07-24 03:09:51 -07001079}
1080
Mathieu Chartier97509952015-07-13 14:35:43 -07001081class VerifySystemWeakVisitor : public IsMarkedVisitor {
1082 public:
1083 explicit VerifySystemWeakVisitor(MarkSweep* mark_sweep) : mark_sweep_(mark_sweep) {}
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001084
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -07001085 virtual mirror::Object* IsMarked(mirror::Object* obj)
1086 OVERRIDE
Mathieu Chartier90443472015-07-16 20:32:27 -07001087 SHARED_REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mathieu Chartier97509952015-07-13 14:35:43 -07001088 mark_sweep_->VerifyIsLive(obj);
1089 return obj;
1090 }
1091
1092 MarkSweep* const mark_sweep_;
1093};
1094
1095void MarkSweep::VerifyIsLive(const mirror::Object* obj) {
Mathieu Chartier4aeec172014-03-27 16:09:46 -07001096 if (!heap_->GetLiveBitmap()->Test(obj)) {
Mathieu Chartiercb535da2015-01-23 13:50:03 -08001097 // TODO: Consider live stack? Has this code bitrotted?
1098 CHECK(!heap_->allocation_stack_->Contains(obj))
1099 << "Found dead object " << obj << "\n" << heap_->DumpSpaces();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001100 }
1101}
1102
1103void MarkSweep::VerifySystemWeaks() {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001104 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001105 // Verify system weaks, uses a special object visitor which returns the input object.
Mathieu Chartier97509952015-07-13 14:35:43 -07001106 VerifySystemWeakVisitor visitor(this);
1107 Runtime::Current()->SweepSystemWeaks(&visitor);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001108}
1109
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001110class CheckpointMarkThreadRoots : public Closure, public RootVisitor {
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001111 public:
Roland Levillain3887c462015-08-12 18:15:42 +01001112 CheckpointMarkThreadRoots(MarkSweep* mark_sweep,
1113 bool revoke_ros_alloc_thread_local_buffers_at_checkpoint)
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -07001114 : mark_sweep_(mark_sweep),
1115 revoke_ros_alloc_thread_local_buffers_at_checkpoint_(
1116 revoke_ros_alloc_thread_local_buffers_at_checkpoint) {
1117 }
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001118
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001119 void VisitRoots(mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -07001120 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_)
1121 REQUIRES(Locks::heap_bitmap_lock_) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001122 for (size_t i = 0; i < count; ++i) {
1123 mark_sweep_->MarkObjectNonNullParallel(*roots[i]);
1124 }
1125 }
1126
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -07001127 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots,
1128 size_t count,
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001129 const RootInfo& info ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -07001130 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_)
1131 REQUIRES(Locks::heap_bitmap_lock_) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001132 for (size_t i = 0; i < count; ++i) {
1133 mark_sweep_->MarkObjectNonNullParallel(roots[i]->AsMirrorPtr());
1134 }
1135 }
1136
Mathieu Chartier4aeec172014-03-27 16:09:46 -07001137 virtual void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001138 ScopedTrace trace("Marking thread roots");
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001139 // Note: self is not necessarily equal to thread since thread may be suspended.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001140 Thread* const self = Thread::Current();
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001141 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
1142 << thread->GetState() << " thread " << thread << " self " << self;
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001143 thread->VisitRoots(this);
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -07001144 if (revoke_ros_alloc_thread_local_buffers_at_checkpoint_) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001145 ScopedTrace trace2("RevokeRosAllocThreadLocalBuffers");
Hiroshi Yamauchic93c5302014-03-20 16:15:37 -07001146 mark_sweep_->GetHeap()->RevokeRosAllocThreadLocalBuffers(thread);
1147 }
Lei Lidd9943d2015-02-02 14:24:44 +08001148 // If thread is a running mutator, then act on behalf of the garbage collector.
1149 // See the code in ThreadList::RunCheckpoint.
Mathieu Chartier10d25082015-10-28 18:36:09 -07001150 mark_sweep_->GetBarrier().Pass(self);
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001151 }
1152
1153 private:
Mathieu Chartier4aeec172014-03-27 16:09:46 -07001154 MarkSweep* const mark_sweep_;
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -07001155 const bool revoke_ros_alloc_thread_local_buffers_at_checkpoint_;
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001156};
1157
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -07001158void MarkSweep::MarkRootsCheckpoint(Thread* self,
1159 bool revoke_ros_alloc_thread_local_buffers_at_checkpoint) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001160 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -07001161 CheckpointMarkThreadRoots check_point(this, revoke_ros_alloc_thread_local_buffers_at_checkpoint);
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001162 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Ian Rogers1d54e732013-05-02 21:10:01 -07001163 // Request the check point is run on all threads returning a count of the threads that must
1164 // run through the barrier including self.
1165 size_t barrier_count = thread_list->RunCheckpoint(&check_point);
1166 // Release locks then wait for all mutator threads to pass the barrier.
Lei Lidd9943d2015-02-02 14:24:44 +08001167 // If there are no threads to wait which implys that all the checkpoint functions are finished,
1168 // then no need to release locks.
1169 if (barrier_count == 0) {
1170 return;
1171 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001172 Locks::heap_bitmap_lock_->ExclusiveUnlock(self);
1173 Locks::mutator_lock_->SharedUnlock(self);
Mathieu Chartier4aeec172014-03-27 16:09:46 -07001174 {
1175 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
1176 gc_barrier_->Increment(self, barrier_count);
1177 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001178 Locks::mutator_lock_->SharedLock(self);
1179 Locks::heap_bitmap_lock_->ExclusiveLock(self);
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001180}
1181
Ian Rogers1d54e732013-05-02 21:10:01 -07001182void MarkSweep::SweepArray(accounting::ObjectStack* allocations, bool swap_bitmaps) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001183 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001184 Thread* self = Thread::Current();
Hiroshi Yamauchibbdc5bc2014-05-28 14:04:59 -07001185 mirror::Object** chunk_free_buffer = reinterpret_cast<mirror::Object**>(
1186 sweep_array_free_buffer_mem_map_->BaseBegin());
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001187 size_t chunk_free_pos = 0;
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07001188 ObjectBytePair freed;
1189 ObjectBytePair freed_los;
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001190 // How many objects are left in the array, modified after each space is swept.
Mathieu Chartier97509952015-07-13 14:35:43 -07001191 StackReference<mirror::Object>* objects = allocations->Begin();
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001192 size_t count = allocations->Size();
1193 // Change the order to ensure that the non-moving space last swept as an optimization.
1194 std::vector<space::ContinuousSpace*> sweep_spaces;
1195 space::ContinuousSpace* non_moving_space = nullptr;
1196 for (space::ContinuousSpace* space : heap_->GetContinuousSpaces()) {
Mathieu Chartier763a31e2015-11-16 16:05:55 -08001197 if (space->IsAllocSpace() &&
1198 !immune_spaces_.ContainsSpace(space) &&
Mathieu Chartier8d562102014-03-12 17:42:10 -07001199 space->GetLiveBitmap() != nullptr) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001200 if (space == heap_->GetNonMovingSpace()) {
1201 non_moving_space = space;
1202 } else {
1203 sweep_spaces.push_back(space);
1204 }
1205 }
1206 }
1207 // Unlikely to sweep a significant amount of non_movable objects, so we do these after the after
1208 // the other alloc spaces as an optimization.
1209 if (non_moving_space != nullptr) {
1210 sweep_spaces.push_back(non_moving_space);
1211 }
1212 // Start by sweeping the continuous spaces.
1213 for (space::ContinuousSpace* space : sweep_spaces) {
1214 space::AllocSpace* alloc_space = space->AsAllocSpace();
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -07001215 accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
1216 accounting::ContinuousSpaceBitmap* mark_bitmap = space->GetMarkBitmap();
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001217 if (swap_bitmaps) {
1218 std::swap(live_bitmap, mark_bitmap);
1219 }
Mathieu Chartier97509952015-07-13 14:35:43 -07001220 StackReference<mirror::Object>* out = objects;
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001221 for (size_t i = 0; i < count; ++i) {
Mathieu Chartier97509952015-07-13 14:35:43 -07001222 mirror::Object* const obj = objects[i].AsMirrorPtr();
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08001223 if (kUseThreadLocalAllocationStack && obj == nullptr) {
1224 continue;
1225 }
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001226 if (space->HasAddress(obj)) {
1227 // This object is in the space, remove it from the array and add it to the sweep buffer
1228 // if needed.
1229 if (!mark_bitmap->Test(obj)) {
1230 if (chunk_free_pos >= kSweepArrayChunkFreeSize) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001231 TimingLogger::ScopedTiming t2("FreeList", GetTimings());
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07001232 freed.objects += chunk_free_pos;
1233 freed.bytes += alloc_space->FreeList(self, chunk_free_pos, chunk_free_buffer);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001234 chunk_free_pos = 0;
1235 }
1236 chunk_free_buffer[chunk_free_pos++] = obj;
1237 }
1238 } else {
Mathieu Chartiercb535da2015-01-23 13:50:03 -08001239 (out++)->Assign(obj);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001240 }
1241 }
1242 if (chunk_free_pos > 0) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001243 TimingLogger::ScopedTiming t2("FreeList", GetTimings());
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07001244 freed.objects += chunk_free_pos;
1245 freed.bytes += alloc_space->FreeList(self, chunk_free_pos, chunk_free_buffer);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001246 chunk_free_pos = 0;
1247 }
1248 // All of the references which space contained are no longer in the allocation stack, update
1249 // the count.
1250 count = out - objects;
1251 }
1252 // Handle the large object space.
1253 space::LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
Mathieu Chartier2dbe6272014-09-16 10:43:23 -07001254 if (large_object_space != nullptr) {
1255 accounting::LargeObjectBitmap* large_live_objects = large_object_space->GetLiveBitmap();
1256 accounting::LargeObjectBitmap* large_mark_objects = large_object_space->GetMarkBitmap();
1257 if (swap_bitmaps) {
1258 std::swap(large_live_objects, large_mark_objects);
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08001259 }
Mathieu Chartier2dbe6272014-09-16 10:43:23 -07001260 for (size_t i = 0; i < count; ++i) {
Mathieu Chartier97509952015-07-13 14:35:43 -07001261 mirror::Object* const obj = objects[i].AsMirrorPtr();
Mathieu Chartier2dbe6272014-09-16 10:43:23 -07001262 // Handle large objects.
1263 if (kUseThreadLocalAllocationStack && obj == nullptr) {
1264 continue;
1265 }
1266 if (!large_mark_objects->Test(obj)) {
1267 ++freed_los.objects;
1268 freed_los.bytes += large_object_space->Free(self, obj);
1269 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001270 }
1271 }
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001272 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001273 TimingLogger::ScopedTiming t2("RecordFree", GetTimings());
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001274 RecordFree(freed);
1275 RecordFreeLOS(freed_los);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001276 t2.NewTiming("ResetStack");
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001277 allocations->Reset();
1278 }
Ian Rogersc5f17732014-06-05 20:48:42 -07001279 sweep_array_free_buffer_mem_map_->MadviseDontNeedAndZero();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001280}
1281
Ian Rogers1d54e732013-05-02 21:10:01 -07001282void MarkSweep::Sweep(bool swap_bitmaps) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001283 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -07001284 // Ensure that nobody inserted items in the live stack after we swapped the stacks.
1285 CHECK_GE(live_stack_freeze_size_, GetHeap()->GetLiveStack()->Size());
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001286 {
1287 TimingLogger::ScopedTiming t2("MarkAllocStackAsLive", GetTimings());
1288 // Mark everything allocated since the last as GC live so that we can sweep concurrently,
1289 // knowing that new allocations won't be marked as live.
1290 accounting::ObjectStack* live_stack = heap_->GetLiveStack();
1291 heap_->MarkAllocStackAsLive(live_stack);
1292 live_stack->Reset();
1293 DCHECK(mark_stack_->IsEmpty());
1294 }
Mathieu Chartier02e25112013-08-14 16:14:24 -07001295 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Mathieu Chartiera1602f22014-01-13 17:19:19 -08001296 if (space->IsContinuousMemMapAllocSpace()) {
1297 space::ContinuousMemMapAllocSpace* alloc_space = space->AsContinuousMemMapAllocSpace();
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001298 TimingLogger::ScopedTiming split(
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -07001299 alloc_space->IsZygoteSpace() ? "SweepZygoteSpace" : "SweepMallocSpace",
1300 GetTimings());
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07001301 RecordFree(alloc_space->Sweep(swap_bitmaps));
Carl Shapiro58551df2011-07-24 03:09:51 -07001302 }
1303 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001304 SweepLargeObjects(swap_bitmaps);
Carl Shapiro58551df2011-07-24 03:09:51 -07001305}
1306
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001307void MarkSweep::SweepLargeObjects(bool swap_bitmaps) {
Mathieu Chartier2dbe6272014-09-16 10:43:23 -07001308 space::LargeObjectSpace* los = heap_->GetLargeObjectsSpace();
1309 if (los != nullptr) {
1310 TimingLogger::ScopedTiming split(__FUNCTION__, GetTimings());
1311 RecordFreeLOS(los->Sweep(swap_bitmaps));
1312 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001313}
1314
Mathieu Chartier407f7022014-02-18 14:37:05 -08001315// Process the "referent" field in a java.lang.ref.Reference. If the referent has not yet been
1316// marked, put it on the appropriate list in the heap for later processing.
1317void MarkSweep::DelayReferenceReferent(mirror::Class* klass, mirror::Reference* ref) {
Mathieu Chartier97509952015-07-13 14:35:43 -07001318 heap_->GetReferenceProcessor()->DelayReferenceReferent(klass, ref, this);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001319}
1320
Mathieu Chartier97509952015-07-13 14:35:43 -07001321class MarkVisitor {
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001322 public:
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -07001323 ALWAYS_INLINE explicit MarkVisitor(MarkSweep* const mark_sweep) : mark_sweep_(mark_sweep) {}
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001324
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -07001325 ALWAYS_INLINE void operator()(mirror::Object* obj,
1326 MemberOffset offset,
1327 bool is_static ATTRIBUTE_UNUSED) const
1328 REQUIRES(Locks::heap_bitmap_lock_)
1329 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001330 if (kCheckLocks) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001331 Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
1332 Locks::heap_bitmap_lock_->AssertExclusiveHeld(Thread::Current());
1333 }
Hiroshi Yamauchieb2baaf2015-05-13 21:14:22 -07001334 mark_sweep_->MarkObject(obj->GetFieldObject<mirror::Object>(offset), obj, offset);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001335 }
1336
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001337 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -07001338 REQUIRES(Locks::heap_bitmap_lock_)
1339 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001340 if (!root->IsNull()) {
1341 VisitRoot(root);
1342 }
1343 }
1344
1345 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -07001346 REQUIRES(Locks::heap_bitmap_lock_)
1347 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001348 if (kCheckLocks) {
1349 Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
1350 Locks::heap_bitmap_lock_->AssertExclusiveHeld(Thread::Current());
1351 }
1352 mark_sweep_->MarkObject(root->AsMirrorPtr());
1353 }
1354
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001355 private:
1356 MarkSweep* const mark_sweep_;
1357};
1358
Carl Shapiro69759ea2011-07-21 18:13:35 -07001359// Scans an object reference. Determines the type of the reference
1360// and dispatches to a specialized scanning routine.
Mathieu Chartier97509952015-07-13 14:35:43 -07001361void MarkSweep::ScanObject(mirror::Object* obj) {
1362 MarkVisitor mark_visitor(this);
Mathieu Chartier407f7022014-02-18 14:37:05 -08001363 DelayReferenceReferentVisitor ref_visitor(this);
1364 ScanObjectVisit(obj, mark_visitor, ref_visitor);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001365}
1366
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001367void MarkSweep::ProcessMarkStackParallel(size_t thread_count) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001368 Thread* self = Thread::Current();
1369 ThreadPool* thread_pool = GetHeap()->GetThreadPool();
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001370 const size_t chunk_size = std::min(mark_stack_->Size() / thread_count + 1,
1371 static_cast<size_t>(MarkStackTask<false>::kMaxSize));
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001372 CHECK_GT(chunk_size, 0U);
1373 // Split the current mark stack up into work tasks.
Mathieu Chartiercb535da2015-01-23 13:50:03 -08001374 for (auto* it = mark_stack_->Begin(), *end = mark_stack_->End(); it < end; ) {
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001375 const size_t delta = std::min(static_cast<size_t>(end - it), chunk_size);
Mathieu Chartier0e54cd02014-03-20 12:41:23 -07001376 thread_pool->AddTask(self, new MarkStackTask<false>(thread_pool, this, delta, it));
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001377 it += delta;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001378 }
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001379 thread_pool->SetMaxActiveWorkers(thread_count - 1);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001380 thread_pool->StartWorkers(self);
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001381 thread_pool->Wait(self, true, true);
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001382 thread_pool->StopWorkers(self);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001383 mark_stack_->Reset();
Ian Rogers3e5cf302014-05-20 16:40:37 -07001384 CHECK_EQ(work_chunks_created_.LoadSequentiallyConsistent(),
1385 work_chunks_deleted_.LoadSequentiallyConsistent())
1386 << " some of the work chunks were leaked";
Carl Shapiro69759ea2011-07-21 18:13:35 -07001387}
1388
Ian Rogers5d76c432011-10-31 21:42:49 -07001389// Scan anything that's on the mark stack.
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001390void MarkSweep::ProcessMarkStack(bool paused) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001391 TimingLogger::ScopedTiming t(paused ? "(Paused)ProcessMarkStack" : __FUNCTION__, GetTimings());
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001392 size_t thread_count = GetThreadCount(paused);
1393 if (kParallelProcessMarkStack && thread_count > 1 &&
1394 mark_stack_->Size() >= kMinimumParallelMarkStackSize) {
1395 ProcessMarkStackParallel(thread_count);
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001396 } else {
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001397 // TODO: Tune this.
1398 static const size_t kFifoSize = 4;
Mathieu Chartier97509952015-07-13 14:35:43 -07001399 BoundedFifoPowerOfTwo<mirror::Object*, kFifoSize> prefetch_fifo;
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001400 for (;;) {
Mathieu Chartier97509952015-07-13 14:35:43 -07001401 mirror::Object* obj = nullptr;
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001402 if (kUseMarkStackPrefetch) {
1403 while (!mark_stack_->IsEmpty() && prefetch_fifo.size() < kFifoSize) {
Mathieu Chartier97509952015-07-13 14:35:43 -07001404 mirror::Object* mark_stack_obj = mark_stack_->PopBack();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001405 DCHECK(mark_stack_obj != nullptr);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001406 __builtin_prefetch(mark_stack_obj);
1407 prefetch_fifo.push_back(mark_stack_obj);
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001408 }
1409 if (prefetch_fifo.empty()) {
1410 break;
1411 }
1412 obj = prefetch_fifo.front();
1413 prefetch_fifo.pop_front();
1414 } else {
1415 if (mark_stack_->IsEmpty()) {
1416 break;
1417 }
1418 obj = mark_stack_->PopBack();
1419 }
Mathieu Chartier4aeec172014-03-27 16:09:46 -07001420 DCHECK(obj != nullptr);
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001421 ScanObject(obj);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001422 }
1423 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001424}
1425
Mathieu Chartier97509952015-07-13 14:35:43 -07001426inline mirror::Object* MarkSweep::IsMarked(mirror::Object* object) {
Mathieu Chartier763a31e2015-11-16 16:05:55 -08001427 if (immune_spaces_.IsInImmuneRegion(object)) {
Mathieu Chartier97509952015-07-13 14:35:43 -07001428 return object;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001429 }
Mathieu Chartier0e54cd02014-03-20 12:41:23 -07001430 if (current_space_bitmap_->HasAddress(object)) {
Mathieu Chartier97509952015-07-13 14:35:43 -07001431 return current_space_bitmap_->Test(object) ? object : nullptr;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001432 }
Mathieu Chartier97509952015-07-13 14:35:43 -07001433 return mark_bitmap_->Test(object) ? object : nullptr;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001434}
1435
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001436void MarkSweep::FinishPhase() {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001437 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001438 if (kCountScannedTypes) {
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07001439 VLOG(gc)
1440 << "MarkSweep scanned"
1441 << " no reference objects=" << no_reference_class_count_.LoadRelaxed()
1442 << " normal objects=" << normal_count_.LoadRelaxed()
1443 << " classes=" << class_count_.LoadRelaxed()
1444 << " object arrays=" << object_array_count_.LoadRelaxed()
1445 << " references=" << reference_count_.LoadRelaxed()
1446 << " other=" << other_count_.LoadRelaxed();
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001447 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001448 if (kCountTasks) {
Ian Rogers3e5cf302014-05-20 16:40:37 -07001449 VLOG(gc) << "Total number of work chunks allocated: " << work_chunks_created_.LoadRelaxed();
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001450 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001451 if (kMeasureOverhead) {
Ian Rogers3e5cf302014-05-20 16:40:37 -07001452 VLOG(gc) << "Overhead time " << PrettyDuration(overhead_time_.LoadRelaxed());
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001453 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001454 if (kProfileLargeObjects) {
Ian Rogers3e5cf302014-05-20 16:40:37 -07001455 VLOG(gc) << "Large objects tested " << large_object_test_.LoadRelaxed()
1456 << " marked " << large_object_mark_.LoadRelaxed();
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001457 }
Mathieu Chartier0e54cd02014-03-20 12:41:23 -07001458 if (kCountMarkedObjects) {
Ian Rogers3e5cf302014-05-20 16:40:37 -07001459 VLOG(gc) << "Marked: null=" << mark_null_count_.LoadRelaxed()
1460 << " immune=" << mark_immune_count_.LoadRelaxed()
1461 << " fastpath=" << mark_fastpath_count_.LoadRelaxed()
1462 << " slowpath=" << mark_slowpath_count_.LoadRelaxed();
Mathieu Chartier0e54cd02014-03-20 12:41:23 -07001463 }
Mathieu Chartier4aeec172014-03-27 16:09:46 -07001464 CHECK(mark_stack_->IsEmpty()); // Ensure that the mark stack is empty.
Mathieu Chartier5301cd22012-05-31 12:11:36 -07001465 mark_stack_->Reset();
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -08001466 Thread* const self = Thread::Current();
1467 ReaderMutexLock mu(self, *Locks::mutator_lock_);
1468 WriterMutexLock mu2(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier4aeec172014-03-27 16:09:46 -07001469 heap_->ClearMarkedObjects();
Carl Shapiro69759ea2011-07-21 18:13:35 -07001470}
1471
Hiroshi Yamauchic93c5302014-03-20 16:15:37 -07001472void MarkSweep::RevokeAllThreadLocalBuffers() {
1473 if (kRevokeRosAllocThreadLocalBuffersAtCheckpoint && IsConcurrent()) {
1474 // If concurrent, rosalloc thread-local buffers are revoked at the
1475 // thread checkpoint. Bump pointer space thread-local buffers must
1476 // not be in use.
1477 GetHeap()->AssertAllBumpPointerSpaceThreadLocalBuffersAreRevoked();
1478 } else {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001479 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Hiroshi Yamauchic93c5302014-03-20 16:15:37 -07001480 GetHeap()->RevokeAllThreadLocalBuffers();
Hiroshi Yamauchic93c5302014-03-20 16:15:37 -07001481 }
1482}
1483
Ian Rogers1d54e732013-05-02 21:10:01 -07001484} // namespace collector
1485} // namespace gc
Carl Shapiro69759ea2011-07-21 18:13:35 -07001486} // namespace art