blob: e2761370332601d749abcc657d8f5dfaed618801 [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_)
278 SHARED_REQUIRES(Locks::mutator_lock_) {
279 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)))) {
Mathieu Chartier175746a2015-05-01 13:00:23 -0700416 LOG(INTERNAL_FATAL) << "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_);
Hiroshi Yamauchid0c84122015-05-15 15:23:30 -0700420 LOG(INTERNAL_FATAL) << "Field info: "
421 << " 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()
439 : holder_->GetClass()->NumReferenceInstanceFields())
440 << "\n";
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -0700441 // Print the memory content of the holder.
442 for (size_t i = 0; i < holder_size / sizeof(uint32_t); ++i) {
443 uint32_t* p = reinterpret_cast<uint32_t*>(holder_);
444 LOG(INTERNAL_FATAL) << &p[i] << ": " << "holder+" << (i * sizeof(uint32_t)) << " = "
445 << std::hex << p[i];
446 }
Hiroshi Yamauchieb2baaf2015-05-13 21:14:22 -0700447 }
Hiroshi Yamauchid38ec802015-05-01 11:50:24 -0700448 PrintFileToLog("/proc/self/maps", LogSeverity::INTERNAL_FATAL);
Vladimir Marko17a924a2015-05-08 15:17:32 +0100449 MemMap::DumpMaps(LOG(INTERNAL_FATAL), true);
Mathieu Chartierf8a86b92016-06-14 17:08:47 -0700450 LOG(INTERNAL_FATAL) << "Attempting see if it's a bad thread root\n";
451 mark_sweep_->VerifySuspendedThreadRoots();
Mathieu Chartierbbd695c2014-04-16 09:48:48 -0700452 LOG(FATAL) << "Can't mark invalid object";
453 }
454 }
455
456 private:
457 MarkSweep* const mark_sweep_;
Hiroshi Yamauchieb2baaf2015-05-13 21:14:22 -0700458 mirror::Object* const holder_;
459 MemberOffset offset_;
Mathieu Chartierbbd695c2014-04-16 09:48:48 -0700460};
461
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -0700462inline void MarkSweep::MarkObjectNonNull(mirror::Object* obj,
463 mirror::Object* holder,
Mathieu Chartier97509952015-07-13 14:35:43 -0700464 MemberOffset offset) {
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700465 DCHECK(obj != nullptr);
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -0700466 if (kUseBakerOrBrooksReadBarrier) {
467 // Verify all the objects have the correct pointer installed.
468 obj->AssertReadBarrierPointer();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800469 }
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800470 if (immune_spaces_.IsInImmuneRegion(obj)) {
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700471 if (kCountMarkedObjects) {
472 ++mark_immune_count_;
473 }
Mathieu Chartierbbd695c2014-04-16 09:48:48 -0700474 DCHECK(mark_bitmap_->Test(obj));
475 } else if (LIKELY(current_space_bitmap_->HasAddress(obj))) {
476 if (kCountMarkedObjects) {
477 ++mark_fastpath_count_;
478 }
479 if (UNLIKELY(!current_space_bitmap_->Set(obj))) {
480 PushOnMarkStack(obj); // This object was not previously marked.
481 }
482 } else {
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700483 if (kCountMarkedObjects) {
484 ++mark_slowpath_count_;
485 }
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700486 MarkObjectSlowPath visitor(this, holder, offset);
Mathieu Chartierbbd695c2014-04-16 09:48:48 -0700487 // TODO: We already know that the object is not in the current_space_bitmap_ but MarkBitmap::Set
488 // will check again.
489 if (!mark_bitmap_->Set(obj, visitor)) {
490 PushOnMarkStack(obj); // Was not already marked, push.
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700491 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700492 }
493}
494
Mathieu Chartier97509952015-07-13 14:35:43 -0700495inline void MarkSweep::PushOnMarkStack(mirror::Object* obj) {
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700496 if (UNLIKELY(mark_stack_->Size() >= mark_stack_->Capacity())) {
497 // Lock is not needed but is here anyways to please annotalysis.
498 MutexLock mu(Thread::Current(), mark_stack_lock_);
499 ExpandMarkStack();
500 }
501 // The object must be pushed on to the mark stack.
502 mark_stack_->PushBack(obj);
503}
504
Mathieu Chartier97509952015-07-13 14:35:43 -0700505inline bool MarkSweep::MarkObjectParallel(mirror::Object* obj) {
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700506 DCHECK(obj != nullptr);
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -0700507 if (kUseBakerOrBrooksReadBarrier) {
508 // Verify all the objects have the correct pointer installed.
509 obj->AssertReadBarrierPointer();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800510 }
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800511 if (immune_spaces_.IsInImmuneRegion(obj)) {
Mathieu Chartier97509952015-07-13 14:35:43 -0700512 DCHECK(IsMarked(obj) != nullptr);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700513 return false;
514 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700515 // Try to take advantage of locality of references within a space, failing this find the space
516 // the hard way.
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -0700517 accounting::ContinuousSpaceBitmap* object_bitmap = current_space_bitmap_;
Mathieu Chartierbbd695c2014-04-16 09:48:48 -0700518 if (LIKELY(object_bitmap->HasAddress(obj))) {
519 return !object_bitmap->AtomicTestAndSet(obj);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700520 }
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700521 MarkObjectSlowPath visitor(this);
Mathieu Chartierbbd695c2014-04-16 09:48:48 -0700522 return !mark_bitmap_->AtomicTestAndSet(obj, visitor);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700523}
524
Mathieu Chartier97509952015-07-13 14:35:43 -0700525void MarkSweep::MarkHeapReference(mirror::HeapReference<mirror::Object>* ref) {
526 MarkObject(ref->AsMirrorPtr(), nullptr, MemberOffset(0));
527}
528
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700529// 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 -0700530inline void MarkSweep::MarkObject(mirror::Object* obj,
531 mirror::Object* holder,
Mathieu Chartier97509952015-07-13 14:35:43 -0700532 MemberOffset offset) {
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700533 if (obj != nullptr) {
Hiroshi Yamauchieb2baaf2015-05-13 21:14:22 -0700534 MarkObjectNonNull(obj, holder, offset);
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700535 } else if (kCountMarkedObjects) {
536 ++mark_null_count_;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700537 }
538}
539
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700540class MarkSweep::VerifyRootMarkedVisitor : public SingleRootVisitor {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700541 public:
542 explicit VerifyRootMarkedVisitor(MarkSweep* collector) : collector_(collector) { }
543
544 void VisitRoot(mirror::Object* root, const RootInfo& info) OVERRIDE
Mathieu Chartier90443472015-07-16 20:32:27 -0700545 SHARED_REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mathieu Chartier97509952015-07-13 14:35:43 -0700546 CHECK(collector_->IsMarked(root) != nullptr) << info.ToString();
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700547 }
548
549 private:
550 MarkSweep* const collector_;
551};
552
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -0700553void MarkSweep::VisitRoots(mirror::Object*** roots,
554 size_t count,
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700555 const RootInfo& info ATTRIBUTE_UNUSED) {
556 for (size_t i = 0; i < count; ++i) {
557 MarkObjectNonNull(*roots[i]);
558 }
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800559}
560
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -0700561void MarkSweep::VisitRoots(mirror::CompressedReference<mirror::Object>** roots,
562 size_t count,
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700563 const RootInfo& info ATTRIBUTE_UNUSED) {
564 for (size_t i = 0; i < count; ++i) {
565 MarkObjectNonNull(roots[i]->AsMirrorPtr());
566 }
Mathieu Chartier893263b2014-03-04 11:07:42 -0800567}
568
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700569class MarkSweep::VerifyRootVisitor : public SingleRootVisitor {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700570 public:
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700571 void VisitRoot(mirror::Object* root, const RootInfo& info) OVERRIDE
Mathieu Chartier90443472015-07-16 20:32:27 -0700572 SHARED_REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mathieu Chartier9086b652015-04-14 09:35:18 -0700573 // See if the root is on any space bitmap.
574 auto* heap = Runtime::Current()->GetHeap();
575 if (heap->GetLiveBitmap()->GetContinuousSpaceBitmap(root) == nullptr) {
576 space::LargeObjectSpace* large_object_space = heap->GetLargeObjectsSpace();
577 if (large_object_space != nullptr && !large_object_space->Contains(root)) {
Mathieu Chartierf8a86b92016-06-14 17:08:47 -0700578 LOG(INTERNAL_FATAL) << "Found invalid root: " << root << " " << info << "\n";
Mathieu Chartier9086b652015-04-14 09:35:18 -0700579 }
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700580 }
581 }
Mathieu Chartier9086b652015-04-14 09:35:18 -0700582};
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700583
Mathieu Chartierf8a86b92016-06-14 17:08:47 -0700584void MarkSweep::VerifySuspendedThreadRoots() {
Mathieu Chartier9086b652015-04-14 09:35:18 -0700585 VerifyRootVisitor visitor;
Mathieu Chartierf8a86b92016-06-14 17:08:47 -0700586 Runtime::Current()->GetThreadList()->VisitRootsForSuspendedThreads(&visitor);
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700587}
588
Mathieu Chartier893263b2014-03-04 11:07:42 -0800589void MarkSweep::MarkRoots(Thread* self) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700590 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Mathieu Chartier893263b2014-03-04 11:07:42 -0800591 if (Locks::mutator_lock_->IsExclusiveHeld(self)) {
592 // If we exclusively hold the mutator lock, all threads must be suspended.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700593 Runtime::Current()->VisitRoots(this);
Mathieu Chartier893263b2014-03-04 11:07:42 -0800594 RevokeAllThreadLocalAllocationStacks(self);
595 } else {
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -0700596 MarkRootsCheckpoint(self, kRevokeRosAllocThreadLocalBuffersAtCheckpoint);
Mathieu Chartier893263b2014-03-04 11:07:42 -0800597 // At this point the live stack should no longer have any mutators which push into it.
598 MarkNonThreadRoots();
599 MarkConcurrentRoots(
600 static_cast<VisitRootFlags>(kVisitRootFlagAllRoots | kVisitRootFlagStartLoggingNewRoots));
601 }
Mathieu Chartier9ebae1f2012-10-15 17:38:16 -0700602}
603
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700604void MarkSweep::MarkNonThreadRoots() {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700605 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700606 Runtime::Current()->VisitNonThreadRoots(this);
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700607}
608
Mathieu Chartier893263b2014-03-04 11:07:42 -0800609void MarkSweep::MarkConcurrentRoots(VisitRootFlags flags) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700610 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Ian Rogers1d54e732013-05-02 21:10:01 -0700611 // Visit all runtime roots and clear dirty flags.
Mathieu Chartier4edd8472015-06-01 10:47:36 -0700612 Runtime::Current()->VisitConcurrentRoots(
613 this, static_cast<VisitRootFlags>(flags | kVisitRootFlagNonMoving));
Carl Shapiro69759ea2011-07-21 18:13:35 -0700614}
615
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700616class MarkSweep::DelayReferenceReferentVisitor {
Mathieu Chartier407f7022014-02-18 14:37:05 -0800617 public:
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -0700618 explicit DelayReferenceReferentVisitor(MarkSweep* collector) : collector_(collector) {}
Mathieu Chartier407f7022014-02-18 14:37:05 -0800619
620 void operator()(mirror::Class* klass, mirror::Reference* ref) const
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -0700621 REQUIRES(Locks::heap_bitmap_lock_)
622 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartier407f7022014-02-18 14:37:05 -0800623 collector_->DelayReferenceReferent(klass, ref);
624 }
625
626 private:
627 MarkSweep* const collector_;
628};
629
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700630template <bool kUseFinger = false>
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700631class MarkSweep::MarkStackTask : public Task {
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700632 public:
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -0700633 MarkStackTask(ThreadPool* thread_pool,
634 MarkSweep* mark_sweep,
635 size_t mark_stack_size,
Mathieu Chartier97509952015-07-13 14:35:43 -0700636 StackReference<mirror::Object>* mark_stack)
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700637 : mark_sweep_(mark_sweep),
638 thread_pool_(thread_pool),
639 mark_stack_pos_(mark_stack_size) {
640 // We may have to copy part of an existing mark stack when another mark stack overflows.
641 if (mark_stack_size != 0) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700642 DCHECK(mark_stack != nullptr);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700643 // TODO: Check performance?
644 std::copy(mark_stack, mark_stack + mark_stack_size, mark_stack_);
Ian Rogers1d54e732013-05-02 21:10:01 -0700645 }
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700646 if (kCountTasks) {
647 ++mark_sweep_->work_chunks_created_;
648 }
649 }
650
651 static const size_t kMaxSize = 1 * KB;
652
653 protected:
Mathieu Chartier407f7022014-02-18 14:37:05 -0800654 class MarkObjectParallelVisitor {
655 public:
Roland Levillain3887c462015-08-12 18:15:42 +0100656 ALWAYS_INLINE MarkObjectParallelVisitor(MarkStackTask<kUseFinger>* chunk_task,
657 MarkSweep* mark_sweep)
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700658 : chunk_task_(chunk_task), mark_sweep_(mark_sweep) {}
Mathieu Chartier407f7022014-02-18 14:37:05 -0800659
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -0700660 ALWAYS_INLINE void operator()(mirror::Object* obj,
661 MemberOffset offset,
662 bool is_static ATTRIBUTE_UNUSED) const
663 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700664 Mark(obj->GetFieldObject<mirror::Object>(offset));
665 }
666
667 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
Mathieu Chartier90443472015-07-16 20:32:27 -0700668 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700669 if (!root->IsNull()) {
670 VisitRoot(root);
671 }
672 }
673
674 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
675 SHARED_REQUIRES(Locks::mutator_lock_) {
676 if (kCheckLocks) {
677 Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
678 Locks::heap_bitmap_lock_->AssertExclusiveHeld(Thread::Current());
679 }
680 Mark(root->AsMirrorPtr());
681 }
682
683 private:
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -0700684 ALWAYS_INLINE void Mark(mirror::Object* ref) const SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartier407f7022014-02-18 14:37:05 -0800685 if (ref != nullptr && mark_sweep_->MarkObjectParallel(ref)) {
686 if (kUseFinger) {
Yabin Cuic7df66e2015-04-15 15:40:18 -0700687 std::atomic_thread_fence(std::memory_order_seq_cst);
Mathieu Chartier407f7022014-02-18 14:37:05 -0800688 if (reinterpret_cast<uintptr_t>(ref) >=
Ian Rogers3e5cf302014-05-20 16:40:37 -0700689 static_cast<uintptr_t>(mark_sweep_->atomic_finger_.LoadRelaxed())) {
Mathieu Chartier407f7022014-02-18 14:37:05 -0800690 return;
691 }
692 }
693 chunk_task_->MarkStackPush(ref);
694 }
695 }
696
Mathieu Chartier407f7022014-02-18 14:37:05 -0800697 MarkStackTask<kUseFinger>* const chunk_task_;
698 MarkSweep* const mark_sweep_;
699 };
700
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700701 class ScanObjectParallelVisitor {
702 public:
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -0700703 ALWAYS_INLINE explicit ScanObjectParallelVisitor(MarkStackTask<kUseFinger>* chunk_task)
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700704 : chunk_task_(chunk_task) {}
705
Mathieu Chartier407f7022014-02-18 14:37:05 -0800706 // No thread safety analysis since multiple threads will use this visitor.
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -0700707 void operator()(mirror::Object* obj) const
708 REQUIRES(Locks::heap_bitmap_lock_)
709 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartier407f7022014-02-18 14:37:05 -0800710 MarkSweep* const mark_sweep = chunk_task_->mark_sweep_;
711 MarkObjectParallelVisitor mark_visitor(chunk_task_, mark_sweep);
712 DelayReferenceReferentVisitor ref_visitor(mark_sweep);
713 mark_sweep->ScanObjectVisit(obj, mark_visitor, ref_visitor);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700714 }
715
716 private:
717 MarkStackTask<kUseFinger>* const chunk_task_;
718 };
719
720 virtual ~MarkStackTask() {
721 // Make sure that we have cleared our mark stack.
722 DCHECK_EQ(mark_stack_pos_, 0U);
723 if (kCountTasks) {
724 ++mark_sweep_->work_chunks_deleted_;
725 }
726 }
727
728 MarkSweep* const mark_sweep_;
729 ThreadPool* const thread_pool_;
730 // Thread local mark stack for this task.
Mathieu Chartier97509952015-07-13 14:35:43 -0700731 StackReference<mirror::Object> mark_stack_[kMaxSize];
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700732 // Mark stack position.
733 size_t mark_stack_pos_;
734
Mathieu Chartier97509952015-07-13 14:35:43 -0700735 ALWAYS_INLINE void MarkStackPush(mirror::Object* obj)
Mathieu Chartier90443472015-07-16 20:32:27 -0700736 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700737 if (UNLIKELY(mark_stack_pos_ == kMaxSize)) {
738 // Mark stack overflow, give 1/2 the stack to the thread pool as a new work task.
739 mark_stack_pos_ /= 2;
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -0700740 auto* task = new MarkStackTask(thread_pool_,
741 mark_sweep_,
742 kMaxSize - mark_stack_pos_,
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700743 mark_stack_ + mark_stack_pos_);
744 thread_pool_->AddTask(Thread::Current(), task);
745 }
746 DCHECK(obj != nullptr);
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700747 DCHECK_LT(mark_stack_pos_, kMaxSize);
Mathieu Chartiercb535da2015-01-23 13:50:03 -0800748 mark_stack_[mark_stack_pos_++].Assign(obj);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700749 }
750
751 virtual void Finalize() {
752 delete this;
753 }
754
755 // Scans all of the objects
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -0700756 virtual void Run(Thread* self ATTRIBUTE_UNUSED)
757 REQUIRES(Locks::heap_bitmap_lock_)
758 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700759 ScanObjectParallelVisitor visitor(this);
760 // TODO: Tune this.
761 static const size_t kFifoSize = 4;
Mathieu Chartier97509952015-07-13 14:35:43 -0700762 BoundedFifoPowerOfTwo<mirror::Object*, kFifoSize> prefetch_fifo;
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700763 for (;;) {
Mathieu Chartier97509952015-07-13 14:35:43 -0700764 mirror::Object* obj = nullptr;
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700765 if (kUseMarkStackPrefetch) {
766 while (mark_stack_pos_ != 0 && prefetch_fifo.size() < kFifoSize) {
Mathieu Chartier97509952015-07-13 14:35:43 -0700767 mirror::Object* const mark_stack_obj = mark_stack_[--mark_stack_pos_].AsMirrorPtr();
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800768 DCHECK(mark_stack_obj != nullptr);
769 __builtin_prefetch(mark_stack_obj);
770 prefetch_fifo.push_back(mark_stack_obj);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700771 }
772 if (UNLIKELY(prefetch_fifo.empty())) {
773 break;
774 }
775 obj = prefetch_fifo.front();
776 prefetch_fifo.pop_front();
777 } else {
778 if (UNLIKELY(mark_stack_pos_ == 0)) {
779 break;
780 }
Mathieu Chartiercb535da2015-01-23 13:50:03 -0800781 obj = mark_stack_[--mark_stack_pos_].AsMirrorPtr();
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700782 }
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700783 DCHECK(obj != nullptr);
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700784 visitor(obj);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700785 }
786 }
787};
788
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700789class MarkSweep::CardScanTask : public MarkStackTask<false> {
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700790 public:
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -0700791 CardScanTask(ThreadPool* thread_pool,
792 MarkSweep* mark_sweep,
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -0700793 accounting::ContinuousSpaceBitmap* bitmap,
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -0700794 uint8_t* begin,
795 uint8_t* end,
796 uint8_t minimum_age,
797 size_t mark_stack_size,
798 StackReference<mirror::Object>* mark_stack_obj,
799 bool clear_card)
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700800 : MarkStackTask<false>(thread_pool, mark_sweep, mark_stack_size, mark_stack_obj),
801 bitmap_(bitmap),
802 begin_(begin),
803 end_(end),
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -0700804 minimum_age_(minimum_age),
805 clear_card_(clear_card) {}
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700806
807 protected:
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -0700808 accounting::ContinuousSpaceBitmap* const bitmap_;
Ian Rogers13735952014-10-08 12:43:28 -0700809 uint8_t* const begin_;
810 uint8_t* const end_;
811 const uint8_t minimum_age_;
Lei Li727b2942015-01-15 11:26:34 +0800812 const bool clear_card_;
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700813
814 virtual void Finalize() {
815 delete this;
816 }
817
818 virtual void Run(Thread* self) NO_THREAD_SAFETY_ANALYSIS {
819 ScanObjectParallelVisitor visitor(this);
820 accounting::CardTable* card_table = mark_sweep_->GetHeap()->GetCardTable();
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -0700821 size_t cards_scanned = clear_card_
822 ? card_table->Scan<true>(bitmap_, begin_, end_, visitor, minimum_age_)
823 : card_table->Scan<false>(bitmap_, begin_, end_, visitor, minimum_age_);
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700824 VLOG(heap) << "Parallel scanning cards " << reinterpret_cast<void*>(begin_) << " - "
825 << reinterpret_cast<void*>(end_) << " = " << cards_scanned;
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700826 // Finish by emptying our local mark stack.
827 MarkStackTask::Run(self);
828 }
829};
830
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700831size_t MarkSweep::GetThreadCount(bool paused) const {
Mathieu Chartierf8cb1782016-03-18 18:45:41 -0700832 // Use less threads if we are in a background state (non jank perceptible) since we want to leave
833 // more CPU time for the foreground apps.
834 if (heap_->GetThreadPool() == nullptr || !Runtime::Current()->InJankPerceptibleProcessState()) {
Mathieu Chartierbbd695c2014-04-16 09:48:48 -0700835 return 1;
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700836 }
Mathieu Chartier10d68862015-04-15 14:21:33 -0700837 return (paused ? heap_->GetParallelGCThreadCount() : heap_->GetConcGCThreadCount()) + 1;
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700838}
839
Ian Rogers13735952014-10-08 12:43:28 -0700840void MarkSweep::ScanGrayObjects(bool paused, uint8_t minimum_age) {
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700841 accounting::CardTable* card_table = GetHeap()->GetCardTable();
842 ThreadPool* thread_pool = GetHeap()->GetThreadPool();
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700843 size_t thread_count = GetThreadCount(paused);
844 // The parallel version with only one thread is faster for card scanning, TODO: fix.
Mathieu Chartierbbd695c2014-04-16 09:48:48 -0700845 if (kParallelCardScan && thread_count > 1) {
Mathieu Chartier720ef762013-08-17 14:46:54 -0700846 Thread* self = Thread::Current();
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700847 // Can't have a different split for each space since multiple spaces can have their cards being
848 // scanned at the same time.
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700849 TimingLogger::ScopedTiming t(paused ? "(Paused)ScanGrayObjects" : __FUNCTION__,
850 GetTimings());
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700851 // 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 -0700852 StackReference<mirror::Object>* mark_stack_begin = mark_stack_->Begin();
853 StackReference<mirror::Object>* mark_stack_end = mark_stack_->End();
Mathieu Chartier720ef762013-08-17 14:46:54 -0700854 const size_t mark_stack_size = mark_stack_end - mark_stack_begin;
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700855 // Estimated number of work tasks we will create.
856 const size_t mark_stack_tasks = GetHeap()->GetContinuousSpaces().size() * thread_count;
857 DCHECK_NE(mark_stack_tasks, 0U);
858 const size_t mark_stack_delta = std::min(CardScanTask::kMaxSize / 2,
859 mark_stack_size / mark_stack_tasks + 1);
860 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700861 if (space->GetMarkBitmap() == nullptr) {
862 continue;
863 }
Ian Rogers13735952014-10-08 12:43:28 -0700864 uint8_t* card_begin = space->Begin();
865 uint8_t* card_end = space->End();
Hiroshi Yamauchi0941b042013-11-05 11:34:03 -0800866 // Align up the end address. For example, the image space's end
867 // may not be card-size-aligned.
868 card_end = AlignUp(card_end, accounting::CardTable::kCardSize);
Roland Levillain14d90572015-07-16 10:52:26 +0100869 DCHECK_ALIGNED(card_begin, accounting::CardTable::kCardSize);
870 DCHECK_ALIGNED(card_end, accounting::CardTable::kCardSize);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700871 // Calculate how many bytes of heap we will scan,
872 const size_t address_range = card_end - card_begin;
873 // Calculate how much address range each task gets.
874 const size_t card_delta = RoundUp(address_range / thread_count + 1,
875 accounting::CardTable::kCardSize);
Lei Li727b2942015-01-15 11:26:34 +0800876 // If paused and the space is neither zygote nor image space, we could clear the dirty
877 // cards to avoid accumulating them to increase card scanning load in the following GC
878 // cycles. We need to keep dirty cards of image space and zygote space in order to track
879 // references to the other spaces.
880 bool clear_card = paused && !space->IsZygoteSpace() && !space->IsImageSpace();
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700881 // Create the worker tasks for this space.
882 while (card_begin != card_end) {
883 // Add a range of cards.
884 size_t addr_remaining = card_end - card_begin;
885 size_t card_increment = std::min(card_delta, addr_remaining);
886 // Take from the back of the mark stack.
887 size_t mark_stack_remaining = mark_stack_end - mark_stack_begin;
888 size_t mark_stack_increment = std::min(mark_stack_delta, mark_stack_remaining);
889 mark_stack_end -= mark_stack_increment;
890 mark_stack_->PopBackCount(static_cast<int32_t>(mark_stack_increment));
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700891 DCHECK_EQ(mark_stack_end, mark_stack_->End());
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700892 // Add the new task to the thread pool.
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -0700893 auto* task = new CardScanTask(thread_pool,
894 this,
895 space->GetMarkBitmap(),
896 card_begin,
897 card_begin + card_increment,
898 minimum_age,
899 mark_stack_increment,
900 mark_stack_end,
901 clear_card);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700902 thread_pool->AddTask(self, task);
903 card_begin += card_increment;
904 }
905 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700906
Hiroshi Yamauchi0941b042013-11-05 11:34:03 -0800907 // Note: the card scan below may dirty new cards (and scan them)
908 // as a side effect when a Reference object is encountered and
909 // queued during the marking. See b/11465268.
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700910 thread_pool->SetMaxActiveWorkers(thread_count - 1);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700911 thread_pool->StartWorkers(self);
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700912 thread_pool->Wait(self, true, true);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700913 thread_pool->StopWorkers(self);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700914 } else {
915 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700916 if (space->GetMarkBitmap() != nullptr) {
917 // Image spaces are handled properly since live == marked for them.
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700918 const char* name = nullptr;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700919 switch (space->GetGcRetentionPolicy()) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700920 case space::kGcRetentionPolicyNeverCollect:
921 name = paused ? "(Paused)ScanGrayImageSpaceObjects" : "ScanGrayImageSpaceObjects";
922 break;
923 case space::kGcRetentionPolicyFullCollect:
924 name = paused ? "(Paused)ScanGrayZygoteSpaceObjects" : "ScanGrayZygoteSpaceObjects";
925 break;
926 case space::kGcRetentionPolicyAlwaysCollect:
927 name = paused ? "(Paused)ScanGrayAllocSpaceObjects" : "ScanGrayAllocSpaceObjects";
928 break;
929 default:
930 LOG(FATAL) << "Unreachable";
Ian Rogers2c4257b2014-10-24 14:20:06 -0700931 UNREACHABLE();
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700932 }
933 TimingLogger::ScopedTiming t(name, GetTimings());
Mathieu Chartier590fee92013-09-13 13:46:47 -0700934 ScanObjectVisitor visitor(this);
Lei Li727b2942015-01-15 11:26:34 +0800935 bool clear_card = paused && !space->IsZygoteSpace() && !space->IsImageSpace();
936 if (clear_card) {
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -0700937 card_table->Scan<true>(space->GetMarkBitmap(),
938 space->Begin(),
939 space->End(),
940 visitor,
Lei Li727b2942015-01-15 11:26:34 +0800941 minimum_age);
942 } else {
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -0700943 card_table->Scan<false>(space->GetMarkBitmap(),
944 space->Begin(),
945 space->End(),
946 visitor,
Lei Li727b2942015-01-15 11:26:34 +0800947 minimum_age);
948 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700949 }
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700950 }
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700951 }
952}
953
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700954class MarkSweep::RecursiveMarkTask : public MarkStackTask<false> {
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700955 public:
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -0700956 RecursiveMarkTask(ThreadPool* thread_pool,
957 MarkSweep* mark_sweep,
958 accounting::ContinuousSpaceBitmap* bitmap,
959 uintptr_t begin,
960 uintptr_t end)
961 : MarkStackTask<false>(thread_pool, mark_sweep, 0, nullptr),
962 bitmap_(bitmap),
963 begin_(begin),
964 end_(end) {}
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700965
966 protected:
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -0700967 accounting::ContinuousSpaceBitmap* const bitmap_;
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700968 const uintptr_t begin_;
969 const uintptr_t end_;
970
971 virtual void Finalize() {
972 delete this;
973 }
974
975 // Scans all of the objects
976 virtual void Run(Thread* self) NO_THREAD_SAFETY_ANALYSIS {
977 ScanObjectParallelVisitor visitor(this);
978 bitmap_->VisitMarkedRange(begin_, end_, visitor);
979 // Finish by emptying our local mark stack.
980 MarkStackTask::Run(self);
981 }
982};
983
Carl Shapiro58551df2011-07-24 03:09:51 -0700984// Populates the mark stack based on the set of marked objects and
985// recursively marks until the mark stack is emptied.
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800986void MarkSweep::RecursiveMark() {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700987 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Mathieu Chartiera1602f22014-01-13 17:19:19 -0800988 // RecursiveMark will build the lists of known instances of the Reference classes. See
989 // DelayReferenceReferent for details.
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700990 if (kUseRecursiveMark) {
991 const bool partial = GetGcType() == kGcTypePartial;
992 ScanObjectVisitor scan_visitor(this);
993 auto* self = Thread::Current();
994 ThreadPool* thread_pool = heap_->GetThreadPool();
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700995 size_t thread_count = GetThreadCount(false);
996 const bool parallel = kParallelRecursiveMark && thread_count > 1;
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700997 mark_stack_->Reset();
Mathieu Chartier02e25112013-08-14 16:14:24 -0700998 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700999 if ((space->GetGcRetentionPolicy() == space::kGcRetentionPolicyAlwaysCollect) ||
1000 (!partial && space->GetGcRetentionPolicy() == space::kGcRetentionPolicyFullCollect)) {
Mathieu Chartier0e54cd02014-03-20 12:41:23 -07001001 current_space_bitmap_ = space->GetMarkBitmap();
1002 if (current_space_bitmap_ == nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001003 continue;
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001004 }
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001005 if (parallel) {
1006 // We will use the mark stack the future.
1007 // CHECK(mark_stack_->IsEmpty());
1008 // This function does not handle heap end increasing, so we must use the space end.
1009 uintptr_t begin = reinterpret_cast<uintptr_t>(space->Begin());
1010 uintptr_t end = reinterpret_cast<uintptr_t>(space->End());
Ian Rogers3e5cf302014-05-20 16:40:37 -07001011 atomic_finger_.StoreRelaxed(AtomicInteger::MaxValue());
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001012
1013 // Create a few worker tasks.
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001014 const size_t n = thread_count * 2;
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001015 while (begin != end) {
1016 uintptr_t start = begin;
1017 uintptr_t delta = (end - begin) / n;
1018 delta = RoundUp(delta, KB);
1019 if (delta < 16 * KB) delta = end - begin;
1020 begin += delta;
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -07001021 auto* task = new RecursiveMarkTask(thread_pool,
1022 this,
1023 current_space_bitmap_,
1024 start,
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001025 begin);
1026 thread_pool->AddTask(self, task);
1027 }
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001028 thread_pool->SetMaxActiveWorkers(thread_count - 1);
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001029 thread_pool->StartWorkers(self);
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001030 thread_pool->Wait(self, true, true);
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001031 thread_pool->StopWorkers(self);
1032 } else {
1033 // This function does not handle heap end increasing, so we must use the space end.
1034 uintptr_t begin = reinterpret_cast<uintptr_t>(space->Begin());
1035 uintptr_t end = reinterpret_cast<uintptr_t>(space->End());
Mathieu Chartier0e54cd02014-03-20 12:41:23 -07001036 current_space_bitmap_->VisitMarkedRange(begin, end, scan_visitor);
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001037 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001038 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001039 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001040 }
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001041 ProcessMarkStack(false);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001042}
1043
Ian Rogers13735952014-10-08 12:43:28 -07001044void MarkSweep::RecursiveMarkDirtyObjects(bool paused, uint8_t minimum_age) {
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001045 ScanGrayObjects(paused, minimum_age);
1046 ProcessMarkStack(paused);
Mathieu Chartier262e5ff2012-06-01 17:35:38 -07001047}
1048
Carl Shapiro58551df2011-07-24 03:09:51 -07001049void MarkSweep::ReMarkRoots() {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001050 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Mathieu Chartier893263b2014-03-04 11:07:42 -08001051 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001052 Runtime::Current()->VisitRoots(this, static_cast<VisitRootFlags>(
1053 kVisitRootFlagNewRoots | kVisitRootFlagStopLoggingNewRoots | kVisitRootFlagClearRootLog));
Mathieu Chartier7bf9f192014-04-04 11:09:41 -07001054 if (kVerifyRootsMarked) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001055 TimingLogger::ScopedTiming t2("(Paused)VerifyRoots", GetTimings());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001056 VerifyRootMarkedVisitor visitor(this);
1057 Runtime::Current()->VisitRoots(&visitor);
Mathieu Chartier893263b2014-03-04 11:07:42 -08001058 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001059}
1060
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -07001061void MarkSweep::SweepSystemWeaks(Thread* self) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001062 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Mathieu Chartier14c3bf92015-07-13 14:35:43 -07001063 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier97509952015-07-13 14:35:43 -07001064 Runtime::Current()->SweepSystemWeaks(this);
Carl Shapiro58551df2011-07-24 03:09:51 -07001065}
1066
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001067class MarkSweep::VerifySystemWeakVisitor : public IsMarkedVisitor {
Mathieu Chartier97509952015-07-13 14:35:43 -07001068 public:
1069 explicit VerifySystemWeakVisitor(MarkSweep* mark_sweep) : mark_sweep_(mark_sweep) {}
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001070
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -07001071 virtual mirror::Object* IsMarked(mirror::Object* obj)
1072 OVERRIDE
Mathieu Chartier90443472015-07-16 20:32:27 -07001073 SHARED_REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mathieu Chartier97509952015-07-13 14:35:43 -07001074 mark_sweep_->VerifyIsLive(obj);
1075 return obj;
1076 }
1077
1078 MarkSweep* const mark_sweep_;
1079};
1080
1081void MarkSweep::VerifyIsLive(const mirror::Object* obj) {
Mathieu Chartier4aeec172014-03-27 16:09:46 -07001082 if (!heap_->GetLiveBitmap()->Test(obj)) {
Mathieu Chartiercb535da2015-01-23 13:50:03 -08001083 // TODO: Consider live stack? Has this code bitrotted?
1084 CHECK(!heap_->allocation_stack_->Contains(obj))
1085 << "Found dead object " << obj << "\n" << heap_->DumpSpaces();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001086 }
1087}
1088
1089void MarkSweep::VerifySystemWeaks() {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001090 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001091 // Verify system weaks, uses a special object visitor which returns the input object.
Mathieu Chartier97509952015-07-13 14:35:43 -07001092 VerifySystemWeakVisitor visitor(this);
1093 Runtime::Current()->SweepSystemWeaks(&visitor);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001094}
1095
Mathieu Chartiera07f5592016-06-16 11:44:28 -07001096class MarkSweep::CheckpointMarkThreadRoots : public Closure, public RootVisitor {
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001097 public:
Roland Levillain3887c462015-08-12 18:15:42 +01001098 CheckpointMarkThreadRoots(MarkSweep* mark_sweep,
1099 bool revoke_ros_alloc_thread_local_buffers_at_checkpoint)
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -07001100 : mark_sweep_(mark_sweep),
1101 revoke_ros_alloc_thread_local_buffers_at_checkpoint_(
1102 revoke_ros_alloc_thread_local_buffers_at_checkpoint) {
1103 }
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001104
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001105 void VisitRoots(mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -07001106 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_)
1107 REQUIRES(Locks::heap_bitmap_lock_) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001108 for (size_t i = 0; i < count; ++i) {
1109 mark_sweep_->MarkObjectNonNullParallel(*roots[i]);
1110 }
1111 }
1112
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -07001113 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots,
1114 size_t count,
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001115 const RootInfo& info ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -07001116 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_)
1117 REQUIRES(Locks::heap_bitmap_lock_) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001118 for (size_t i = 0; i < count; ++i) {
1119 mark_sweep_->MarkObjectNonNullParallel(roots[i]->AsMirrorPtr());
1120 }
1121 }
1122
Mathieu Chartier4aeec172014-03-27 16:09:46 -07001123 virtual void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001124 ScopedTrace trace("Marking thread roots");
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001125 // Note: self is not necessarily equal to thread since thread may be suspended.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001126 Thread* const self = Thread::Current();
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001127 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
1128 << thread->GetState() << " thread " << thread << " self " << self;
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001129 thread->VisitRoots(this);
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -07001130 if (revoke_ros_alloc_thread_local_buffers_at_checkpoint_) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001131 ScopedTrace trace2("RevokeRosAllocThreadLocalBuffers");
Hiroshi Yamauchic93c5302014-03-20 16:15:37 -07001132 mark_sweep_->GetHeap()->RevokeRosAllocThreadLocalBuffers(thread);
1133 }
Lei Lidd9943d2015-02-02 14:24:44 +08001134 // If thread is a running mutator, then act on behalf of the garbage collector.
1135 // See the code in ThreadList::RunCheckpoint.
Mathieu Chartier10d25082015-10-28 18:36:09 -07001136 mark_sweep_->GetBarrier().Pass(self);
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001137 }
1138
1139 private:
Mathieu Chartier4aeec172014-03-27 16:09:46 -07001140 MarkSweep* const mark_sweep_;
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -07001141 const bool revoke_ros_alloc_thread_local_buffers_at_checkpoint_;
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001142};
1143
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -07001144void MarkSweep::MarkRootsCheckpoint(Thread* self,
1145 bool revoke_ros_alloc_thread_local_buffers_at_checkpoint) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001146 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -07001147 CheckpointMarkThreadRoots check_point(this, revoke_ros_alloc_thread_local_buffers_at_checkpoint);
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001148 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Ian Rogers1d54e732013-05-02 21:10:01 -07001149 // Request the check point is run on all threads returning a count of the threads that must
1150 // run through the barrier including self.
1151 size_t barrier_count = thread_list->RunCheckpoint(&check_point);
1152 // Release locks then wait for all mutator threads to pass the barrier.
Lei Lidd9943d2015-02-02 14:24:44 +08001153 // If there are no threads to wait which implys that all the checkpoint functions are finished,
1154 // then no need to release locks.
1155 if (barrier_count == 0) {
1156 return;
1157 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001158 Locks::heap_bitmap_lock_->ExclusiveUnlock(self);
1159 Locks::mutator_lock_->SharedUnlock(self);
Mathieu Chartier4aeec172014-03-27 16:09:46 -07001160 {
1161 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
1162 gc_barrier_->Increment(self, barrier_count);
1163 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001164 Locks::mutator_lock_->SharedLock(self);
1165 Locks::heap_bitmap_lock_->ExclusiveLock(self);
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001166}
1167
Ian Rogers1d54e732013-05-02 21:10:01 -07001168void MarkSweep::SweepArray(accounting::ObjectStack* allocations, bool swap_bitmaps) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001169 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001170 Thread* self = Thread::Current();
Hiroshi Yamauchibbdc5bc2014-05-28 14:04:59 -07001171 mirror::Object** chunk_free_buffer = reinterpret_cast<mirror::Object**>(
1172 sweep_array_free_buffer_mem_map_->BaseBegin());
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001173 size_t chunk_free_pos = 0;
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07001174 ObjectBytePair freed;
1175 ObjectBytePair freed_los;
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001176 // How many objects are left in the array, modified after each space is swept.
Mathieu Chartier97509952015-07-13 14:35:43 -07001177 StackReference<mirror::Object>* objects = allocations->Begin();
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001178 size_t count = allocations->Size();
1179 // Change the order to ensure that the non-moving space last swept as an optimization.
1180 std::vector<space::ContinuousSpace*> sweep_spaces;
1181 space::ContinuousSpace* non_moving_space = nullptr;
1182 for (space::ContinuousSpace* space : heap_->GetContinuousSpaces()) {
Mathieu Chartier763a31e2015-11-16 16:05:55 -08001183 if (space->IsAllocSpace() &&
1184 !immune_spaces_.ContainsSpace(space) &&
Mathieu Chartier8d562102014-03-12 17:42:10 -07001185 space->GetLiveBitmap() != nullptr) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001186 if (space == heap_->GetNonMovingSpace()) {
1187 non_moving_space = space;
1188 } else {
1189 sweep_spaces.push_back(space);
1190 }
1191 }
1192 }
1193 // Unlikely to sweep a significant amount of non_movable objects, so we do these after the after
1194 // the other alloc spaces as an optimization.
1195 if (non_moving_space != nullptr) {
1196 sweep_spaces.push_back(non_moving_space);
1197 }
1198 // Start by sweeping the continuous spaces.
1199 for (space::ContinuousSpace* space : sweep_spaces) {
1200 space::AllocSpace* alloc_space = space->AsAllocSpace();
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -07001201 accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
1202 accounting::ContinuousSpaceBitmap* mark_bitmap = space->GetMarkBitmap();
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001203 if (swap_bitmaps) {
1204 std::swap(live_bitmap, mark_bitmap);
1205 }
Mathieu Chartier97509952015-07-13 14:35:43 -07001206 StackReference<mirror::Object>* out = objects;
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001207 for (size_t i = 0; i < count; ++i) {
Mathieu Chartier97509952015-07-13 14:35:43 -07001208 mirror::Object* const obj = objects[i].AsMirrorPtr();
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08001209 if (kUseThreadLocalAllocationStack && obj == nullptr) {
1210 continue;
1211 }
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001212 if (space->HasAddress(obj)) {
1213 // This object is in the space, remove it from the array and add it to the sweep buffer
1214 // if needed.
1215 if (!mark_bitmap->Test(obj)) {
1216 if (chunk_free_pos >= kSweepArrayChunkFreeSize) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001217 TimingLogger::ScopedTiming t2("FreeList", GetTimings());
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07001218 freed.objects += chunk_free_pos;
1219 freed.bytes += alloc_space->FreeList(self, chunk_free_pos, chunk_free_buffer);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001220 chunk_free_pos = 0;
1221 }
1222 chunk_free_buffer[chunk_free_pos++] = obj;
1223 }
1224 } else {
Mathieu Chartiercb535da2015-01-23 13:50:03 -08001225 (out++)->Assign(obj);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001226 }
1227 }
1228 if (chunk_free_pos > 0) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001229 TimingLogger::ScopedTiming t2("FreeList", GetTimings());
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07001230 freed.objects += chunk_free_pos;
1231 freed.bytes += alloc_space->FreeList(self, chunk_free_pos, chunk_free_buffer);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001232 chunk_free_pos = 0;
1233 }
1234 // All of the references which space contained are no longer in the allocation stack, update
1235 // the count.
1236 count = out - objects;
1237 }
1238 // Handle the large object space.
1239 space::LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
Mathieu Chartier2dbe6272014-09-16 10:43:23 -07001240 if (large_object_space != nullptr) {
1241 accounting::LargeObjectBitmap* large_live_objects = large_object_space->GetLiveBitmap();
1242 accounting::LargeObjectBitmap* large_mark_objects = large_object_space->GetMarkBitmap();
1243 if (swap_bitmaps) {
1244 std::swap(large_live_objects, large_mark_objects);
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08001245 }
Mathieu Chartier2dbe6272014-09-16 10:43:23 -07001246 for (size_t i = 0; i < count; ++i) {
Mathieu Chartier97509952015-07-13 14:35:43 -07001247 mirror::Object* const obj = objects[i].AsMirrorPtr();
Mathieu Chartier2dbe6272014-09-16 10:43:23 -07001248 // Handle large objects.
1249 if (kUseThreadLocalAllocationStack && obj == nullptr) {
1250 continue;
1251 }
1252 if (!large_mark_objects->Test(obj)) {
1253 ++freed_los.objects;
1254 freed_los.bytes += large_object_space->Free(self, obj);
1255 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001256 }
1257 }
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001258 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001259 TimingLogger::ScopedTiming t2("RecordFree", GetTimings());
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001260 RecordFree(freed);
1261 RecordFreeLOS(freed_los);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001262 t2.NewTiming("ResetStack");
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001263 allocations->Reset();
1264 }
Ian Rogersc5f17732014-06-05 20:48:42 -07001265 sweep_array_free_buffer_mem_map_->MadviseDontNeedAndZero();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001266}
1267
Ian Rogers1d54e732013-05-02 21:10:01 -07001268void MarkSweep::Sweep(bool swap_bitmaps) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001269 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -07001270 // Ensure that nobody inserted items in the live stack after we swapped the stacks.
1271 CHECK_GE(live_stack_freeze_size_, GetHeap()->GetLiveStack()->Size());
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001272 {
1273 TimingLogger::ScopedTiming t2("MarkAllocStackAsLive", GetTimings());
1274 // Mark everything allocated since the last as GC live so that we can sweep concurrently,
1275 // knowing that new allocations won't be marked as live.
1276 accounting::ObjectStack* live_stack = heap_->GetLiveStack();
1277 heap_->MarkAllocStackAsLive(live_stack);
1278 live_stack->Reset();
1279 DCHECK(mark_stack_->IsEmpty());
1280 }
Mathieu Chartier02e25112013-08-14 16:14:24 -07001281 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Mathieu Chartiera1602f22014-01-13 17:19:19 -08001282 if (space->IsContinuousMemMapAllocSpace()) {
1283 space::ContinuousMemMapAllocSpace* alloc_space = space->AsContinuousMemMapAllocSpace();
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001284 TimingLogger::ScopedTiming split(
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -07001285 alloc_space->IsZygoteSpace() ? "SweepZygoteSpace" : "SweepMallocSpace",
1286 GetTimings());
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07001287 RecordFree(alloc_space->Sweep(swap_bitmaps));
Carl Shapiro58551df2011-07-24 03:09:51 -07001288 }
1289 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001290 SweepLargeObjects(swap_bitmaps);
Carl Shapiro58551df2011-07-24 03:09:51 -07001291}
1292
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001293void MarkSweep::SweepLargeObjects(bool swap_bitmaps) {
Mathieu Chartier2dbe6272014-09-16 10:43:23 -07001294 space::LargeObjectSpace* los = heap_->GetLargeObjectsSpace();
1295 if (los != nullptr) {
1296 TimingLogger::ScopedTiming split(__FUNCTION__, GetTimings());
1297 RecordFreeLOS(los->Sweep(swap_bitmaps));
1298 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001299}
1300
Mathieu Chartier407f7022014-02-18 14:37:05 -08001301// Process the "referent" field in a java.lang.ref.Reference. If the referent has not yet been
1302// marked, put it on the appropriate list in the heap for later processing.
1303void MarkSweep::DelayReferenceReferent(mirror::Class* klass, mirror::Reference* ref) {
Mathieu Chartier97509952015-07-13 14:35:43 -07001304 heap_->GetReferenceProcessor()->DelayReferenceReferent(klass, ref, this);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001305}
1306
Mathieu Chartier97509952015-07-13 14:35:43 -07001307class MarkVisitor {
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001308 public:
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -07001309 ALWAYS_INLINE explicit MarkVisitor(MarkSweep* const mark_sweep) : mark_sweep_(mark_sweep) {}
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001310
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -07001311 ALWAYS_INLINE void operator()(mirror::Object* obj,
1312 MemberOffset offset,
1313 bool is_static ATTRIBUTE_UNUSED) const
1314 REQUIRES(Locks::heap_bitmap_lock_)
1315 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001316 if (kCheckLocks) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001317 Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
1318 Locks::heap_bitmap_lock_->AssertExclusiveHeld(Thread::Current());
1319 }
Hiroshi Yamauchieb2baaf2015-05-13 21:14:22 -07001320 mark_sweep_->MarkObject(obj->GetFieldObject<mirror::Object>(offset), obj, offset);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001321 }
1322
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001323 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -07001324 REQUIRES(Locks::heap_bitmap_lock_)
1325 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001326 if (!root->IsNull()) {
1327 VisitRoot(root);
1328 }
1329 }
1330
1331 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Mathieu Chartier1ac1c2b2015-09-22 14:53:32 -07001332 REQUIRES(Locks::heap_bitmap_lock_)
1333 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001334 if (kCheckLocks) {
1335 Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
1336 Locks::heap_bitmap_lock_->AssertExclusiveHeld(Thread::Current());
1337 }
1338 mark_sweep_->MarkObject(root->AsMirrorPtr());
1339 }
1340
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001341 private:
1342 MarkSweep* const mark_sweep_;
1343};
1344
Carl Shapiro69759ea2011-07-21 18:13:35 -07001345// Scans an object reference. Determines the type of the reference
1346// and dispatches to a specialized scanning routine.
Mathieu Chartier97509952015-07-13 14:35:43 -07001347void MarkSweep::ScanObject(mirror::Object* obj) {
1348 MarkVisitor mark_visitor(this);
Mathieu Chartier407f7022014-02-18 14:37:05 -08001349 DelayReferenceReferentVisitor ref_visitor(this);
1350 ScanObjectVisit(obj, mark_visitor, ref_visitor);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001351}
1352
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001353void MarkSweep::ProcessMarkStackParallel(size_t thread_count) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001354 Thread* self = Thread::Current();
1355 ThreadPool* thread_pool = GetHeap()->GetThreadPool();
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001356 const size_t chunk_size = std::min(mark_stack_->Size() / thread_count + 1,
1357 static_cast<size_t>(MarkStackTask<false>::kMaxSize));
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001358 CHECK_GT(chunk_size, 0U);
1359 // Split the current mark stack up into work tasks.
Mathieu Chartiercb535da2015-01-23 13:50:03 -08001360 for (auto* it = mark_stack_->Begin(), *end = mark_stack_->End(); it < end; ) {
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001361 const size_t delta = std::min(static_cast<size_t>(end - it), chunk_size);
Mathieu Chartier0e54cd02014-03-20 12:41:23 -07001362 thread_pool->AddTask(self, new MarkStackTask<false>(thread_pool, this, delta, it));
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001363 it += delta;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001364 }
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001365 thread_pool->SetMaxActiveWorkers(thread_count - 1);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001366 thread_pool->StartWorkers(self);
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001367 thread_pool->Wait(self, true, true);
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001368 thread_pool->StopWorkers(self);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001369 mark_stack_->Reset();
Ian Rogers3e5cf302014-05-20 16:40:37 -07001370 CHECK_EQ(work_chunks_created_.LoadSequentiallyConsistent(),
1371 work_chunks_deleted_.LoadSequentiallyConsistent())
1372 << " some of the work chunks were leaked";
Carl Shapiro69759ea2011-07-21 18:13:35 -07001373}
1374
Ian Rogers5d76c432011-10-31 21:42:49 -07001375// Scan anything that's on the mark stack.
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001376void MarkSweep::ProcessMarkStack(bool paused) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001377 TimingLogger::ScopedTiming t(paused ? "(Paused)ProcessMarkStack" : __FUNCTION__, GetTimings());
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001378 size_t thread_count = GetThreadCount(paused);
1379 if (kParallelProcessMarkStack && thread_count > 1 &&
1380 mark_stack_->Size() >= kMinimumParallelMarkStackSize) {
1381 ProcessMarkStackParallel(thread_count);
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001382 } else {
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001383 // TODO: Tune this.
1384 static const size_t kFifoSize = 4;
Mathieu Chartier97509952015-07-13 14:35:43 -07001385 BoundedFifoPowerOfTwo<mirror::Object*, kFifoSize> prefetch_fifo;
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001386 for (;;) {
Mathieu Chartier97509952015-07-13 14:35:43 -07001387 mirror::Object* obj = nullptr;
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001388 if (kUseMarkStackPrefetch) {
1389 while (!mark_stack_->IsEmpty() && prefetch_fifo.size() < kFifoSize) {
Mathieu Chartier97509952015-07-13 14:35:43 -07001390 mirror::Object* mark_stack_obj = mark_stack_->PopBack();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001391 DCHECK(mark_stack_obj != nullptr);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001392 __builtin_prefetch(mark_stack_obj);
1393 prefetch_fifo.push_back(mark_stack_obj);
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001394 }
1395 if (prefetch_fifo.empty()) {
1396 break;
1397 }
1398 obj = prefetch_fifo.front();
1399 prefetch_fifo.pop_front();
1400 } else {
1401 if (mark_stack_->IsEmpty()) {
1402 break;
1403 }
1404 obj = mark_stack_->PopBack();
1405 }
Mathieu Chartier4aeec172014-03-27 16:09:46 -07001406 DCHECK(obj != nullptr);
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001407 ScanObject(obj);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001408 }
1409 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001410}
1411
Mathieu Chartier97509952015-07-13 14:35:43 -07001412inline mirror::Object* MarkSweep::IsMarked(mirror::Object* object) {
Mathieu Chartier763a31e2015-11-16 16:05:55 -08001413 if (immune_spaces_.IsInImmuneRegion(object)) {
Mathieu Chartier97509952015-07-13 14:35:43 -07001414 return object;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001415 }
Mathieu Chartier0e54cd02014-03-20 12:41:23 -07001416 if (current_space_bitmap_->HasAddress(object)) {
Mathieu Chartier97509952015-07-13 14:35:43 -07001417 return current_space_bitmap_->Test(object) ? object : nullptr;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001418 }
Mathieu Chartier97509952015-07-13 14:35:43 -07001419 return mark_bitmap_->Test(object) ? object : nullptr;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001420}
1421
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001422void MarkSweep::FinishPhase() {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001423 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001424 if (kCountScannedTypes) {
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07001425 VLOG(gc)
1426 << "MarkSweep scanned"
1427 << " no reference objects=" << no_reference_class_count_.LoadRelaxed()
1428 << " normal objects=" << normal_count_.LoadRelaxed()
1429 << " classes=" << class_count_.LoadRelaxed()
1430 << " object arrays=" << object_array_count_.LoadRelaxed()
1431 << " references=" << reference_count_.LoadRelaxed()
1432 << " other=" << other_count_.LoadRelaxed();
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001433 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001434 if (kCountTasks) {
Ian Rogers3e5cf302014-05-20 16:40:37 -07001435 VLOG(gc) << "Total number of work chunks allocated: " << work_chunks_created_.LoadRelaxed();
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001436 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001437 if (kMeasureOverhead) {
Ian Rogers3e5cf302014-05-20 16:40:37 -07001438 VLOG(gc) << "Overhead time " << PrettyDuration(overhead_time_.LoadRelaxed());
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001439 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001440 if (kProfileLargeObjects) {
Ian Rogers3e5cf302014-05-20 16:40:37 -07001441 VLOG(gc) << "Large objects tested " << large_object_test_.LoadRelaxed()
1442 << " marked " << large_object_mark_.LoadRelaxed();
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001443 }
Mathieu Chartier0e54cd02014-03-20 12:41:23 -07001444 if (kCountMarkedObjects) {
Ian Rogers3e5cf302014-05-20 16:40:37 -07001445 VLOG(gc) << "Marked: null=" << mark_null_count_.LoadRelaxed()
1446 << " immune=" << mark_immune_count_.LoadRelaxed()
1447 << " fastpath=" << mark_fastpath_count_.LoadRelaxed()
1448 << " slowpath=" << mark_slowpath_count_.LoadRelaxed();
Mathieu Chartier0e54cd02014-03-20 12:41:23 -07001449 }
Mathieu Chartier4aeec172014-03-27 16:09:46 -07001450 CHECK(mark_stack_->IsEmpty()); // Ensure that the mark stack is empty.
Mathieu Chartier5301cd22012-05-31 12:11:36 -07001451 mark_stack_->Reset();
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -08001452 Thread* const self = Thread::Current();
1453 ReaderMutexLock mu(self, *Locks::mutator_lock_);
1454 WriterMutexLock mu2(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier4aeec172014-03-27 16:09:46 -07001455 heap_->ClearMarkedObjects();
Carl Shapiro69759ea2011-07-21 18:13:35 -07001456}
1457
Hiroshi Yamauchic93c5302014-03-20 16:15:37 -07001458void MarkSweep::RevokeAllThreadLocalBuffers() {
1459 if (kRevokeRosAllocThreadLocalBuffersAtCheckpoint && IsConcurrent()) {
1460 // If concurrent, rosalloc thread-local buffers are revoked at the
1461 // thread checkpoint. Bump pointer space thread-local buffers must
1462 // not be in use.
1463 GetHeap()->AssertAllBumpPointerSpaceThreadLocalBuffersAreRevoked();
1464 } else {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001465 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Hiroshi Yamauchic93c5302014-03-20 16:15:37 -07001466 GetHeap()->RevokeAllThreadLocalBuffers();
Hiroshi Yamauchic93c5302014-03-20 16:15:37 -07001467 }
1468}
1469
Ian Rogers1d54e732013-05-02 21:10:01 -07001470} // namespace collector
1471} // namespace gc
Carl Shapiro69759ea2011-07-21 18:13:35 -07001472} // namespace art