blob: ad3dd33303a0cc1ebf748a4f23cbeb0a8debd052 [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"
Andreas Gampe542451c2016-07-26 09:02:02 -070026#include "base/enums.h"
Elliott Hughes07ed66b2012-12-12 18:34:25 -080027#include "base/logging.h"
Elliott Hughes76160052012-12-12 16:31:20 -080028#include "base/macros.h"
Ian Rogers693ff612013-02-01 10:56:12 -080029#include "base/mutex-inl.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080030#include "base/systrace.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010031#include "base/time_utils.h"
Sameer Abu Asala8439542013-02-14 16:06:42 -080032#include "base/timing_logger.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070033#include "gc/accounting/card_table-inl.h"
Mathieu Chartier4aeec172014-03-27 16:09:46 -070034#include "gc/accounting/heap_bitmap-inl.h"
Mathieu Chartier11409ae2013-09-23 11:49:36 -070035#include "gc/accounting/mod_union_table.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070036#include "gc/accounting/space_bitmap-inl.h"
37#include "gc/heap.h"
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -070038#include "gc/reference_processor.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070039#include "gc/space/large_object_space.h"
40#include "gc/space/space-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080041#include "mark_sweep-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080042#include "mirror/object-inl.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070043#include "runtime.h"
Mathieu Chartier4aeec172014-03-27 16:09:46 -070044#include "scoped_thread_state_change.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070045#include "thread-inl.h"
Mathieu Chartier6f1c9492012-10-15 12:08:41 -070046#include "thread_list.h"
Carl Shapiro69759ea2011-07-21 18:13:35 -070047
Carl Shapiro69759ea2011-07-21 18:13:35 -070048namespace art {
Ian Rogers1d54e732013-05-02 21:10:01 -070049namespace gc {
50namespace collector {
Carl Shapiro69759ea2011-07-21 18:13:35 -070051
Mathieu Chartier02b6a782012-10-26 13:51:26 -070052// Performance options.
Mathieu Chartiereb7bbad2014-02-25 15:52:46 -080053static constexpr bool kUseRecursiveMark = false;
54static constexpr bool kUseMarkStackPrefetch = true;
55static constexpr size_t kSweepArrayChunkFreeSize = 1024;
56static constexpr bool kPreCleanCards = true;
Mathieu Chartier94c32c52013-08-09 11:14:04 -070057
58// Parallelism options.
Mathieu Chartiereb7bbad2014-02-25 15:52:46 -080059static constexpr bool kParallelCardScan = true;
60static constexpr bool kParallelRecursiveMark = true;
Mathieu Chartier94c32c52013-08-09 11:14:04 -070061// Don't attempt to parallelize mark stack processing unless the mark stack is at least n
62// elements. This is temporary until we reduce the overhead caused by allocating tasks, etc.. Not
63// having this can add overhead in ProcessReferences since we may end up doing many calls of
64// ProcessMarkStack with very small mark stacks.
Mathieu Chartiereb7bbad2014-02-25 15:52:46 -080065static constexpr size_t kMinimumParallelMarkStackSize = 128;
66static constexpr bool kParallelProcessMarkStack = true;
Mathieu Chartier858f1c52012-10-17 17:45:55 -070067
Mathieu Chartier02b6a782012-10-26 13:51:26 -070068// Profiling and information flags.
Mathieu Chartiereb7bbad2014-02-25 15:52:46 -080069static constexpr bool kProfileLargeObjects = false;
70static constexpr bool kMeasureOverhead = false;
71static constexpr bool kCountTasks = false;
Mathieu Chartier0e54cd02014-03-20 12:41:23 -070072static constexpr bool kCountMarkedObjects = false;
Mathieu Chartier94c32c52013-08-09 11:14:04 -070073
74// Turn off kCheckLocks when profiling the GC since it slows the GC down by up to 40%.
Mathieu Chartiereb7bbad2014-02-25 15:52:46 -080075static constexpr bool kCheckLocks = kDebugLocking;
Mathieu Chartier7bf9f192014-04-04 11:09:41 -070076static constexpr bool kVerifyRootsMarked = kIsDebugBuild;
Mathieu Chartier02b6a782012-10-26 13:51:26 -070077
Hiroshi Yamauchic93c5302014-03-20 16:15:37 -070078// If true, revoke the rosalloc thread-local buffers at the
79// checkpoint, as opposed to during the pause.
80static constexpr bool kRevokeRosAllocThreadLocalBuffersAtCheckpoint = true;
81
Mathieu Chartier2b82db42012-11-14 17:29:05 -080082void MarkSweep::BindBitmaps() {
Mathieu Chartierf5997b42014-06-20 10:37:54 -070083 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Mathieu Chartier2b82db42012-11-14 17:29:05 -080084 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -080085 // Mark all of the spaces we never collect as immune.
Mathieu Chartier94c32c52013-08-09 11:14:04 -070086 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Ian Rogers1d54e732013-05-02 21:10:01 -070087 if (space->GetGcRetentionPolicy() == space::kGcRetentionPolicyNeverCollect) {
Mathieu Chartier763a31e2015-11-16 16:05:55 -080088 immune_spaces_.AddSpace(space);
Mathieu Chartier2b82db42012-11-14 17:29:05 -080089 }
90 }
91}
92
Ian Rogers1d54e732013-05-02 21:10:01 -070093MarkSweep::MarkSweep(Heap* heap, bool is_concurrent, const std::string& name_prefix)
94 : GarbageCollector(heap,
Mathieu Chartier590fee92013-09-13 13:46:47 -070095 name_prefix +
Ian Rogers1d54e732013-05-02 21:10:01 -070096 (is_concurrent ? "concurrent mark sweep": "mark sweep")),
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -070097 current_space_bitmap_(nullptr),
98 mark_bitmap_(nullptr),
99 mark_stack_(nullptr),
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800100 gc_barrier_(new Barrier(0)),
Mathieu Chartier958291c2013-08-27 18:14:55 -0700101 mark_stack_lock_("mark sweep mark stack lock", kMarkSweepMarkStackLock),
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -0700102 is_concurrent_(is_concurrent),
103 live_stack_freeze_size_(0) {
Hiroshi Yamauchibbdc5bc2014-05-28 14:04:59 -0700104 std::string error_msg;
105 MemMap* mem_map = MemMap::MapAnonymous(
106 "mark sweep sweep array free buffer", nullptr,
107 RoundUp(kSweepArrayChunkFreeSize * sizeof(mirror::Object*), kPageSize),
Vladimir Marko5c42c292015-02-25 12:02:49 +0000108 PROT_READ | PROT_WRITE, false, false, &error_msg);
Hiroshi Yamauchibbdc5bc2014-05-28 14:04:59 -0700109 CHECK(mem_map != nullptr) << "Couldn't allocate sweep array free buffer: " << error_msg;
110 sweep_array_free_buffer_mem_map_.reset(mem_map);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800111}
112
113void MarkSweep::InitializePhase() {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700114 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700115 mark_stack_ = heap_->GetMarkStack();
Mathieu Chartiere53225c2013-08-19 10:59:11 -0700116 DCHECK(mark_stack_ != nullptr);
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800117 immune_spaces_.Reset();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700118 no_reference_class_count_.StoreRelaxed(0);
119 normal_count_.StoreRelaxed(0);
Ian Rogers3e5cf302014-05-20 16:40:37 -0700120 class_count_.StoreRelaxed(0);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700121 object_array_count_.StoreRelaxed(0);
Ian Rogers3e5cf302014-05-20 16:40:37 -0700122 other_count_.StoreRelaxed(0);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700123 reference_count_.StoreRelaxed(0);
Ian Rogers3e5cf302014-05-20 16:40:37 -0700124 large_object_test_.StoreRelaxed(0);
125 large_object_mark_.StoreRelaxed(0);
126 overhead_time_ .StoreRelaxed(0);
127 work_chunks_created_.StoreRelaxed(0);
128 work_chunks_deleted_.StoreRelaxed(0);
Ian Rogers3e5cf302014-05-20 16:40:37 -0700129 mark_null_count_.StoreRelaxed(0);
130 mark_immune_count_.StoreRelaxed(0);
131 mark_fastpath_count_.StoreRelaxed(0);
132 mark_slowpath_count_.StoreRelaxed(0);
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700133 {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700134 // TODO: I don't think we should need heap bitmap lock to Get the mark bitmap.
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700135 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
136 mark_bitmap_ = heap_->GetMarkBitmap();
137 }
Mathieu Chartier10fb83a2014-06-15 15:15:43 -0700138 if (!GetCurrentIteration()->GetClearSoftReferences()) {
Hiroshi Yamauchidf386c52014-04-08 16:21:52 -0700139 // Always clear soft references if a non-sticky collection.
Mathieu Chartier10fb83a2014-06-15 15:15:43 -0700140 GetCurrentIteration()->SetClearSoftReferences(GetGcType() != collector::kGcTypeSticky);
Hiroshi Yamauchidf386c52014-04-08 16:21:52 -0700141 }
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700142}
143
144void MarkSweep::RunPhases() {
145 Thread* self = Thread::Current();
146 InitializePhase();
147 Locks::mutator_lock_->AssertNotHeld(self);
148 if (IsConcurrent()) {
149 GetHeap()->PreGcVerification(this);
150 {
151 ReaderMutexLock mu(self, *Locks::mutator_lock_);
152 MarkingPhase();
153 }
154 ScopedPause pause(this);
155 GetHeap()->PrePauseRosAllocVerification(this);
156 PausePhase();
157 RevokeAllThreadLocalBuffers();
158 } else {
159 ScopedPause pause(this);
160 GetHeap()->PreGcVerificationPaused(this);
161 MarkingPhase();
162 GetHeap()->PrePauseRosAllocVerification(this);
163 PausePhase();
164 RevokeAllThreadLocalBuffers();
165 }
166 {
167 // Sweeping always done concurrently, even for non concurrent mark sweep.
168 ReaderMutexLock mu(self, *Locks::mutator_lock_);
169 ReclaimPhase();
170 }
171 GetHeap()->PostGcVerification(this);
172 FinishPhase();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800173}
174
175void MarkSweep::ProcessReferences(Thread* self) {
Mathieu Chartier8e56c7e2012-11-20 13:25:50 -0800176 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -0700177 GetHeap()->GetReferenceProcessor()->ProcessReferences(
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -0700178 true,
179 GetTimings(),
180 GetCurrentIteration()->GetClearSoftReferences(),
181 this);
Mathieu Chartier1ad27842014-03-19 17:08:17 -0700182}
183
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -0700184void MarkSweep::PausePhase() {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700185 TimingLogger::ScopedTiming t("(Paused)PausePhase", GetTimings());
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800186 Thread* self = Thread::Current();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800187 Locks::mutator_lock_->AssertExclusiveHeld(self);
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -0700188 if (IsConcurrent()) {
189 // Handle the dirty objects if we are a concurrent GC.
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800190 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800191 // Re-mark root set.
192 ReMarkRoots();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800193 // Scan dirty objects, this is only required if we are not doing concurrent GC.
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700194 RecursiveMarkDirtyObjects(true, accounting::CardTable::kCardDirty);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800195 }
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -0700196 {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700197 TimingLogger::ScopedTiming t2("SwapStacks", GetTimings());
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800198 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartiera4f6af92015-08-11 17:35:25 -0700199 heap_->SwapStacks();
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -0700200 live_stack_freeze_size_ = heap_->GetLiveStack()->Size();
201 // Need to revoke all the thread local allocation stacks since we just swapped the allocation
202 // stacks and don't want anybody to allocate into the live stack.
Mathieu Chartierc22c59e2014-02-24 15:16:06 -0800203 RevokeAllThreadLocalAllocationStacks(self);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800204 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700205 heap_->PreSweepingGcVerification(this);
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700206 // Disallow new system weaks to prevent a race which occurs when someone adds a new system
207 // weak before we sweep them. Since this new system weak may not be marked, the GC may
208 // incorrectly sweep it. This also fixes a race where interning may attempt to return a strong
209 // reference to a string that is about to be swept.
210 Runtime::Current()->DisallowNewSystemWeaks();
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -0700211 // Enable the reference processing slow path, needs to be done with mutators paused since there
212 // is no lock in the GetReferent fast path.
213 GetHeap()->GetReferenceProcessor()->EnableSlowPath();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800214}
215
Mathieu Chartierdda54f52014-02-24 09:58:40 -0800216void MarkSweep::PreCleanCards() {
217 // Don't do this for non concurrent GCs since they don't have any dirty cards.
218 if (kPreCleanCards && IsConcurrent()) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700219 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Mathieu Chartierdda54f52014-02-24 09:58:40 -0800220 Thread* self = Thread::Current();
221 CHECK(!Locks::mutator_lock_->IsExclusiveHeld(self));
222 // Process dirty cards and add dirty cards to mod union tables, also ages cards.
Lei Li4add3b42015-01-15 11:55:26 +0800223 heap_->ProcessCards(GetTimings(), false, true, false);
Mathieu Chartiereb7bbad2014-02-25 15:52:46 -0800224 // The checkpoint root marking is required to avoid a race condition which occurs if the
225 // following happens during a reference write:
226 // 1. mutator dirties the card (write barrier)
227 // 2. GC ages the card (the above ProcessCards call)
228 // 3. GC scans the object (the RecursiveMarkDirtyObjects call below)
229 // 4. mutator writes the value (corresponding to the write barrier in 1.)
230 // This causes the GC to age the card but not necessarily mark the reference which the mutator
231 // wrote into the object stored in the card.
232 // Having the checkpoint fixes this issue since it ensures that the card mark and the
233 // reference write are visible to the GC before the card is scanned (this is due to locks being
234 // acquired / released in the checkpoint code).
235 // The other roots are also marked to help reduce the pause.
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -0700236 MarkRootsCheckpoint(self, false);
Mathieu Chartierdda54f52014-02-24 09:58:40 -0800237 MarkNonThreadRoots();
Mathieu Chartier893263b2014-03-04 11:07:42 -0800238 MarkConcurrentRoots(
239 static_cast<VisitRootFlags>(kVisitRootFlagClearRootLog | kVisitRootFlagNewRoots));
Mathieu Chartierdda54f52014-02-24 09:58:40 -0800240 // Process the newly aged cards.
241 RecursiveMarkDirtyObjects(false, accounting::CardTable::kCardDirty - 1);
242 // TODO: Empty allocation stack to reduce the number of objects we need to test / mark as live
243 // in the next GC.
244 }
245}
246
Mathieu Chartierc22c59e2014-02-24 15:16:06 -0800247void MarkSweep::RevokeAllThreadLocalAllocationStacks(Thread* self) {
248 if (kUseThreadLocalAllocationStack) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700249 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Mathieu Chartierc22c59e2014-02-24 15:16:06 -0800250 Locks::mutator_lock_->AssertExclusiveHeld(self);
251 heap_->RevokeAllThreadLocalAllocationStacks(self);
252 }
253}
254
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800255void MarkSweep::MarkingPhase() {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700256 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800257 Thread* self = Thread::Current();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800258 BindBitmaps();
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700259 FindDefaultSpaceBitmap();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800260 // Process dirty cards and add dirty cards to mod union tables.
Lei Li4add3b42015-01-15 11:55:26 +0800261 // If the GC type is non sticky, then we just clear the cards instead of ageing them.
262 heap_->ProcessCards(GetTimings(), false, true, GetGcType() != kGcTypeSticky);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800263 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier893263b2014-03-04 11:07:42 -0800264 MarkRoots(self);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800265 MarkReachableObjects();
Mathieu Chartierdda54f52014-02-24 09:58:40 -0800266 // Pre-clean dirtied cards to reduce pauses.
267 PreCleanCards();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800268}
269
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700270class MarkSweep::ScanObjectVisitor {
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800271 public:
272 explicit ScanObjectVisitor(MarkSweep* const mark_sweep) ALWAYS_INLINE
273 : mark_sweep_(mark_sweep) {}
274
275 void operator()(mirror::Object* obj) const
276 ALWAYS_INLINE
277 REQUIRES(Locks::heap_bitmap_lock_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700278 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800279 if (kCheckLocks) {
280 Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
281 Locks::heap_bitmap_lock_->AssertExclusiveHeld(Thread::Current());
282 }
283 mark_sweep_->ScanObject(obj);
284 }
285
286 private:
287 MarkSweep* const mark_sweep_;
288};
289
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700290void MarkSweep::UpdateAndMarkModUnion() {
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800291 for (const auto& space : immune_spaces_.GetSpaces()) {
292 const char* name = space->IsZygoteSpace()
293 ? "UpdateAndMarkZygoteModUnionTable"
294 : "UpdateAndMarkImageModUnionTable";
295 DCHECK(space->IsZygoteSpace() || space->IsImageSpace()) << *space;
296 TimingLogger::ScopedTiming t(name, GetTimings());
297 accounting::ModUnionTable* mod_union_table = heap_->FindModUnionTableFromSpace(space);
298 if (mod_union_table != nullptr) {
Mathieu Chartier97509952015-07-13 14:35:43 -0700299 mod_union_table->UpdateAndMarkReferences(this);
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800300 } else {
301 // No mod-union table, scan all the live bits. This can only occur for app images.
302 space->GetLiveBitmap()->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()),
303 reinterpret_cast<uintptr_t>(space->End()),
304 ScanObjectVisitor(this));
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700305 }
306 }
307}
308
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800309void MarkSweep::MarkReachableObjects() {
Mathieu Chartier4aeec172014-03-27 16:09:46 -0700310 UpdateAndMarkModUnion();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800311 // Recursively mark all the non-image bits set in the mark bitmap.
312 RecursiveMark();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800313}
314
315void MarkSweep::ReclaimPhase() {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700316 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Mathieu Chartier951ec2c2015-09-22 08:50:05 -0700317 Thread* const self = Thread::Current();
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -0700318 // Process the references concurrently.
319 ProcessReferences(self);
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -0700320 SweepSystemWeaks(self);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -0700321 Runtime* const runtime = Runtime::Current();
322 runtime->AllowNewSystemWeaks();
323 // Clean up class loaders after system weaks are swept since that is how we know if class
324 // unloading occurred.
325 runtime->GetClassLinker()->CleanupClassLoaders();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800326 {
327 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -0700328 GetHeap()->RecordFreeRevoke();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800329 // Reclaim unmarked objects.
Ian Rogers1d54e732013-05-02 21:10:01 -0700330 Sweep(false);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800331 // Swap the live and mark bitmaps for each space which we modified space. This is an
332 // optimization that enables us to not clear live bits inside of the sweep. Only swaps unbound
333 // bitmaps.
334 SwapBitmaps();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800335 // Unbind the live and mark bitmaps.
Mathieu Chartiera1602f22014-01-13 17:19:19 -0800336 GetHeap()->UnBindBitmaps();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800337 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800338}
339
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700340void MarkSweep::FindDefaultSpaceBitmap() {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700341 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Mathieu Chartier02e25112013-08-14 16:14:24 -0700342 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -0700343 accounting::ContinuousSpaceBitmap* bitmap = space->GetMarkBitmap();
Mathieu Chartierbbd695c2014-04-16 09:48:48 -0700344 // We want to have the main space instead of non moving if possible.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700345 if (bitmap != nullptr &&
346 space->GetGcRetentionPolicy() == space::kGcRetentionPolicyAlwaysCollect) {
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700347 current_space_bitmap_ = bitmap;
Mathieu Chartierbbd695c2014-04-16 09:48:48 -0700348 // If we are not the non moving space exit the loop early since this will be good enough.
349 if (space != heap_->GetNonMovingSpace()) {
350 break;
351 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700352 }
353 }
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -0700354 CHECK(current_space_bitmap_ != nullptr) << "Could not find a default mark bitmap\n"
355 << heap_->DumpSpaces();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700356}
357
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800358void MarkSweep::ExpandMarkStack() {
Mathieu Chartierba311b42013-08-27 13:02:30 -0700359 ResizeMarkStack(mark_stack_->Capacity() * 2);
360}
361
362void MarkSweep::ResizeMarkStack(size_t new_size) {
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800363 // Rare case, no need to have Thread::Current be a parameter.
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800364 if (UNLIKELY(mark_stack_->Size() < mark_stack_->Capacity())) {
365 // Someone else acquired the lock and expanded the mark stack before us.
366 return;
367 }
Mathieu Chartier97509952015-07-13 14:35:43 -0700368 std::vector<StackReference<mirror::Object>> temp(mark_stack_->Begin(), mark_stack_->End());
Mathieu Chartierba311b42013-08-27 13:02:30 -0700369 CHECK_LE(mark_stack_->Size(), new_size);
370 mark_stack_->Resize(new_size);
Mathieu Chartiercb535da2015-01-23 13:50:03 -0800371 for (auto& obj : temp) {
372 mark_stack_->PushBack(obj.AsMirrorPtr());
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800373 }
374}
375
Mathieu Chartiere48a1692015-07-15 19:58:45 -0700376mirror::Object* MarkSweep::MarkObject(mirror::Object* obj) {
377 MarkObject(obj, nullptr, MemberOffset(0));
378 return obj;
379}
380
Mathieu Chartier97509952015-07-13 14:35:43 -0700381inline void MarkSweep::MarkObjectNonNullParallel(mirror::Object* obj) {
Mathieu Chartierbbd695c2014-04-16 09:48:48 -0700382 DCHECK(obj != nullptr);
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800383 if (MarkObjectParallel(obj)) {
Mathieu Chartierba311b42013-08-27 13:02:30 -0700384 MutexLock mu(Thread::Current(), mark_stack_lock_);
385 if (UNLIKELY(mark_stack_->Size() >= mark_stack_->Capacity())) {
Mathieu Chartier184e3222013-08-03 14:02:57 -0700386 ExpandMarkStack();
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800387 }
Mathieu Chartierba311b42013-08-27 13:02:30 -0700388 // The object must be pushed on to the mark stack.
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700389 mark_stack_->PushBack(obj);
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800390 }
391}
392
Mathieu Chartier97509952015-07-13 14:35:43 -0700393bool MarkSweep::IsMarkedHeapReference(mirror::HeapReference<mirror::Object>* ref) {
394 return IsMarked(ref->AsMirrorPtr());
Mathieu Chartier308351a2014-06-15 12:39:02 -0700395}
396
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700397class MarkSweep::MarkObjectSlowPath {
Mathieu Chartierbbd695c2014-04-16 09:48:48 -0700398 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700399 explicit MarkObjectSlowPath(MarkSweep* mark_sweep,
400 mirror::Object* holder = nullptr,
401 MemberOffset offset = MemberOffset(0))
402 : mark_sweep_(mark_sweep),
403 holder_(holder),
404 offset_(offset) {}
Mathieu Chartierbbd695c2014-04-16 09:48:48 -0700405
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700406 void operator()(const mirror::Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartierbbd695c2014-04-16 09:48:48 -0700407 if (kProfileLargeObjects) {
408 // TODO: Differentiate between marking and testing somehow.
409 ++mark_sweep_->large_object_test_;
410 ++mark_sweep_->large_object_mark_;
411 }
412 space::LargeObjectSpace* large_object_space = mark_sweep_->GetHeap()->GetLargeObjectsSpace();
Mathieu Chartiera17288e2014-05-08 17:53:19 -0700413 if (UNLIKELY(obj == nullptr || !IsAligned<kPageSize>(obj) ||
Mathieu Chartier2dbe6272014-09-16 10:43:23 -0700414 (kIsDebugBuild && large_object_space != nullptr &&
415 !large_object_space->Contains(obj)))) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700416 LOG(FATAL_WITHOUT_ABORT) << "Tried to mark " << obj << " not contained by any spaces";
Hiroshi Yamauchieb2baaf2015-05-13 21:14:22 -0700417 if (holder_ != nullptr) {
Hiroshi Yamauchid0c84122015-05-15 15:23:30 -0700418 size_t holder_size = holder_->SizeOf();
Hiroshi Yamauchieb2baaf2015-05-13 21:14:22 -0700419 ArtField* field = holder_->FindFieldByOffset(offset_);
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700420 LOG(FATAL_WITHOUT_ABORT) << "Field info: "
Hiroshi Yamauchid0c84122015-05-15 15:23:30 -0700421 << " holder=" << holder_
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -0700422 << " holder is "
423 << (mark_sweep_->GetHeap()->IsLiveObjectLocked(holder_)
424 ? "alive" : "dead")
Hiroshi Yamauchid0c84122015-05-15 15:23:30 -0700425 << " holder_size=" << holder_size
Hiroshi Yamauchieb2baaf2015-05-13 21:14:22 -0700426 << " holder_type=" << PrettyTypeOf(holder_)
427 << " offset=" << offset_.Uint32Value()
Hiroshi Yamauchid0c84122015-05-15 15:23:30 -0700428 << " field=" << (field != nullptr ? field->GetName() : "nullptr")
429 << " field_type="
430 << (field != nullptr ? field->GetTypeDescriptor() : "")
431 << " first_ref_field_offset="
432 << (holder_->IsClass()
Mathieu Chartiere401d142015-04-22 13:56:20 -0700433 ? holder_->AsClass()->GetFirstReferenceStaticFieldOffset(
Andreas Gampe542451c2016-07-26 09:02:02 -0700434 kRuntimePointerSize)
Hiroshi Yamauchid0c84122015-05-15 15:23:30 -0700435 : holder_->GetClass()->GetFirstReferenceInstanceFieldOffset())
436 << " num_of_ref_fields="
437 << (holder_->IsClass()
438 ? holder_->AsClass()->NumReferenceStaticFields()
Mathieu Chartier9826c3e2016-08-17 10:28:48 -0700439 : holder_->GetClass()->NumReferenceInstanceFields());
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -0700440 // Print the memory content of the holder.
441 for (size_t i = 0; i < holder_size / sizeof(uint32_t); ++i) {
442 uint32_t* p = reinterpret_cast<uint32_t*>(holder_);
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700443 LOG(FATAL_WITHOUT_ABORT) << &p[i] << ": " << "holder+" << (i * sizeof(uint32_t)) << " = "
Mathieu Chartier5bb4b0b2016-08-17 22:43:52 +0000444 << std::hex << p[i];
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -0700445 }
Hiroshi Yamauchieb2baaf2015-05-13 21:14:22 -0700446 }
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700447 PrintFileToLog("/proc/self/maps", LogSeverity::FATAL_WITHOUT_ABORT);
448 MemMap::DumpMaps(LOG_STREAM(FATAL_WITHOUT_ABORT), true);
449 LOG(FATAL_WITHOUT_ABORT) << "Attempting see if it's a bad thread root";
Mathieu Chartierf8a86b92016-06-14 17:08:47 -0700450 mark_sweep_->VerifySuspendedThreadRoots();
Mathieu Chartierbbd695c2014-04-16 09:48:48 -0700451 LOG(FATAL) << "Can't mark invalid object";
452 }
453 }
454
455 private:
456 MarkSweep* const mark_sweep_;
Hiroshi Yamauchieb2baaf2015-05-13 21:14:22 -0700457 mirror::Object* const holder_;
458 MemberOffset offset_;
Mathieu Chartierbbd695c2014-04-16 09:48:48 -0700459};
460
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -0700461inline void MarkSweep::MarkObjectNonNull(mirror::Object* obj,
462 mirror::Object* holder,
Mathieu Chartier97509952015-07-13 14:35:43 -0700463 MemberOffset offset) {
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700464 DCHECK(obj != nullptr);
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -0700465 if (kUseBakerOrBrooksReadBarrier) {
466 // Verify all the objects have the correct pointer installed.
467 obj->AssertReadBarrierPointer();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800468 }
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800469 if (immune_spaces_.IsInImmuneRegion(obj)) {
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700470 if (kCountMarkedObjects) {
471 ++mark_immune_count_;
472 }
Mathieu Chartierbbd695c2014-04-16 09:48:48 -0700473 DCHECK(mark_bitmap_->Test(obj));
474 } else if (LIKELY(current_space_bitmap_->HasAddress(obj))) {
475 if (kCountMarkedObjects) {
476 ++mark_fastpath_count_;
477 }
478 if (UNLIKELY(!current_space_bitmap_->Set(obj))) {
479 PushOnMarkStack(obj); // This object was not previously marked.
480 }
481 } else {
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700482 if (kCountMarkedObjects) {
483 ++mark_slowpath_count_;
484 }
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700485 MarkObjectSlowPath visitor(this, holder, offset);
Mathieu Chartierbbd695c2014-04-16 09:48:48 -0700486 // TODO: We already know that the object is not in the current_space_bitmap_ but MarkBitmap::Set
487 // will check again.
488 if (!mark_bitmap_->Set(obj, visitor)) {
489 PushOnMarkStack(obj); // Was not already marked, push.
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700490 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700491 }
492}
493
Mathieu Chartier97509952015-07-13 14:35:43 -0700494inline void MarkSweep::PushOnMarkStack(mirror::Object* obj) {
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700495 if (UNLIKELY(mark_stack_->Size() >= mark_stack_->Capacity())) {
496 // Lock is not needed but is here anyways to please annotalysis.
497 MutexLock mu(Thread::Current(), mark_stack_lock_);
498 ExpandMarkStack();
499 }
500 // The object must be pushed on to the mark stack.
501 mark_stack_->PushBack(obj);
502}
503
Mathieu Chartier97509952015-07-13 14:35:43 -0700504inline bool MarkSweep::MarkObjectParallel(mirror::Object* obj) {
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700505 DCHECK(obj != nullptr);
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -0700506 if (kUseBakerOrBrooksReadBarrier) {
507 // Verify all the objects have the correct pointer installed.
508 obj->AssertReadBarrierPointer();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800509 }
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800510 if (immune_spaces_.IsInImmuneRegion(obj)) {
Mathieu Chartier97509952015-07-13 14:35:43 -0700511 DCHECK(IsMarked(obj) != nullptr);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700512 return false;
513 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700514 // Try to take advantage of locality of references within a space, failing this find the space
515 // the hard way.
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -0700516 accounting::ContinuousSpaceBitmap* object_bitmap = current_space_bitmap_;
Mathieu Chartierbbd695c2014-04-16 09:48:48 -0700517 if (LIKELY(object_bitmap->HasAddress(obj))) {
518 return !object_bitmap->AtomicTestAndSet(obj);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700519 }
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700520 MarkObjectSlowPath visitor(this);
Mathieu Chartierbbd695c2014-04-16 09:48:48 -0700521 return !mark_bitmap_->AtomicTestAndSet(obj, visitor);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700522}
523
Mathieu Chartier97509952015-07-13 14:35:43 -0700524void MarkSweep::MarkHeapReference(mirror::HeapReference<mirror::Object>* ref) {
525 MarkObject(ref->AsMirrorPtr(), nullptr, MemberOffset(0));
526}
527
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700528// 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 -0700529inline void MarkSweep::MarkObject(mirror::Object* obj,
530 mirror::Object* holder,
Mathieu Chartier97509952015-07-13 14:35:43 -0700531 MemberOffset offset) {
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700532 if (obj != nullptr) {
Hiroshi Yamauchieb2baaf2015-05-13 21:14:22 -0700533 MarkObjectNonNull(obj, holder, offset);
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700534 } else if (kCountMarkedObjects) {
535 ++mark_null_count_;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700536 }
537}
538
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700539class MarkSweep::VerifyRootMarkedVisitor : public SingleRootVisitor {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700540 public:
541 explicit VerifyRootMarkedVisitor(MarkSweep* collector) : collector_(collector) { }
542
543 void VisitRoot(mirror::Object* root, const RootInfo& info) OVERRIDE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700544 REQUIRES_SHARED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mathieu Chartier97509952015-07-13 14:35:43 -0700545 CHECK(collector_->IsMarked(root) != nullptr) << info.ToString();
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700546 }
547
548 private:
549 MarkSweep* const collector_;
550};
551
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -0700552void MarkSweep::VisitRoots(mirror::Object*** roots,
553 size_t count,
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700554 const RootInfo& info ATTRIBUTE_UNUSED) {
555 for (size_t i = 0; i < count; ++i) {
556 MarkObjectNonNull(*roots[i]);
557 }
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800558}
559
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -0700560void MarkSweep::VisitRoots(mirror::CompressedReference<mirror::Object>** roots,
561 size_t count,
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700562 const RootInfo& info ATTRIBUTE_UNUSED) {
563 for (size_t i = 0; i < count; ++i) {
564 MarkObjectNonNull(roots[i]->AsMirrorPtr());
565 }
Mathieu Chartier893263b2014-03-04 11:07:42 -0800566}
567
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700568class MarkSweep::VerifyRootVisitor : public SingleRootVisitor {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700569 public:
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700570 void VisitRoot(mirror::Object* root, const RootInfo& info) OVERRIDE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700571 REQUIRES_SHARED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mathieu Chartier9086b652015-04-14 09:35:18 -0700572 // See if the root is on any space bitmap.
573 auto* heap = Runtime::Current()->GetHeap();
574 if (heap->GetLiveBitmap()->GetContinuousSpaceBitmap(root) == nullptr) {
575 space::LargeObjectSpace* large_object_space = heap->GetLargeObjectsSpace();
576 if (large_object_space != nullptr && !large_object_space->Contains(root)) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700577 LOG(FATAL_WITHOUT_ABORT) << "Found invalid root: " << root << " " << info;
Mathieu Chartier9086b652015-04-14 09:35:18 -0700578 }
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700579 }
580 }
Mathieu Chartier9086b652015-04-14 09:35:18 -0700581};
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700582
Mathieu Chartierf8a86b92016-06-14 17:08:47 -0700583void MarkSweep::VerifySuspendedThreadRoots() {
Mathieu Chartier9086b652015-04-14 09:35:18 -0700584 VerifyRootVisitor visitor;
Mathieu Chartierf8a86b92016-06-14 17:08:47 -0700585 Runtime::Current()->GetThreadList()->VisitRootsForSuspendedThreads(&visitor);
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700586}
587
Mathieu Chartier893263b2014-03-04 11:07:42 -0800588void MarkSweep::MarkRoots(Thread* self) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700589 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Mathieu Chartier893263b2014-03-04 11:07:42 -0800590 if (Locks::mutator_lock_->IsExclusiveHeld(self)) {
591 // If we exclusively hold the mutator lock, all threads must be suspended.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700592 Runtime::Current()->VisitRoots(this);
Mathieu Chartier893263b2014-03-04 11:07:42 -0800593 RevokeAllThreadLocalAllocationStacks(self);
594 } else {
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -0700595 MarkRootsCheckpoint(self, kRevokeRosAllocThreadLocalBuffersAtCheckpoint);
Mathieu Chartier893263b2014-03-04 11:07:42 -0800596 // At this point the live stack should no longer have any mutators which push into it.
597 MarkNonThreadRoots();
598 MarkConcurrentRoots(
599 static_cast<VisitRootFlags>(kVisitRootFlagAllRoots | kVisitRootFlagStartLoggingNewRoots));
600 }
Mathieu Chartier9ebae1f2012-10-15 17:38:16 -0700601}
602
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700603void MarkSweep::MarkNonThreadRoots() {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700604 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700605 Runtime::Current()->VisitNonThreadRoots(this);
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700606}
607
Mathieu Chartier893263b2014-03-04 11:07:42 -0800608void MarkSweep::MarkConcurrentRoots(VisitRootFlags flags) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700609 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Ian Rogers1d54e732013-05-02 21:10:01 -0700610 // Visit all runtime roots and clear dirty flags.
Mathieu Chartier4edd8472015-06-01 10:47:36 -0700611 Runtime::Current()->VisitConcurrentRoots(
612 this, static_cast<VisitRootFlags>(flags | kVisitRootFlagNonMoving));
Carl Shapiro69759ea2011-07-21 18:13:35 -0700613}
614
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700615class MarkSweep::DelayReferenceReferentVisitor {
Mathieu Chartier407f7022014-02-18 14:37:05 -0800616 public:
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -0700617 explicit DelayReferenceReferentVisitor(MarkSweep* collector) : collector_(collector) {}
Mathieu Chartier407f7022014-02-18 14:37:05 -0800618
619 void operator()(mirror::Class* klass, mirror::Reference* ref) const
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -0700620 REQUIRES(Locks::heap_bitmap_lock_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700621 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier407f7022014-02-18 14:37:05 -0800622 collector_->DelayReferenceReferent(klass, ref);
623 }
624
625 private:
626 MarkSweep* const collector_;
627};
628
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700629template <bool kUseFinger = false>
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700630class MarkSweep::MarkStackTask : public Task {
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700631 public:
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -0700632 MarkStackTask(ThreadPool* thread_pool,
633 MarkSweep* mark_sweep,
634 size_t mark_stack_size,
Mathieu Chartier97509952015-07-13 14:35:43 -0700635 StackReference<mirror::Object>* mark_stack)
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700636 : mark_sweep_(mark_sweep),
637 thread_pool_(thread_pool),
638 mark_stack_pos_(mark_stack_size) {
639 // We may have to copy part of an existing mark stack when another mark stack overflows.
640 if (mark_stack_size != 0) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700641 DCHECK(mark_stack != nullptr);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700642 // TODO: Check performance?
643 std::copy(mark_stack, mark_stack + mark_stack_size, mark_stack_);
Ian Rogers1d54e732013-05-02 21:10:01 -0700644 }
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700645 if (kCountTasks) {
646 ++mark_sweep_->work_chunks_created_;
647 }
648 }
649
650 static const size_t kMaxSize = 1 * KB;
651
652 protected:
Mathieu Chartier407f7022014-02-18 14:37:05 -0800653 class MarkObjectParallelVisitor {
654 public:
Roland Levillain3887c462015-08-12 18:15:42 +0100655 ALWAYS_INLINE MarkObjectParallelVisitor(MarkStackTask<kUseFinger>* chunk_task,
656 MarkSweep* mark_sweep)
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700657 : chunk_task_(chunk_task), mark_sweep_(mark_sweep) {}
Mathieu Chartier407f7022014-02-18 14:37:05 -0800658
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -0700659 ALWAYS_INLINE void operator()(mirror::Object* obj,
660 MemberOffset offset,
661 bool is_static ATTRIBUTE_UNUSED) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700662 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700663 Mark(obj->GetFieldObject<mirror::Object>(offset));
664 }
665
666 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700667 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700668 if (!root->IsNull()) {
669 VisitRoot(root);
670 }
671 }
672
673 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700674 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700675 if (kCheckLocks) {
676 Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
677 Locks::heap_bitmap_lock_->AssertExclusiveHeld(Thread::Current());
678 }
679 Mark(root->AsMirrorPtr());
680 }
681
682 private:
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700683 ALWAYS_INLINE void Mark(mirror::Object* ref) const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier407f7022014-02-18 14:37:05 -0800684 if (ref != nullptr && mark_sweep_->MarkObjectParallel(ref)) {
685 if (kUseFinger) {
Yabin Cuic7df66e2015-04-15 15:40:18 -0700686 std::atomic_thread_fence(std::memory_order_seq_cst);
Mathieu Chartier407f7022014-02-18 14:37:05 -0800687 if (reinterpret_cast<uintptr_t>(ref) >=
Ian Rogers3e5cf302014-05-20 16:40:37 -0700688 static_cast<uintptr_t>(mark_sweep_->atomic_finger_.LoadRelaxed())) {
Mathieu Chartier407f7022014-02-18 14:37:05 -0800689 return;
690 }
691 }
692 chunk_task_->MarkStackPush(ref);
693 }
694 }
695
Mathieu Chartier407f7022014-02-18 14:37:05 -0800696 MarkStackTask<kUseFinger>* const chunk_task_;
697 MarkSweep* const mark_sweep_;
698 };
699
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700700 class ScanObjectParallelVisitor {
701 public:
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -0700702 ALWAYS_INLINE explicit ScanObjectParallelVisitor(MarkStackTask<kUseFinger>* chunk_task)
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700703 : chunk_task_(chunk_task) {}
704
Mathieu Chartier407f7022014-02-18 14:37:05 -0800705 // No thread safety analysis since multiple threads will use this visitor.
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -0700706 void operator()(mirror::Object* obj) const
707 REQUIRES(Locks::heap_bitmap_lock_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700708 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier407f7022014-02-18 14:37:05 -0800709 MarkSweep* const mark_sweep = chunk_task_->mark_sweep_;
710 MarkObjectParallelVisitor mark_visitor(chunk_task_, mark_sweep);
711 DelayReferenceReferentVisitor ref_visitor(mark_sweep);
712 mark_sweep->ScanObjectVisit(obj, mark_visitor, ref_visitor);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700713 }
714
715 private:
716 MarkStackTask<kUseFinger>* const chunk_task_;
717 };
718
719 virtual ~MarkStackTask() {
720 // Make sure that we have cleared our mark stack.
721 DCHECK_EQ(mark_stack_pos_, 0U);
722 if (kCountTasks) {
723 ++mark_sweep_->work_chunks_deleted_;
724 }
725 }
726
727 MarkSweep* const mark_sweep_;
728 ThreadPool* const thread_pool_;
729 // Thread local mark stack for this task.
Mathieu Chartier97509952015-07-13 14:35:43 -0700730 StackReference<mirror::Object> mark_stack_[kMaxSize];
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700731 // Mark stack position.
732 size_t mark_stack_pos_;
733
Mathieu Chartier97509952015-07-13 14:35:43 -0700734 ALWAYS_INLINE void MarkStackPush(mirror::Object* obj)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700735 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700736 if (UNLIKELY(mark_stack_pos_ == kMaxSize)) {
737 // Mark stack overflow, give 1/2 the stack to the thread pool as a new work task.
738 mark_stack_pos_ /= 2;
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -0700739 auto* task = new MarkStackTask(thread_pool_,
740 mark_sweep_,
741 kMaxSize - mark_stack_pos_,
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700742 mark_stack_ + mark_stack_pos_);
743 thread_pool_->AddTask(Thread::Current(), task);
744 }
745 DCHECK(obj != nullptr);
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700746 DCHECK_LT(mark_stack_pos_, kMaxSize);
Mathieu Chartiercb535da2015-01-23 13:50:03 -0800747 mark_stack_[mark_stack_pos_++].Assign(obj);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700748 }
749
750 virtual void Finalize() {
751 delete this;
752 }
753
754 // Scans all of the objects
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -0700755 virtual void Run(Thread* self ATTRIBUTE_UNUSED)
756 REQUIRES(Locks::heap_bitmap_lock_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700757 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700758 ScanObjectParallelVisitor visitor(this);
759 // TODO: Tune this.
760 static const size_t kFifoSize = 4;
Mathieu Chartier97509952015-07-13 14:35:43 -0700761 BoundedFifoPowerOfTwo<mirror::Object*, kFifoSize> prefetch_fifo;
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700762 for (;;) {
Mathieu Chartier97509952015-07-13 14:35:43 -0700763 mirror::Object* obj = nullptr;
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700764 if (kUseMarkStackPrefetch) {
765 while (mark_stack_pos_ != 0 && prefetch_fifo.size() < kFifoSize) {
Mathieu Chartier97509952015-07-13 14:35:43 -0700766 mirror::Object* const mark_stack_obj = mark_stack_[--mark_stack_pos_].AsMirrorPtr();
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800767 DCHECK(mark_stack_obj != nullptr);
768 __builtin_prefetch(mark_stack_obj);
769 prefetch_fifo.push_back(mark_stack_obj);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700770 }
771 if (UNLIKELY(prefetch_fifo.empty())) {
772 break;
773 }
774 obj = prefetch_fifo.front();
775 prefetch_fifo.pop_front();
776 } else {
777 if (UNLIKELY(mark_stack_pos_ == 0)) {
778 break;
779 }
Mathieu Chartiercb535da2015-01-23 13:50:03 -0800780 obj = mark_stack_[--mark_stack_pos_].AsMirrorPtr();
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700781 }
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700782 DCHECK(obj != nullptr);
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700783 visitor(obj);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700784 }
785 }
786};
787
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700788class MarkSweep::CardScanTask : public MarkStackTask<false> {
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700789 public:
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -0700790 CardScanTask(ThreadPool* thread_pool,
791 MarkSweep* mark_sweep,
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -0700792 accounting::ContinuousSpaceBitmap* bitmap,
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -0700793 uint8_t* begin,
794 uint8_t* end,
795 uint8_t minimum_age,
796 size_t mark_stack_size,
797 StackReference<mirror::Object>* mark_stack_obj,
798 bool clear_card)
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700799 : MarkStackTask<false>(thread_pool, mark_sweep, mark_stack_size, mark_stack_obj),
800 bitmap_(bitmap),
801 begin_(begin),
802 end_(end),
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -0700803 minimum_age_(minimum_age),
804 clear_card_(clear_card) {}
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700805
806 protected:
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -0700807 accounting::ContinuousSpaceBitmap* const bitmap_;
Ian Rogers13735952014-10-08 12:43:28 -0700808 uint8_t* const begin_;
809 uint8_t* const end_;
810 const uint8_t minimum_age_;
Lei Li727b2942015-01-15 11:26:34 +0800811 const bool clear_card_;
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700812
813 virtual void Finalize() {
814 delete this;
815 }
816
817 virtual void Run(Thread* self) NO_THREAD_SAFETY_ANALYSIS {
818 ScanObjectParallelVisitor visitor(this);
819 accounting::CardTable* card_table = mark_sweep_->GetHeap()->GetCardTable();
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -0700820 size_t cards_scanned = clear_card_
821 ? card_table->Scan<true>(bitmap_, begin_, end_, visitor, minimum_age_)
822 : card_table->Scan<false>(bitmap_, begin_, end_, visitor, minimum_age_);
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700823 VLOG(heap) << "Parallel scanning cards " << reinterpret_cast<void*>(begin_) << " - "
824 << reinterpret_cast<void*>(end_) << " = " << cards_scanned;
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700825 // Finish by emptying our local mark stack.
826 MarkStackTask::Run(self);
827 }
828};
829
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700830size_t MarkSweep::GetThreadCount(bool paused) const {
Mathieu Chartierf8cb1782016-03-18 18:45:41 -0700831 // Use less threads if we are in a background state (non jank perceptible) since we want to leave
832 // more CPU time for the foreground apps.
833 if (heap_->GetThreadPool() == nullptr || !Runtime::Current()->InJankPerceptibleProcessState()) {
Mathieu Chartierbbd695c2014-04-16 09:48:48 -0700834 return 1;
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700835 }
Mathieu Chartier10d68862015-04-15 14:21:33 -0700836 return (paused ? heap_->GetParallelGCThreadCount() : heap_->GetConcGCThreadCount()) + 1;
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700837}
838
Ian Rogers13735952014-10-08 12:43:28 -0700839void MarkSweep::ScanGrayObjects(bool paused, uint8_t minimum_age) {
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700840 accounting::CardTable* card_table = GetHeap()->GetCardTable();
841 ThreadPool* thread_pool = GetHeap()->GetThreadPool();
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700842 size_t thread_count = GetThreadCount(paused);
843 // The parallel version with only one thread is faster for card scanning, TODO: fix.
Mathieu Chartierbbd695c2014-04-16 09:48:48 -0700844 if (kParallelCardScan && thread_count > 1) {
Mathieu Chartier720ef762013-08-17 14:46:54 -0700845 Thread* self = Thread::Current();
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700846 // Can't have a different split for each space since multiple spaces can have their cards being
847 // scanned at the same time.
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700848 TimingLogger::ScopedTiming t(paused ? "(Paused)ScanGrayObjects" : __FUNCTION__,
849 GetTimings());
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700850 // 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 -0700851 StackReference<mirror::Object>* mark_stack_begin = mark_stack_->Begin();
852 StackReference<mirror::Object>* mark_stack_end = mark_stack_->End();
Mathieu Chartier720ef762013-08-17 14:46:54 -0700853 const size_t mark_stack_size = mark_stack_end - mark_stack_begin;
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700854 // Estimated number of work tasks we will create.
855 const size_t mark_stack_tasks = GetHeap()->GetContinuousSpaces().size() * thread_count;
856 DCHECK_NE(mark_stack_tasks, 0U);
857 const size_t mark_stack_delta = std::min(CardScanTask::kMaxSize / 2,
858 mark_stack_size / mark_stack_tasks + 1);
859 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700860 if (space->GetMarkBitmap() == nullptr) {
861 continue;
862 }
Ian Rogers13735952014-10-08 12:43:28 -0700863 uint8_t* card_begin = space->Begin();
864 uint8_t* card_end = space->End();
Hiroshi Yamauchi0941b042013-11-05 11:34:03 -0800865 // Align up the end address. For example, the image space's end
866 // may not be card-size-aligned.
867 card_end = AlignUp(card_end, accounting::CardTable::kCardSize);
Roland Levillain14d90572015-07-16 10:52:26 +0100868 DCHECK_ALIGNED(card_begin, accounting::CardTable::kCardSize);
869 DCHECK_ALIGNED(card_end, accounting::CardTable::kCardSize);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700870 // Calculate how many bytes of heap we will scan,
871 const size_t address_range = card_end - card_begin;
872 // Calculate how much address range each task gets.
873 const size_t card_delta = RoundUp(address_range / thread_count + 1,
874 accounting::CardTable::kCardSize);
Lei Li727b2942015-01-15 11:26:34 +0800875 // If paused and the space is neither zygote nor image space, we could clear the dirty
876 // cards to avoid accumulating them to increase card scanning load in the following GC
877 // cycles. We need to keep dirty cards of image space and zygote space in order to track
878 // references to the other spaces.
879 bool clear_card = paused && !space->IsZygoteSpace() && !space->IsImageSpace();
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700880 // Create the worker tasks for this space.
881 while (card_begin != card_end) {
882 // Add a range of cards.
883 size_t addr_remaining = card_end - card_begin;
884 size_t card_increment = std::min(card_delta, addr_remaining);
885 // Take from the back of the mark stack.
886 size_t mark_stack_remaining = mark_stack_end - mark_stack_begin;
887 size_t mark_stack_increment = std::min(mark_stack_delta, mark_stack_remaining);
888 mark_stack_end -= mark_stack_increment;
889 mark_stack_->PopBackCount(static_cast<int32_t>(mark_stack_increment));
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700890 DCHECK_EQ(mark_stack_end, mark_stack_->End());
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700891 // Add the new task to the thread pool.
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -0700892 auto* task = new CardScanTask(thread_pool,
893 this,
894 space->GetMarkBitmap(),
895 card_begin,
896 card_begin + card_increment,
897 minimum_age,
898 mark_stack_increment,
899 mark_stack_end,
900 clear_card);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700901 thread_pool->AddTask(self, task);
902 card_begin += card_increment;
903 }
904 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700905
Hiroshi Yamauchi0941b042013-11-05 11:34:03 -0800906 // Note: the card scan below may dirty new cards (and scan them)
907 // as a side effect when a Reference object is encountered and
908 // queued during the marking. See b/11465268.
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700909 thread_pool->SetMaxActiveWorkers(thread_count - 1);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700910 thread_pool->StartWorkers(self);
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700911 thread_pool->Wait(self, true, true);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700912 thread_pool->StopWorkers(self);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700913 } else {
914 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700915 if (space->GetMarkBitmap() != nullptr) {
916 // Image spaces are handled properly since live == marked for them.
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700917 const char* name = nullptr;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700918 switch (space->GetGcRetentionPolicy()) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700919 case space::kGcRetentionPolicyNeverCollect:
920 name = paused ? "(Paused)ScanGrayImageSpaceObjects" : "ScanGrayImageSpaceObjects";
921 break;
922 case space::kGcRetentionPolicyFullCollect:
923 name = paused ? "(Paused)ScanGrayZygoteSpaceObjects" : "ScanGrayZygoteSpaceObjects";
924 break;
925 case space::kGcRetentionPolicyAlwaysCollect:
926 name = paused ? "(Paused)ScanGrayAllocSpaceObjects" : "ScanGrayAllocSpaceObjects";
927 break;
928 default:
929 LOG(FATAL) << "Unreachable";
Ian Rogers2c4257b2014-10-24 14:20:06 -0700930 UNREACHABLE();
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700931 }
932 TimingLogger::ScopedTiming t(name, GetTimings());
Mathieu Chartier590fee92013-09-13 13:46:47 -0700933 ScanObjectVisitor visitor(this);
Lei Li727b2942015-01-15 11:26:34 +0800934 bool clear_card = paused && !space->IsZygoteSpace() && !space->IsImageSpace();
935 if (clear_card) {
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -0700936 card_table->Scan<true>(space->GetMarkBitmap(),
937 space->Begin(),
938 space->End(),
939 visitor,
Lei Li727b2942015-01-15 11:26:34 +0800940 minimum_age);
941 } else {
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -0700942 card_table->Scan<false>(space->GetMarkBitmap(),
943 space->Begin(),
944 space->End(),
945 visitor,
Lei Li727b2942015-01-15 11:26:34 +0800946 minimum_age);
947 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700948 }
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700949 }
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700950 }
951}
952
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700953class MarkSweep::RecursiveMarkTask : public MarkStackTask<false> {
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700954 public:
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -0700955 RecursiveMarkTask(ThreadPool* thread_pool,
956 MarkSweep* mark_sweep,
957 accounting::ContinuousSpaceBitmap* bitmap,
958 uintptr_t begin,
959 uintptr_t end)
960 : MarkStackTask<false>(thread_pool, mark_sweep, 0, nullptr),
961 bitmap_(bitmap),
962 begin_(begin),
963 end_(end) {}
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700964
965 protected:
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -0700966 accounting::ContinuousSpaceBitmap* const bitmap_;
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700967 const uintptr_t begin_;
968 const uintptr_t end_;
969
970 virtual void Finalize() {
971 delete this;
972 }
973
974 // Scans all of the objects
975 virtual void Run(Thread* self) NO_THREAD_SAFETY_ANALYSIS {
976 ScanObjectParallelVisitor visitor(this);
977 bitmap_->VisitMarkedRange(begin_, end_, visitor);
978 // Finish by emptying our local mark stack.
979 MarkStackTask::Run(self);
980 }
981};
982
Carl Shapiro58551df2011-07-24 03:09:51 -0700983// Populates the mark stack based on the set of marked objects and
984// recursively marks until the mark stack is emptied.
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800985void MarkSweep::RecursiveMark() {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700986 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Mathieu Chartiera1602f22014-01-13 17:19:19 -0800987 // RecursiveMark will build the lists of known instances of the Reference classes. See
988 // DelayReferenceReferent for details.
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700989 if (kUseRecursiveMark) {
990 const bool partial = GetGcType() == kGcTypePartial;
991 ScanObjectVisitor scan_visitor(this);
992 auto* self = Thread::Current();
993 ThreadPool* thread_pool = heap_->GetThreadPool();
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700994 size_t thread_count = GetThreadCount(false);
995 const bool parallel = kParallelRecursiveMark && thread_count > 1;
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700996 mark_stack_->Reset();
Mathieu Chartier02e25112013-08-14 16:14:24 -0700997 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700998 if ((space->GetGcRetentionPolicy() == space::kGcRetentionPolicyAlwaysCollect) ||
999 (!partial && space->GetGcRetentionPolicy() == space::kGcRetentionPolicyFullCollect)) {
Mathieu Chartier0e54cd02014-03-20 12:41:23 -07001000 current_space_bitmap_ = space->GetMarkBitmap();
1001 if (current_space_bitmap_ == nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001002 continue;
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001003 }
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001004 if (parallel) {
1005 // We will use the mark stack the future.
1006 // CHECK(mark_stack_->IsEmpty());
1007 // This function does not handle heap end increasing, so we must use the space end.
1008 uintptr_t begin = reinterpret_cast<uintptr_t>(space->Begin());
1009 uintptr_t end = reinterpret_cast<uintptr_t>(space->End());
Ian Rogers3e5cf302014-05-20 16:40:37 -07001010 atomic_finger_.StoreRelaxed(AtomicInteger::MaxValue());
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001011
1012 // Create a few worker tasks.
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001013 const size_t n = thread_count * 2;
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001014 while (begin != end) {
1015 uintptr_t start = begin;
1016 uintptr_t delta = (end - begin) / n;
1017 delta = RoundUp(delta, KB);
1018 if (delta < 16 * KB) delta = end - begin;
1019 begin += delta;
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -07001020 auto* task = new RecursiveMarkTask(thread_pool,
1021 this,
1022 current_space_bitmap_,
1023 start,
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001024 begin);
1025 thread_pool->AddTask(self, task);
1026 }
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001027 thread_pool->SetMaxActiveWorkers(thread_count - 1);
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001028 thread_pool->StartWorkers(self);
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001029 thread_pool->Wait(self, true, true);
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001030 thread_pool->StopWorkers(self);
1031 } else {
1032 // This function does not handle heap end increasing, so we must use the space end.
1033 uintptr_t begin = reinterpret_cast<uintptr_t>(space->Begin());
1034 uintptr_t end = reinterpret_cast<uintptr_t>(space->End());
Mathieu Chartier0e54cd02014-03-20 12:41:23 -07001035 current_space_bitmap_->VisitMarkedRange(begin, end, scan_visitor);
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001036 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001037 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001038 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001039 }
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001040 ProcessMarkStack(false);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001041}
1042
Ian Rogers13735952014-10-08 12:43:28 -07001043void MarkSweep::RecursiveMarkDirtyObjects(bool paused, uint8_t minimum_age) {
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001044 ScanGrayObjects(paused, minimum_age);
1045 ProcessMarkStack(paused);
Mathieu Chartier262e5ff2012-06-01 17:35:38 -07001046}
1047
Carl Shapiro58551df2011-07-24 03:09:51 -07001048void MarkSweep::ReMarkRoots() {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001049 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Mathieu Chartier893263b2014-03-04 11:07:42 -08001050 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001051 Runtime::Current()->VisitRoots(this, static_cast<VisitRootFlags>(
1052 kVisitRootFlagNewRoots | kVisitRootFlagStopLoggingNewRoots | kVisitRootFlagClearRootLog));
Mathieu Chartier7bf9f192014-04-04 11:09:41 -07001053 if (kVerifyRootsMarked) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001054 TimingLogger::ScopedTiming t2("(Paused)VerifyRoots", GetTimings());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001055 VerifyRootMarkedVisitor visitor(this);
1056 Runtime::Current()->VisitRoots(&visitor);
Mathieu Chartier893263b2014-03-04 11:07:42 -08001057 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001058}
1059
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -07001060void MarkSweep::SweepSystemWeaks(Thread* self) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001061 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Mathieu Chartier14c3bf92015-07-13 14:35:43 -07001062 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier97509952015-07-13 14:35:43 -07001063 Runtime::Current()->SweepSystemWeaks(this);
Carl Shapiro58551df2011-07-24 03:09:51 -07001064}
1065
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001066class MarkSweep::VerifySystemWeakVisitor : public IsMarkedVisitor {
Mathieu Chartier97509952015-07-13 14:35:43 -07001067 public:
1068 explicit VerifySystemWeakVisitor(MarkSweep* mark_sweep) : mark_sweep_(mark_sweep) {}
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001069
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -07001070 virtual mirror::Object* IsMarked(mirror::Object* obj)
1071 OVERRIDE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001072 REQUIRES_SHARED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mathieu Chartier97509952015-07-13 14:35:43 -07001073 mark_sweep_->VerifyIsLive(obj);
1074 return obj;
1075 }
1076
1077 MarkSweep* const mark_sweep_;
1078};
1079
1080void MarkSweep::VerifyIsLive(const mirror::Object* obj) {
Mathieu Chartier4aeec172014-03-27 16:09:46 -07001081 if (!heap_->GetLiveBitmap()->Test(obj)) {
Mathieu Chartiercb535da2015-01-23 13:50:03 -08001082 // TODO: Consider live stack? Has this code bitrotted?
1083 CHECK(!heap_->allocation_stack_->Contains(obj))
1084 << "Found dead object " << obj << "\n" << heap_->DumpSpaces();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001085 }
1086}
1087
1088void MarkSweep::VerifySystemWeaks() {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001089 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001090 // Verify system weaks, uses a special object visitor which returns the input object.
Mathieu Chartier97509952015-07-13 14:35:43 -07001091 VerifySystemWeakVisitor visitor(this);
1092 Runtime::Current()->SweepSystemWeaks(&visitor);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001093}
1094
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001095class MarkSweep::CheckpointMarkThreadRoots : public Closure, public RootVisitor {
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001096 public:
Roland Levillain3887c462015-08-12 18:15:42 +01001097 CheckpointMarkThreadRoots(MarkSweep* mark_sweep,
1098 bool revoke_ros_alloc_thread_local_buffers_at_checkpoint)
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -07001099 : mark_sweep_(mark_sweep),
1100 revoke_ros_alloc_thread_local_buffers_at_checkpoint_(
1101 revoke_ros_alloc_thread_local_buffers_at_checkpoint) {
1102 }
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001103
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001104 void VisitRoots(mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001105 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_)
Mathieu Chartier90443472015-07-16 20:32:27 -07001106 REQUIRES(Locks::heap_bitmap_lock_) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001107 for (size_t i = 0; i < count; ++i) {
1108 mark_sweep_->MarkObjectNonNullParallel(*roots[i]);
1109 }
1110 }
1111
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -07001112 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots,
1113 size_t count,
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001114 const RootInfo& info ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001115 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_)
Mathieu Chartier90443472015-07-16 20:32:27 -07001116 REQUIRES(Locks::heap_bitmap_lock_) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001117 for (size_t i = 0; i < count; ++i) {
1118 mark_sweep_->MarkObjectNonNullParallel(roots[i]->AsMirrorPtr());
1119 }
1120 }
1121
Mathieu Chartier4aeec172014-03-27 16:09:46 -07001122 virtual void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001123 ScopedTrace trace("Marking thread roots");
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001124 // Note: self is not necessarily equal to thread since thread may be suspended.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001125 Thread* const self = Thread::Current();
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001126 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
1127 << thread->GetState() << " thread " << thread << " self " << self;
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001128 thread->VisitRoots(this);
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -07001129 if (revoke_ros_alloc_thread_local_buffers_at_checkpoint_) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001130 ScopedTrace trace2("RevokeRosAllocThreadLocalBuffers");
Hiroshi Yamauchic93c5302014-03-20 16:15:37 -07001131 mark_sweep_->GetHeap()->RevokeRosAllocThreadLocalBuffers(thread);
1132 }
Lei Lidd9943d2015-02-02 14:24:44 +08001133 // If thread is a running mutator, then act on behalf of the garbage collector.
1134 // See the code in ThreadList::RunCheckpoint.
Mathieu Chartier10d25082015-10-28 18:36:09 -07001135 mark_sweep_->GetBarrier().Pass(self);
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001136 }
1137
1138 private:
Mathieu Chartier4aeec172014-03-27 16:09:46 -07001139 MarkSweep* const mark_sweep_;
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -07001140 const bool revoke_ros_alloc_thread_local_buffers_at_checkpoint_;
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001141};
1142
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -07001143void MarkSweep::MarkRootsCheckpoint(Thread* self,
1144 bool revoke_ros_alloc_thread_local_buffers_at_checkpoint) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001145 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -07001146 CheckpointMarkThreadRoots check_point(this, revoke_ros_alloc_thread_local_buffers_at_checkpoint);
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001147 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Ian Rogers1d54e732013-05-02 21:10:01 -07001148 // Request the check point is run on all threads returning a count of the threads that must
1149 // run through the barrier including self.
1150 size_t barrier_count = thread_list->RunCheckpoint(&check_point);
1151 // Release locks then wait for all mutator threads to pass the barrier.
Lei Lidd9943d2015-02-02 14:24:44 +08001152 // If there are no threads to wait which implys that all the checkpoint functions are finished,
1153 // then no need to release locks.
1154 if (barrier_count == 0) {
1155 return;
1156 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001157 Locks::heap_bitmap_lock_->ExclusiveUnlock(self);
1158 Locks::mutator_lock_->SharedUnlock(self);
Mathieu Chartier4aeec172014-03-27 16:09:46 -07001159 {
1160 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
1161 gc_barrier_->Increment(self, barrier_count);
1162 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001163 Locks::mutator_lock_->SharedLock(self);
1164 Locks::heap_bitmap_lock_->ExclusiveLock(self);
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001165}
1166
Ian Rogers1d54e732013-05-02 21:10:01 -07001167void MarkSweep::SweepArray(accounting::ObjectStack* allocations, bool swap_bitmaps) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001168 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001169 Thread* self = Thread::Current();
Hiroshi Yamauchibbdc5bc2014-05-28 14:04:59 -07001170 mirror::Object** chunk_free_buffer = reinterpret_cast<mirror::Object**>(
1171 sweep_array_free_buffer_mem_map_->BaseBegin());
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001172 size_t chunk_free_pos = 0;
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07001173 ObjectBytePair freed;
1174 ObjectBytePair freed_los;
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001175 // How many objects are left in the array, modified after each space is swept.
Mathieu Chartier97509952015-07-13 14:35:43 -07001176 StackReference<mirror::Object>* objects = allocations->Begin();
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001177 size_t count = allocations->Size();
1178 // Change the order to ensure that the non-moving space last swept as an optimization.
1179 std::vector<space::ContinuousSpace*> sweep_spaces;
1180 space::ContinuousSpace* non_moving_space = nullptr;
1181 for (space::ContinuousSpace* space : heap_->GetContinuousSpaces()) {
Mathieu Chartier763a31e2015-11-16 16:05:55 -08001182 if (space->IsAllocSpace() &&
1183 !immune_spaces_.ContainsSpace(space) &&
Mathieu Chartier8d562102014-03-12 17:42:10 -07001184 space->GetLiveBitmap() != nullptr) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001185 if (space == heap_->GetNonMovingSpace()) {
1186 non_moving_space = space;
1187 } else {
1188 sweep_spaces.push_back(space);
1189 }
1190 }
1191 }
1192 // Unlikely to sweep a significant amount of non_movable objects, so we do these after the after
1193 // the other alloc spaces as an optimization.
1194 if (non_moving_space != nullptr) {
1195 sweep_spaces.push_back(non_moving_space);
1196 }
1197 // Start by sweeping the continuous spaces.
1198 for (space::ContinuousSpace* space : sweep_spaces) {
1199 space::AllocSpace* alloc_space = space->AsAllocSpace();
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -07001200 accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
1201 accounting::ContinuousSpaceBitmap* mark_bitmap = space->GetMarkBitmap();
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001202 if (swap_bitmaps) {
1203 std::swap(live_bitmap, mark_bitmap);
1204 }
Mathieu Chartier97509952015-07-13 14:35:43 -07001205 StackReference<mirror::Object>* out = objects;
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001206 for (size_t i = 0; i < count; ++i) {
Mathieu Chartier97509952015-07-13 14:35:43 -07001207 mirror::Object* const obj = objects[i].AsMirrorPtr();
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08001208 if (kUseThreadLocalAllocationStack && obj == nullptr) {
1209 continue;
1210 }
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001211 if (space->HasAddress(obj)) {
1212 // This object is in the space, remove it from the array and add it to the sweep buffer
1213 // if needed.
1214 if (!mark_bitmap->Test(obj)) {
1215 if (chunk_free_pos >= kSweepArrayChunkFreeSize) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001216 TimingLogger::ScopedTiming t2("FreeList", GetTimings());
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07001217 freed.objects += chunk_free_pos;
1218 freed.bytes += alloc_space->FreeList(self, chunk_free_pos, chunk_free_buffer);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001219 chunk_free_pos = 0;
1220 }
1221 chunk_free_buffer[chunk_free_pos++] = obj;
1222 }
1223 } else {
Mathieu Chartiercb535da2015-01-23 13:50:03 -08001224 (out++)->Assign(obj);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001225 }
1226 }
1227 if (chunk_free_pos > 0) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001228 TimingLogger::ScopedTiming t2("FreeList", GetTimings());
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07001229 freed.objects += chunk_free_pos;
1230 freed.bytes += alloc_space->FreeList(self, chunk_free_pos, chunk_free_buffer);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001231 chunk_free_pos = 0;
1232 }
1233 // All of the references which space contained are no longer in the allocation stack, update
1234 // the count.
1235 count = out - objects;
1236 }
1237 // Handle the large object space.
1238 space::LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
Mathieu Chartier2dbe6272014-09-16 10:43:23 -07001239 if (large_object_space != nullptr) {
1240 accounting::LargeObjectBitmap* large_live_objects = large_object_space->GetLiveBitmap();
1241 accounting::LargeObjectBitmap* large_mark_objects = large_object_space->GetMarkBitmap();
1242 if (swap_bitmaps) {
1243 std::swap(large_live_objects, large_mark_objects);
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08001244 }
Mathieu Chartier2dbe6272014-09-16 10:43:23 -07001245 for (size_t i = 0; i < count; ++i) {
Mathieu Chartier97509952015-07-13 14:35:43 -07001246 mirror::Object* const obj = objects[i].AsMirrorPtr();
Mathieu Chartier2dbe6272014-09-16 10:43:23 -07001247 // Handle large objects.
1248 if (kUseThreadLocalAllocationStack && obj == nullptr) {
1249 continue;
1250 }
1251 if (!large_mark_objects->Test(obj)) {
1252 ++freed_los.objects;
1253 freed_los.bytes += large_object_space->Free(self, obj);
1254 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001255 }
1256 }
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001257 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001258 TimingLogger::ScopedTiming t2("RecordFree", GetTimings());
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001259 RecordFree(freed);
1260 RecordFreeLOS(freed_los);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001261 t2.NewTiming("ResetStack");
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001262 allocations->Reset();
1263 }
Ian Rogersc5f17732014-06-05 20:48:42 -07001264 sweep_array_free_buffer_mem_map_->MadviseDontNeedAndZero();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001265}
1266
Ian Rogers1d54e732013-05-02 21:10:01 -07001267void MarkSweep::Sweep(bool swap_bitmaps) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001268 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -07001269 // Ensure that nobody inserted items in the live stack after we swapped the stacks.
1270 CHECK_GE(live_stack_freeze_size_, GetHeap()->GetLiveStack()->Size());
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001271 {
1272 TimingLogger::ScopedTiming t2("MarkAllocStackAsLive", GetTimings());
1273 // Mark everything allocated since the last as GC live so that we can sweep concurrently,
1274 // knowing that new allocations won't be marked as live.
1275 accounting::ObjectStack* live_stack = heap_->GetLiveStack();
1276 heap_->MarkAllocStackAsLive(live_stack);
1277 live_stack->Reset();
1278 DCHECK(mark_stack_->IsEmpty());
1279 }
Mathieu Chartier02e25112013-08-14 16:14:24 -07001280 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Mathieu Chartiera1602f22014-01-13 17:19:19 -08001281 if (space->IsContinuousMemMapAllocSpace()) {
1282 space::ContinuousMemMapAllocSpace* alloc_space = space->AsContinuousMemMapAllocSpace();
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001283 TimingLogger::ScopedTiming split(
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -07001284 alloc_space->IsZygoteSpace() ? "SweepZygoteSpace" : "SweepMallocSpace",
1285 GetTimings());
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07001286 RecordFree(alloc_space->Sweep(swap_bitmaps));
Carl Shapiro58551df2011-07-24 03:09:51 -07001287 }
1288 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001289 SweepLargeObjects(swap_bitmaps);
Carl Shapiro58551df2011-07-24 03:09:51 -07001290}
1291
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001292void MarkSweep::SweepLargeObjects(bool swap_bitmaps) {
Mathieu Chartier2dbe6272014-09-16 10:43:23 -07001293 space::LargeObjectSpace* los = heap_->GetLargeObjectsSpace();
1294 if (los != nullptr) {
1295 TimingLogger::ScopedTiming split(__FUNCTION__, GetTimings());
1296 RecordFreeLOS(los->Sweep(swap_bitmaps));
1297 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001298}
1299
Mathieu Chartier407f7022014-02-18 14:37:05 -08001300// Process the "referent" field in a java.lang.ref.Reference. If the referent has not yet been
1301// marked, put it on the appropriate list in the heap for later processing.
1302void MarkSweep::DelayReferenceReferent(mirror::Class* klass, mirror::Reference* ref) {
Mathieu Chartier97509952015-07-13 14:35:43 -07001303 heap_->GetReferenceProcessor()->DelayReferenceReferent(klass, ref, this);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001304}
1305
Mathieu Chartier97509952015-07-13 14:35:43 -07001306class MarkVisitor {
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001307 public:
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -07001308 ALWAYS_INLINE explicit MarkVisitor(MarkSweep* const mark_sweep) : mark_sweep_(mark_sweep) {}
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001309
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -07001310 ALWAYS_INLINE void operator()(mirror::Object* obj,
1311 MemberOffset offset,
1312 bool is_static ATTRIBUTE_UNUSED) const
1313 REQUIRES(Locks::heap_bitmap_lock_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001314 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001315 if (kCheckLocks) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001316 Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
1317 Locks::heap_bitmap_lock_->AssertExclusiveHeld(Thread::Current());
1318 }
Hiroshi Yamauchieb2baaf2015-05-13 21:14:22 -07001319 mark_sweep_->MarkObject(obj->GetFieldObject<mirror::Object>(offset), obj, offset);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001320 }
1321
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001322 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -07001323 REQUIRES(Locks::heap_bitmap_lock_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001324 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001325 if (!root->IsNull()) {
1326 VisitRoot(root);
1327 }
1328 }
1329
1330 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -07001331 REQUIRES(Locks::heap_bitmap_lock_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001332 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001333 if (kCheckLocks) {
1334 Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
1335 Locks::heap_bitmap_lock_->AssertExclusiveHeld(Thread::Current());
1336 }
1337 mark_sweep_->MarkObject(root->AsMirrorPtr());
1338 }
1339
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001340 private:
1341 MarkSweep* const mark_sweep_;
1342};
1343
Carl Shapiro69759ea2011-07-21 18:13:35 -07001344// Scans an object reference. Determines the type of the reference
1345// and dispatches to a specialized scanning routine.
Mathieu Chartier97509952015-07-13 14:35:43 -07001346void MarkSweep::ScanObject(mirror::Object* obj) {
1347 MarkVisitor mark_visitor(this);
Mathieu Chartier407f7022014-02-18 14:37:05 -08001348 DelayReferenceReferentVisitor ref_visitor(this);
1349 ScanObjectVisit(obj, mark_visitor, ref_visitor);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001350}
1351
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001352void MarkSweep::ProcessMarkStackParallel(size_t thread_count) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001353 Thread* self = Thread::Current();
1354 ThreadPool* thread_pool = GetHeap()->GetThreadPool();
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001355 const size_t chunk_size = std::min(mark_stack_->Size() / thread_count + 1,
1356 static_cast<size_t>(MarkStackTask<false>::kMaxSize));
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001357 CHECK_GT(chunk_size, 0U);
1358 // Split the current mark stack up into work tasks.
Mathieu Chartiercb535da2015-01-23 13:50:03 -08001359 for (auto* it = mark_stack_->Begin(), *end = mark_stack_->End(); it < end; ) {
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001360 const size_t delta = std::min(static_cast<size_t>(end - it), chunk_size);
Mathieu Chartier0e54cd02014-03-20 12:41:23 -07001361 thread_pool->AddTask(self, new MarkStackTask<false>(thread_pool, this, delta, it));
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001362 it += delta;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001363 }
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001364 thread_pool->SetMaxActiveWorkers(thread_count - 1);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001365 thread_pool->StartWorkers(self);
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001366 thread_pool->Wait(self, true, true);
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001367 thread_pool->StopWorkers(self);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001368 mark_stack_->Reset();
Ian Rogers3e5cf302014-05-20 16:40:37 -07001369 CHECK_EQ(work_chunks_created_.LoadSequentiallyConsistent(),
1370 work_chunks_deleted_.LoadSequentiallyConsistent())
1371 << " some of the work chunks were leaked";
Carl Shapiro69759ea2011-07-21 18:13:35 -07001372}
1373
Ian Rogers5d76c432011-10-31 21:42:49 -07001374// Scan anything that's on the mark stack.
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001375void MarkSweep::ProcessMarkStack(bool paused) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001376 TimingLogger::ScopedTiming t(paused ? "(Paused)ProcessMarkStack" : __FUNCTION__, GetTimings());
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001377 size_t thread_count = GetThreadCount(paused);
1378 if (kParallelProcessMarkStack && thread_count > 1 &&
1379 mark_stack_->Size() >= kMinimumParallelMarkStackSize) {
1380 ProcessMarkStackParallel(thread_count);
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001381 } else {
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001382 // TODO: Tune this.
1383 static const size_t kFifoSize = 4;
Mathieu Chartier97509952015-07-13 14:35:43 -07001384 BoundedFifoPowerOfTwo<mirror::Object*, kFifoSize> prefetch_fifo;
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001385 for (;;) {
Mathieu Chartier97509952015-07-13 14:35:43 -07001386 mirror::Object* obj = nullptr;
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001387 if (kUseMarkStackPrefetch) {
1388 while (!mark_stack_->IsEmpty() && prefetch_fifo.size() < kFifoSize) {
Mathieu Chartier97509952015-07-13 14:35:43 -07001389 mirror::Object* mark_stack_obj = mark_stack_->PopBack();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001390 DCHECK(mark_stack_obj != nullptr);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001391 __builtin_prefetch(mark_stack_obj);
1392 prefetch_fifo.push_back(mark_stack_obj);
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001393 }
1394 if (prefetch_fifo.empty()) {
1395 break;
1396 }
1397 obj = prefetch_fifo.front();
1398 prefetch_fifo.pop_front();
1399 } else {
1400 if (mark_stack_->IsEmpty()) {
1401 break;
1402 }
1403 obj = mark_stack_->PopBack();
1404 }
Mathieu Chartier4aeec172014-03-27 16:09:46 -07001405 DCHECK(obj != nullptr);
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001406 ScanObject(obj);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001407 }
1408 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001409}
1410
Mathieu Chartier97509952015-07-13 14:35:43 -07001411inline mirror::Object* MarkSweep::IsMarked(mirror::Object* object) {
Mathieu Chartier763a31e2015-11-16 16:05:55 -08001412 if (immune_spaces_.IsInImmuneRegion(object)) {
Mathieu Chartier97509952015-07-13 14:35:43 -07001413 return object;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001414 }
Mathieu Chartier0e54cd02014-03-20 12:41:23 -07001415 if (current_space_bitmap_->HasAddress(object)) {
Mathieu Chartier97509952015-07-13 14:35:43 -07001416 return current_space_bitmap_->Test(object) ? object : nullptr;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001417 }
Mathieu Chartier97509952015-07-13 14:35:43 -07001418 return mark_bitmap_->Test(object) ? object : nullptr;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001419}
1420
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001421void MarkSweep::FinishPhase() {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001422 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001423 if (kCountScannedTypes) {
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07001424 VLOG(gc)
1425 << "MarkSweep scanned"
1426 << " no reference objects=" << no_reference_class_count_.LoadRelaxed()
1427 << " normal objects=" << normal_count_.LoadRelaxed()
1428 << " classes=" << class_count_.LoadRelaxed()
1429 << " object arrays=" << object_array_count_.LoadRelaxed()
1430 << " references=" << reference_count_.LoadRelaxed()
1431 << " other=" << other_count_.LoadRelaxed();
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001432 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001433 if (kCountTasks) {
Ian Rogers3e5cf302014-05-20 16:40:37 -07001434 VLOG(gc) << "Total number of work chunks allocated: " << work_chunks_created_.LoadRelaxed();
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001435 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001436 if (kMeasureOverhead) {
Ian Rogers3e5cf302014-05-20 16:40:37 -07001437 VLOG(gc) << "Overhead time " << PrettyDuration(overhead_time_.LoadRelaxed());
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001438 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001439 if (kProfileLargeObjects) {
Ian Rogers3e5cf302014-05-20 16:40:37 -07001440 VLOG(gc) << "Large objects tested " << large_object_test_.LoadRelaxed()
1441 << " marked " << large_object_mark_.LoadRelaxed();
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001442 }
Mathieu Chartier0e54cd02014-03-20 12:41:23 -07001443 if (kCountMarkedObjects) {
Ian Rogers3e5cf302014-05-20 16:40:37 -07001444 VLOG(gc) << "Marked: null=" << mark_null_count_.LoadRelaxed()
1445 << " immune=" << mark_immune_count_.LoadRelaxed()
1446 << " fastpath=" << mark_fastpath_count_.LoadRelaxed()
1447 << " slowpath=" << mark_slowpath_count_.LoadRelaxed();
Mathieu Chartier0e54cd02014-03-20 12:41:23 -07001448 }
Mathieu Chartier4aeec172014-03-27 16:09:46 -07001449 CHECK(mark_stack_->IsEmpty()); // Ensure that the mark stack is empty.
Mathieu Chartier5301cd22012-05-31 12:11:36 -07001450 mark_stack_->Reset();
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -08001451 Thread* const self = Thread::Current();
1452 ReaderMutexLock mu(self, *Locks::mutator_lock_);
1453 WriterMutexLock mu2(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier4aeec172014-03-27 16:09:46 -07001454 heap_->ClearMarkedObjects();
Carl Shapiro69759ea2011-07-21 18:13:35 -07001455}
1456
Hiroshi Yamauchic93c5302014-03-20 16:15:37 -07001457void MarkSweep::RevokeAllThreadLocalBuffers() {
1458 if (kRevokeRosAllocThreadLocalBuffersAtCheckpoint && IsConcurrent()) {
1459 // If concurrent, rosalloc thread-local buffers are revoked at the
1460 // thread checkpoint. Bump pointer space thread-local buffers must
1461 // not be in use.
1462 GetHeap()->AssertAllBumpPointerSpaceThreadLocalBuffersAreRevoked();
1463 } else {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001464 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Hiroshi Yamauchic93c5302014-03-20 16:15:37 -07001465 GetHeap()->RevokeAllThreadLocalBuffers();
Hiroshi Yamauchic93c5302014-03-20 16:15:37 -07001466 }
1467}
1468
Ian Rogers1d54e732013-05-02 21:10:01 -07001469} // namespace collector
1470} // namespace gc
Carl Shapiro69759ea2011-07-21 18:13:35 -07001471} // namespace art