blob: b8051c9b386cfde4d4dc910d188f5ab1e8f519b0 [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
Mathieu Chartier2b82db42012-11-14 17:29:05 -080019#include <functional>
20#include <numeric>
Carl Shapiro58551df2011-07-24 03:09:51 -070021#include <climits>
22#include <vector>
23
Mathieu Chartier94c32c52013-08-09 11:14:04 -070024#include "base/bounded_fifo.h"
Elliott Hughes07ed66b2012-12-12 18:34:25 -080025#include "base/logging.h"
Elliott Hughes76160052012-12-12 16:31:20 -080026#include "base/macros.h"
Ian Rogers693ff612013-02-01 10:56:12 -080027#include "base/mutex-inl.h"
Sameer Abu Asala8439542013-02-14 16:06:42 -080028#include "base/timing_logger.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070029#include "gc/accounting/card_table-inl.h"
Mathieu Chartier4aeec172014-03-27 16:09:46 -070030#include "gc/accounting/heap_bitmap-inl.h"
Mathieu Chartier11409ae2013-09-23 11:49:36 -070031#include "gc/accounting/mod_union_table.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070032#include "gc/accounting/space_bitmap-inl.h"
33#include "gc/heap.h"
34#include "gc/space/image_space.h"
35#include "gc/space/large_object_space.h"
36#include "gc/space/space-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080037#include "mark_sweep-inl.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070038#include "mirror/art_field-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080039#include "mirror/object-inl.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070040#include "runtime.h"
Mathieu Chartier4aeec172014-03-27 16:09:46 -070041#include "scoped_thread_state_change.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070042#include "thread-inl.h"
Mathieu Chartier6f1c9492012-10-15 12:08:41 -070043#include "thread_list.h"
Carl Shapiro69759ea2011-07-21 18:13:35 -070044
Brian Carlstromea46f952013-07-30 01:26:50 -070045using ::art::mirror::ArtField;
Brian Carlstrom3e3d5912013-07-18 00:19:45 -070046using ::art::mirror::Class;
Brian Carlstrom3e3d5912013-07-18 00:19:45 -070047using ::art::mirror::Object;
48using ::art::mirror::ObjectArray;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080049
Carl Shapiro69759ea2011-07-21 18:13:35 -070050namespace art {
Ian Rogers1d54e732013-05-02 21:10:01 -070051namespace gc {
52namespace collector {
Carl Shapiro69759ea2011-07-21 18:13:35 -070053
Mathieu Chartier02b6a782012-10-26 13:51:26 -070054// Performance options.
Mathieu Chartiereb7bbad2014-02-25 15:52:46 -080055static constexpr bool kUseRecursiveMark = false;
56static constexpr bool kUseMarkStackPrefetch = true;
57static constexpr size_t kSweepArrayChunkFreeSize = 1024;
58static constexpr bool kPreCleanCards = true;
Mathieu Chartier94c32c52013-08-09 11:14:04 -070059
60// Parallelism options.
Mathieu Chartiereb7bbad2014-02-25 15:52:46 -080061static constexpr bool kParallelCardScan = true;
62static constexpr bool kParallelRecursiveMark = true;
Mathieu Chartier94c32c52013-08-09 11:14:04 -070063// Don't attempt to parallelize mark stack processing unless the mark stack is at least n
64// elements. This is temporary until we reduce the overhead caused by allocating tasks, etc.. Not
65// having this can add overhead in ProcessReferences since we may end up doing many calls of
66// ProcessMarkStack with very small mark stacks.
Mathieu Chartiereb7bbad2014-02-25 15:52:46 -080067static constexpr size_t kMinimumParallelMarkStackSize = 128;
68static constexpr bool kParallelProcessMarkStack = true;
Mathieu Chartier858f1c52012-10-17 17:45:55 -070069
Mathieu Chartier02b6a782012-10-26 13:51:26 -070070// Profiling and information flags.
Mathieu Chartiereb7bbad2014-02-25 15:52:46 -080071static constexpr bool kProfileLargeObjects = false;
72static constexpr bool kMeasureOverhead = false;
73static constexpr bool kCountTasks = false;
74static constexpr bool kCountJavaLangRefs = false;
Mathieu Chartier0e54cd02014-03-20 12:41:23 -070075static constexpr bool kCountMarkedObjects = false;
Mathieu Chartier94c32c52013-08-09 11:14:04 -070076
77// Turn off kCheckLocks when profiling the GC since it slows the GC down by up to 40%.
Mathieu Chartiereb7bbad2014-02-25 15:52:46 -080078static constexpr bool kCheckLocks = kDebugLocking;
Mathieu Chartier7bf9f192014-04-04 11:09:41 -070079static constexpr bool kVerifyRootsMarked = kIsDebugBuild;
Mathieu Chartier02b6a782012-10-26 13:51:26 -070080
Hiroshi Yamauchic93c5302014-03-20 16:15:37 -070081// If true, revoke the rosalloc thread-local buffers at the
82// checkpoint, as opposed to during the pause.
83static constexpr bool kRevokeRosAllocThreadLocalBuffersAtCheckpoint = true;
84
Mathieu Chartier2b82db42012-11-14 17:29:05 -080085void MarkSweep::BindBitmaps() {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -070086 timings_.StartSplit("BindBitmaps");
Mathieu Chartier2b82db42012-11-14 17:29:05 -080087 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -080088 // Mark all of the spaces we never collect as immune.
Mathieu Chartier94c32c52013-08-09 11:14:04 -070089 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Ian Rogers1d54e732013-05-02 21:10:01 -070090 if (space->GetGcRetentionPolicy() == space::kGcRetentionPolicyNeverCollect) {
Mathieu Chartier8d562102014-03-12 17:42:10 -070091 CHECK(immune_region_.AddContinuousSpace(space)) << "Failed to add space " << *space;
Mathieu Chartier2b82db42012-11-14 17:29:05 -080092 }
93 }
Anwar Ghuloum4446ab92013-08-09 21:17:25 -070094 timings_.EndSplit();
Mathieu Chartier2b82db42012-11-14 17:29:05 -080095}
96
Ian Rogers1d54e732013-05-02 21:10:01 -070097MarkSweep::MarkSweep(Heap* heap, bool is_concurrent, const std::string& name_prefix)
98 : GarbageCollector(heap,
Mathieu Chartier590fee92013-09-13 13:46:47 -070099 name_prefix +
Ian Rogers1d54e732013-05-02 21:10:01 -0700100 (is_concurrent ? "concurrent mark sweep": "mark sweep")),
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800101 gc_barrier_(new Barrier(0)),
Mathieu Chartier958291c2013-08-27 18:14:55 -0700102 mark_stack_lock_("mark sweep mark stack lock", kMarkSweepMarkStackLock),
Mathieu Chartier590fee92013-09-13 13:46:47 -0700103 is_concurrent_(is_concurrent) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800104}
105
106void MarkSweep::InitializePhase() {
Ian Rogers5fe9af72013-11-14 00:17:20 -0800107 TimingLogger::ScopedSplit split("InitializePhase", &timings_);
Mathieu Chartiere53225c2013-08-19 10:59:11 -0700108 mark_stack_ = heap_->mark_stack_.get();
109 DCHECK(mark_stack_ != nullptr);
Mathieu Chartier8d562102014-03-12 17:42:10 -0700110 immune_region_.Reset();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800111 class_count_ = 0;
112 array_count_ = 0;
113 other_count_ = 0;
114 large_object_test_ = 0;
115 large_object_mark_ = 0;
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800116 overhead_time_ = 0;
117 work_chunks_created_ = 0;
118 work_chunks_deleted_ = 0;
119 reference_count_ = 0;
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700120 mark_null_count_ = 0;
121 mark_immune_count_ = 0;
122 mark_fastpath_count_ = 0;
123 mark_slowpath_count_ = 0;
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700124 {
125 // TODO: I don't think we should need heap bitmap lock to get the mark bitmap.
126 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
127 mark_bitmap_ = heap_->GetMarkBitmap();
128 }
Hiroshi Yamauchidf386c52014-04-08 16:21:52 -0700129 if (!clear_soft_references_) {
130 // Always clear soft references if a non-sticky collection.
131 clear_soft_references_ = GetGcType() != collector::kGcTypeSticky;
132 }
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700133}
134
135void MarkSweep::RunPhases() {
136 Thread* self = Thread::Current();
137 InitializePhase();
138 Locks::mutator_lock_->AssertNotHeld(self);
139 if (IsConcurrent()) {
140 GetHeap()->PreGcVerification(this);
141 {
142 ReaderMutexLock mu(self, *Locks::mutator_lock_);
143 MarkingPhase();
144 }
145 ScopedPause pause(this);
146 GetHeap()->PrePauseRosAllocVerification(this);
147 PausePhase();
148 RevokeAllThreadLocalBuffers();
149 } else {
150 ScopedPause pause(this);
151 GetHeap()->PreGcVerificationPaused(this);
152 MarkingPhase();
153 GetHeap()->PrePauseRosAllocVerification(this);
154 PausePhase();
155 RevokeAllThreadLocalBuffers();
156 }
157 {
158 // Sweeping always done concurrently, even for non concurrent mark sweep.
159 ReaderMutexLock mu(self, *Locks::mutator_lock_);
160 ReclaimPhase();
161 }
162 GetHeap()->PostGcVerification(this);
163 FinishPhase();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800164}
165
166void MarkSweep::ProcessReferences(Thread* self) {
Ian Rogers5fe9af72013-11-14 00:17:20 -0800167 TimingLogger::ScopedSplit split("ProcessReferences", &timings_);
Mathieu Chartier8e56c7e2012-11-20 13:25:50 -0800168 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier39e32612013-11-12 16:28:05 -0800169 GetHeap()->ProcessReferences(timings_, clear_soft_references_, &IsMarkedCallback,
Mathieu Chartier3bb57c72014-02-18 11:38:45 -0800170 &MarkObjectCallback, &ProcessMarkStackPausedCallback, this);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800171}
172
Mathieu Chartier601276a2014-03-20 15:12:30 -0700173void MarkSweep::PreProcessReferences() {
174 if (IsConcurrent()) {
175 // No reason to do this for non-concurrent GC since pre processing soft references only helps
176 // pauses.
177 timings_.NewSplit("PreProcessReferences");
178 GetHeap()->ProcessSoftReferences(timings_, clear_soft_references_, &IsMarkedCallback,
179 &MarkObjectCallback, &ProcessMarkStackPausedCallback, this);
180 }
Mathieu Chartier1ad27842014-03-19 17:08:17 -0700181}
182
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -0700183void MarkSweep::PausePhase() {
184 TimingLogger::ScopedSplit split("(Paused)PausePhase", &timings_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800185 Thread* self = Thread::Current();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800186 Locks::mutator_lock_->AssertExclusiveHeld(self);
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -0700187 if (IsConcurrent()) {
188 // Handle the dirty objects if we are a concurrent GC.
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800189 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800190 // Re-mark root set.
191 ReMarkRoots();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800192 // Scan dirty objects, this is only required if we are not doing concurrent GC.
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700193 RecursiveMarkDirtyObjects(true, accounting::CardTable::kCardDirty);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800194 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800195 ProcessReferences(self);
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -0700196 {
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700197 TimingLogger::ScopedSplit split("SwapStacks", &timings_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800198 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -0700199 heap_->SwapStacks(self);
200 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 timings_.StartSplit("PreSweepingGcVerification");
206 heap_->PreSweepingGcVerification(this);
207 timings_.EndSplit();
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700208 // Disallow new system weaks to prevent a race which occurs when someone adds a new system
209 // weak before we sweep them. Since this new system weak may not be marked, the GC may
210 // incorrectly sweep it. This also fixes a race where interning may attempt to return a strong
211 // reference to a string that is about to be swept.
212 Runtime::Current()->DisallowNewSystemWeaks();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800213}
214
Mathieu Chartierdda54f52014-02-24 09:58:40 -0800215void MarkSweep::PreCleanCards() {
216 // Don't do this for non concurrent GCs since they don't have any dirty cards.
217 if (kPreCleanCards && IsConcurrent()) {
218 Thread* self = Thread::Current();
219 CHECK(!Locks::mutator_lock_->IsExclusiveHeld(self));
220 // Process dirty cards and add dirty cards to mod union tables, also ages cards.
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -0800221 heap_->ProcessCards(timings_, false);
Mathieu Chartiereb7bbad2014-02-25 15:52:46 -0800222 // The checkpoint root marking is required to avoid a race condition which occurs if the
223 // following happens during a reference write:
224 // 1. mutator dirties the card (write barrier)
225 // 2. GC ages the card (the above ProcessCards call)
226 // 3. GC scans the object (the RecursiveMarkDirtyObjects call below)
227 // 4. mutator writes the value (corresponding to the write barrier in 1.)
228 // This causes the GC to age the card but not necessarily mark the reference which the mutator
229 // wrote into the object stored in the card.
230 // Having the checkpoint fixes this issue since it ensures that the card mark and the
231 // reference write are visible to the GC before the card is scanned (this is due to locks being
232 // acquired / released in the checkpoint code).
233 // The other roots are also marked to help reduce the pause.
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -0700234 MarkRootsCheckpoint(self, false);
Mathieu Chartierdda54f52014-02-24 09:58:40 -0800235 MarkNonThreadRoots();
Mathieu Chartier893263b2014-03-04 11:07:42 -0800236 MarkConcurrentRoots(
237 static_cast<VisitRootFlags>(kVisitRootFlagClearRootLog | kVisitRootFlagNewRoots));
Mathieu Chartierdda54f52014-02-24 09:58:40 -0800238 // Process the newly aged cards.
239 RecursiveMarkDirtyObjects(false, accounting::CardTable::kCardDirty - 1);
240 // TODO: Empty allocation stack to reduce the number of objects we need to test / mark as live
241 // in the next GC.
242 }
243}
244
Mathieu Chartierc22c59e2014-02-24 15:16:06 -0800245void MarkSweep::RevokeAllThreadLocalAllocationStacks(Thread* self) {
246 if (kUseThreadLocalAllocationStack) {
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -0700247 timings_.NewSplit("RevokeAllThreadLocalAllocationStacks");
Mathieu Chartierc22c59e2014-02-24 15:16:06 -0800248 Locks::mutator_lock_->AssertExclusiveHeld(self);
249 heap_->RevokeAllThreadLocalAllocationStacks(self);
250 }
251}
252
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800253void MarkSweep::MarkingPhase() {
Ian Rogers5fe9af72013-11-14 00:17:20 -0800254 TimingLogger::ScopedSplit split("MarkingPhase", &timings_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800255 Thread* self = Thread::Current();
256
257 BindBitmaps();
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700258 FindDefaultSpaceBitmap();
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700259
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800260 // Process dirty cards and add dirty cards to mod union tables.
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -0800261 heap_->ProcessCards(timings_, false);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800262
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 Chartier601276a2014-03-20 15:12:30 -0700268 PreProcessReferences();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800269}
270
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700271void MarkSweep::UpdateAndMarkModUnion() {
272 for (const auto& space : heap_->GetContinuousSpaces()) {
Mathieu Chartier8d562102014-03-12 17:42:10 -0700273 if (immune_region_.ContainsSpace(space)) {
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700274 const char* name = space->IsZygoteSpace() ? "UpdateAndMarkZygoteModUnionTable" :
275 "UpdateAndMarkImageModUnionTable";
Ian Rogers5fe9af72013-11-14 00:17:20 -0800276 TimingLogger::ScopedSplit split(name, &timings_);
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700277 accounting::ModUnionTable* mod_union_table = heap_->FindModUnionTableFromSpace(space);
278 CHECK(mod_union_table != nullptr);
Mathieu Chartier407f7022014-02-18 14:37:05 -0800279 mod_union_table->UpdateAndMarkReferences(MarkHeapReferenceCallback, this);
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700280 }
281 }
282}
283
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800284void MarkSweep::MarkReachableObjects() {
Mathieu Chartier4aeec172014-03-27 16:09:46 -0700285 UpdateAndMarkModUnion();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800286 // Recursively mark all the non-image bits set in the mark bitmap.
287 RecursiveMark();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800288}
289
290void MarkSweep::ReclaimPhase() {
Ian Rogers5fe9af72013-11-14 00:17:20 -0800291 TimingLogger::ScopedSplit split("ReclaimPhase", &timings_);
Mathieu Chartier720ef762013-08-17 14:46:54 -0700292 Thread* self = Thread::Current();
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -0700293 SweepSystemWeaks(self);
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700294 Runtime::Current()->AllowNewSystemWeaks();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800295 {
296 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
297
298 // Reclaim unmarked objects.
Ian Rogers1d54e732013-05-02 21:10:01 -0700299 Sweep(false);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800300
301 // Swap the live and mark bitmaps for each space which we modified space. This is an
302 // optimization that enables us to not clear live bits inside of the sweep. Only swaps unbound
303 // bitmaps.
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700304 timings_.StartSplit("SwapBitmaps");
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800305 SwapBitmaps();
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700306 timings_.EndSplit();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800307
308 // Unbind the live and mark bitmaps.
Mathieu Chartiera1602f22014-01-13 17:19:19 -0800309 TimingLogger::ScopedSplit split("UnBindBitmaps", &timings_);
310 GetHeap()->UnBindBitmaps();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800311 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800312}
313
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700314void MarkSweep::FindDefaultSpaceBitmap() {
Ian Rogers5fe9af72013-11-14 00:17:20 -0800315 TimingLogger::ScopedSplit split("FindDefaultMarkBitmap", &timings_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700316 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -0700317 accounting::ContinuousSpaceBitmap* bitmap = space->GetMarkBitmap();
Mathieu Chartierbbd695c2014-04-16 09:48:48 -0700318 // We want to have the main space instead of non moving if possible.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700319 if (bitmap != nullptr &&
320 space->GetGcRetentionPolicy() == space::kGcRetentionPolicyAlwaysCollect) {
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700321 current_space_bitmap_ = bitmap;
Mathieu Chartierbbd695c2014-04-16 09:48:48 -0700322 // If we are not the non moving space exit the loop early since this will be good enough.
323 if (space != heap_->GetNonMovingSpace()) {
324 break;
325 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700326 }
327 }
Mathieu Chartierbbd695c2014-04-16 09:48:48 -0700328 if (current_space_bitmap_ == nullptr) {
329 heap_->DumpSpaces();
330 LOG(FATAL) << "Could not find a default mark bitmap";
331 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700332}
333
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800334void MarkSweep::ExpandMarkStack() {
Mathieu Chartierba311b42013-08-27 13:02:30 -0700335 ResizeMarkStack(mark_stack_->Capacity() * 2);
336}
337
338void MarkSweep::ResizeMarkStack(size_t new_size) {
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800339 // Rare case, no need to have Thread::Current be a parameter.
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800340 if (UNLIKELY(mark_stack_->Size() < mark_stack_->Capacity())) {
341 // Someone else acquired the lock and expanded the mark stack before us.
342 return;
343 }
Mathieu Chartier02e25112013-08-14 16:14:24 -0700344 std::vector<Object*> temp(mark_stack_->Begin(), mark_stack_->End());
Mathieu Chartierba311b42013-08-27 13:02:30 -0700345 CHECK_LE(mark_stack_->Size(), new_size);
346 mark_stack_->Resize(new_size);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700347 for (const auto& obj : temp) {
348 mark_stack_->PushBack(obj);
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800349 }
350}
351
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700352inline void MarkSweep::MarkObjectNonNullParallel(Object* obj) {
Mathieu Chartierbbd695c2014-04-16 09:48:48 -0700353 DCHECK(obj != nullptr);
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800354 if (MarkObjectParallel(obj)) {
Mathieu Chartierba311b42013-08-27 13:02:30 -0700355 MutexLock mu(Thread::Current(), mark_stack_lock_);
356 if (UNLIKELY(mark_stack_->Size() >= mark_stack_->Capacity())) {
Mathieu Chartier184e3222013-08-03 14:02:57 -0700357 ExpandMarkStack();
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800358 }
Mathieu Chartierba311b42013-08-27 13:02:30 -0700359 // The object must be pushed on to the mark stack.
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700360 mark_stack_->PushBack(obj);
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800361 }
362}
363
Mathieu Chartier3bb57c72014-02-18 11:38:45 -0800364mirror::Object* MarkSweep::MarkObjectCallback(mirror::Object* obj, void* arg) {
Mathieu Chartier39e32612013-11-12 16:28:05 -0800365 MarkSweep* mark_sweep = reinterpret_cast<MarkSweep*>(arg);
366 mark_sweep->MarkObject(obj);
Mathieu Chartier39e32612013-11-12 16:28:05 -0800367 return obj;
368}
369
Mathieu Chartier407f7022014-02-18 14:37:05 -0800370void MarkSweep::MarkHeapReferenceCallback(mirror::HeapReference<mirror::Object>* ref, void* arg) {
371 reinterpret_cast<MarkSweep*>(arg)->MarkObject(ref->AsMirrorPtr());
372}
373
Mathieu Chartierbbd695c2014-04-16 09:48:48 -0700374class MarkSweepMarkObjectSlowPath {
375 public:
376 explicit MarkSweepMarkObjectSlowPath(MarkSweep* mark_sweep) : mark_sweep_(mark_sweep) {
377 }
378
379 void operator()(const Object* obj) const ALWAYS_INLINE {
380 if (kProfileLargeObjects) {
381 // TODO: Differentiate between marking and testing somehow.
382 ++mark_sweep_->large_object_test_;
383 ++mark_sweep_->large_object_mark_;
384 }
385 space::LargeObjectSpace* large_object_space = mark_sweep_->GetHeap()->GetLargeObjectsSpace();
386 if (UNLIKELY(!IsAligned<kPageSize>(obj) ||
387 (kIsDebugBuild && !large_object_space->Contains(obj)))) {
388 LOG(ERROR) << "Tried to mark " << obj << " not contained by any spaces";
389 LOG(ERROR) << "Attempting see if it's a bad root";
390 mark_sweep_->VerifyRoots();
391 LOG(FATAL) << "Can't mark invalid object";
392 }
393 }
394
395 private:
396 MarkSweep* const mark_sweep_;
397};
398
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700399inline void MarkSweep::MarkObjectNonNull(Object* obj) {
400 DCHECK(obj != nullptr);
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -0700401 if (kUseBakerOrBrooksReadBarrier) {
402 // Verify all the objects have the correct pointer installed.
403 obj->AssertReadBarrierPointer();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800404 }
Mathieu Chartier8d562102014-03-12 17:42:10 -0700405 if (immune_region_.ContainsObject(obj)) {
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700406 if (kCountMarkedObjects) {
407 ++mark_immune_count_;
408 }
Mathieu Chartierbbd695c2014-04-16 09:48:48 -0700409 DCHECK(mark_bitmap_->Test(obj));
410 } else if (LIKELY(current_space_bitmap_->HasAddress(obj))) {
411 if (kCountMarkedObjects) {
412 ++mark_fastpath_count_;
413 }
414 if (UNLIKELY(!current_space_bitmap_->Set(obj))) {
415 PushOnMarkStack(obj); // This object was not previously marked.
416 }
417 } else {
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700418 if (kCountMarkedObjects) {
419 ++mark_slowpath_count_;
420 }
Mathieu Chartierbbd695c2014-04-16 09:48:48 -0700421 MarkSweepMarkObjectSlowPath visitor(this);
422 // TODO: We already know that the object is not in the current_space_bitmap_ but MarkBitmap::Set
423 // will check again.
424 if (!mark_bitmap_->Set(obj, visitor)) {
425 PushOnMarkStack(obj); // Was not already marked, push.
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700426 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700427 }
428}
429
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700430inline void MarkSweep::PushOnMarkStack(Object* obj) {
431 if (UNLIKELY(mark_stack_->Size() >= mark_stack_->Capacity())) {
432 // Lock is not needed but is here anyways to please annotalysis.
433 MutexLock mu(Thread::Current(), mark_stack_lock_);
434 ExpandMarkStack();
435 }
436 // The object must be pushed on to the mark stack.
437 mark_stack_->PushBack(obj);
438}
439
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700440inline bool MarkSweep::MarkObjectParallel(const Object* obj) {
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700441 DCHECK(obj != nullptr);
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -0700442 if (kUseBakerOrBrooksReadBarrier) {
443 // Verify all the objects have the correct pointer installed.
444 obj->AssertReadBarrierPointer();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800445 }
Mathieu Chartier8d562102014-03-12 17:42:10 -0700446 if (immune_region_.ContainsObject(obj)) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700447 DCHECK(IsMarked(obj));
448 return false;
449 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700450 // Try to take advantage of locality of references within a space, failing this find the space
451 // the hard way.
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -0700452 accounting::ContinuousSpaceBitmap* object_bitmap = current_space_bitmap_;
Mathieu Chartierbbd695c2014-04-16 09:48:48 -0700453 if (LIKELY(object_bitmap->HasAddress(obj))) {
454 return !object_bitmap->AtomicTestAndSet(obj);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700455 }
Mathieu Chartierbbd695c2014-04-16 09:48:48 -0700456 MarkSweepMarkObjectSlowPath visitor(this);
457 return !mark_bitmap_->AtomicTestAndSet(obj, visitor);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700458}
459
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700460// Used to mark objects when processing the mark stack. If an object is null, it is not marked.
461inline void MarkSweep::MarkObject(Object* obj) {
462 if (obj != nullptr) {
Mathieu Chartier9642c962013-08-05 17:40:36 -0700463 MarkObjectNonNull(obj);
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700464 } else if (kCountMarkedObjects) {
465 ++mark_null_count_;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700466 }
467}
468
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700469void MarkSweep::MarkRootParallelCallback(Object** root, void* arg, uint32_t /*thread_id*/,
Mathieu Chartier815873e2014-02-13 18:02:13 -0800470 RootType /*root_type*/) {
Mathieu Chartier815873e2014-02-13 18:02:13 -0800471 reinterpret_cast<MarkSweep*>(arg)->MarkObjectNonNullParallel(*root);
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800472}
473
Mathieu Chartier893263b2014-03-04 11:07:42 -0800474void MarkSweep::VerifyRootMarked(Object** root, void* arg, uint32_t /*thread_id*/,
475 RootType /*root_type*/) {
476 CHECK(reinterpret_cast<MarkSweep*>(arg)->IsMarked(*root));
477}
478
Mathieu Chartier815873e2014-02-13 18:02:13 -0800479void MarkSweep::MarkRootCallback(Object** root, void* arg, uint32_t /*thread_id*/,
480 RootType /*root_type*/) {
Mathieu Chartier815873e2014-02-13 18:02:13 -0800481 reinterpret_cast<MarkSweep*>(arg)->MarkObjectNonNull(*root);
482}
483
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700484void MarkSweep::VerifyRootCallback(const Object* root, void* arg, size_t vreg,
Mathieu Chartier7bf9f192014-04-04 11:09:41 -0700485 const StackVisitor* visitor, RootType root_type) {
486 reinterpret_cast<MarkSweep*>(arg)->VerifyRoot(root, vreg, visitor, root_type);
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700487}
488
Mathieu Chartier7bf9f192014-04-04 11:09:41 -0700489void MarkSweep::VerifyRoot(const Object* root, size_t vreg, const StackVisitor* visitor,
490 RootType root_type) {
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700491 // See if the root is on any space bitmap.
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -0700492 if (heap_->GetLiveBitmap()->GetContinuousSpaceBitmap(root) == nullptr) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700493 space::LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
Mathieu Chartier4202b742012-10-17 17:51:25 -0700494 if (!large_object_space->Contains(root)) {
Mathieu Chartier7bf9f192014-04-04 11:09:41 -0700495 LOG(ERROR) << "Found invalid root: " << root << " with type " << root_type;
Ian Rogers40e3bac2012-11-20 00:09:14 -0800496 if (visitor != NULL) {
497 LOG(ERROR) << visitor->DescribeLocation() << " in VReg: " << vreg;
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700498 }
499 }
500 }
501}
502
503void MarkSweep::VerifyRoots() {
504 Runtime::Current()->GetThreadList()->VerifyRoots(VerifyRootCallback, this);
505}
506
Mathieu Chartier893263b2014-03-04 11:07:42 -0800507void MarkSweep::MarkRoots(Thread* self) {
508 if (Locks::mutator_lock_->IsExclusiveHeld(self)) {
509 // If we exclusively hold the mutator lock, all threads must be suspended.
510 timings_.StartSplit("MarkRoots");
511 Runtime::Current()->VisitRoots(MarkRootCallback, this);
512 timings_.EndSplit();
513 RevokeAllThreadLocalAllocationStacks(self);
514 } else {
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -0700515 MarkRootsCheckpoint(self, kRevokeRosAllocThreadLocalBuffersAtCheckpoint);
Mathieu Chartier893263b2014-03-04 11:07:42 -0800516 // At this point the live stack should no longer have any mutators which push into it.
517 MarkNonThreadRoots();
518 MarkConcurrentRoots(
519 static_cast<VisitRootFlags>(kVisitRootFlagAllRoots | kVisitRootFlagStartLoggingNewRoots));
520 }
Mathieu Chartier9ebae1f2012-10-15 17:38:16 -0700521}
522
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700523void MarkSweep::MarkNonThreadRoots() {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700524 timings_.StartSplit("MarkNonThreadRoots");
Mathieu Chartier423d2a32013-09-12 17:33:56 -0700525 Runtime::Current()->VisitNonThreadRoots(MarkRootCallback, this);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700526 timings_.EndSplit();
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700527}
528
Mathieu Chartier893263b2014-03-04 11:07:42 -0800529void MarkSweep::MarkConcurrentRoots(VisitRootFlags flags) {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700530 timings_.StartSplit("MarkConcurrentRoots");
Ian Rogers1d54e732013-05-02 21:10:01 -0700531 // Visit all runtime roots and clear dirty flags.
Mathieu Chartier893263b2014-03-04 11:07:42 -0800532 Runtime::Current()->VisitConcurrentRoots(MarkRootCallback, this, flags);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700533 timings_.EndSplit();
Carl Shapiro69759ea2011-07-21 18:13:35 -0700534}
535
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700536class ScanObjectVisitor {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700537 public:
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700538 explicit ScanObjectVisitor(MarkSweep* const mark_sweep) ALWAYS_INLINE
539 : mark_sweep_(mark_sweep) {}
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700540
Mathieu Chartier407f7022014-02-18 14:37:05 -0800541 void operator()(Object* obj) const ALWAYS_INLINE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
542 EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700543 if (kCheckLocks) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800544 Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
545 Locks::heap_bitmap_lock_->AssertExclusiveHeld(Thread::Current());
546 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700547 mark_sweep_->ScanObject(obj);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700548 }
549
550 private:
551 MarkSweep* const mark_sweep_;
552};
553
Mathieu Chartier407f7022014-02-18 14:37:05 -0800554class DelayReferenceReferentVisitor {
555 public:
556 explicit DelayReferenceReferentVisitor(MarkSweep* collector) : collector_(collector) {
557 }
558
559 void operator()(mirror::Class* klass, mirror::Reference* ref) const
560 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
561 EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
562 collector_->DelayReferenceReferent(klass, ref);
563 }
564
565 private:
566 MarkSweep* const collector_;
567};
568
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700569template <bool kUseFinger = false>
570class MarkStackTask : public Task {
571 public:
572 MarkStackTask(ThreadPool* thread_pool, MarkSweep* mark_sweep, size_t mark_stack_size,
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700573 Object** mark_stack)
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700574 : mark_sweep_(mark_sweep),
575 thread_pool_(thread_pool),
576 mark_stack_pos_(mark_stack_size) {
577 // We may have to copy part of an existing mark stack when another mark stack overflows.
578 if (mark_stack_size != 0) {
579 DCHECK(mark_stack != NULL);
580 // TODO: Check performance?
581 std::copy(mark_stack, mark_stack + mark_stack_size, mark_stack_);
Ian Rogers1d54e732013-05-02 21:10:01 -0700582 }
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700583 if (kCountTasks) {
584 ++mark_sweep_->work_chunks_created_;
585 }
586 }
587
588 static const size_t kMaxSize = 1 * KB;
589
590 protected:
Mathieu Chartier407f7022014-02-18 14:37:05 -0800591 class MarkObjectParallelVisitor {
592 public:
593 explicit MarkObjectParallelVisitor(MarkStackTask<kUseFinger>* chunk_task,
594 MarkSweep* mark_sweep) ALWAYS_INLINE
595 : chunk_task_(chunk_task), mark_sweep_(mark_sweep) {}
596
597 void operator()(Object* obj, MemberOffset offset, bool /* static */) const ALWAYS_INLINE
598 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersb0fa5dc2014-04-28 16:47:08 -0700599 mirror::Object* ref = obj->GetFieldObject<mirror::Object>(offset);
Mathieu Chartier407f7022014-02-18 14:37:05 -0800600 if (ref != nullptr && mark_sweep_->MarkObjectParallel(ref)) {
601 if (kUseFinger) {
602 android_memory_barrier();
603 if (reinterpret_cast<uintptr_t>(ref) >=
604 static_cast<uintptr_t>(mark_sweep_->atomic_finger_)) {
605 return;
606 }
607 }
608 chunk_task_->MarkStackPush(ref);
609 }
610 }
611
612 private:
613 MarkStackTask<kUseFinger>* const chunk_task_;
614 MarkSweep* const mark_sweep_;
615 };
616
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700617 class ScanObjectParallelVisitor {
618 public:
619 explicit ScanObjectParallelVisitor(MarkStackTask<kUseFinger>* chunk_task) ALWAYS_INLINE
620 : chunk_task_(chunk_task) {}
621
Mathieu Chartier407f7022014-02-18 14:37:05 -0800622 // No thread safety analysis since multiple threads will use this visitor.
623 void operator()(Object* obj) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
624 EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
625 MarkSweep* const mark_sweep = chunk_task_->mark_sweep_;
626 MarkObjectParallelVisitor mark_visitor(chunk_task_, mark_sweep);
627 DelayReferenceReferentVisitor ref_visitor(mark_sweep);
628 mark_sweep->ScanObjectVisit(obj, mark_visitor, ref_visitor);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700629 }
630
631 private:
632 MarkStackTask<kUseFinger>* const chunk_task_;
633 };
634
635 virtual ~MarkStackTask() {
636 // Make sure that we have cleared our mark stack.
637 DCHECK_EQ(mark_stack_pos_, 0U);
638 if (kCountTasks) {
639 ++mark_sweep_->work_chunks_deleted_;
640 }
641 }
642
643 MarkSweep* const mark_sweep_;
644 ThreadPool* const thread_pool_;
645 // Thread local mark stack for this task.
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700646 Object* mark_stack_[kMaxSize];
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700647 // Mark stack position.
648 size_t mark_stack_pos_;
649
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700650 void MarkStackPush(Object* obj) ALWAYS_INLINE {
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700651 if (UNLIKELY(mark_stack_pos_ == kMaxSize)) {
652 // Mark stack overflow, give 1/2 the stack to the thread pool as a new work task.
653 mark_stack_pos_ /= 2;
654 auto* task = new MarkStackTask(thread_pool_, mark_sweep_, kMaxSize - mark_stack_pos_,
655 mark_stack_ + mark_stack_pos_);
656 thread_pool_->AddTask(Thread::Current(), task);
657 }
658 DCHECK(obj != nullptr);
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700659 DCHECK_LT(mark_stack_pos_, kMaxSize);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700660 mark_stack_[mark_stack_pos_++] = obj;
661 }
662
663 virtual void Finalize() {
664 delete this;
665 }
666
667 // Scans all of the objects
Mathieu Chartier407f7022014-02-18 14:37:05 -0800668 virtual void Run(Thread* self) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
669 EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700670 ScanObjectParallelVisitor visitor(this);
671 // TODO: Tune this.
672 static const size_t kFifoSize = 4;
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700673 BoundedFifoPowerOfTwo<Object*, kFifoSize> prefetch_fifo;
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700674 for (;;) {
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700675 Object* obj = nullptr;
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700676 if (kUseMarkStackPrefetch) {
677 while (mark_stack_pos_ != 0 && prefetch_fifo.size() < kFifoSize) {
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700678 Object* obj = mark_stack_[--mark_stack_pos_];
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700679 DCHECK(obj != nullptr);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700680 __builtin_prefetch(obj);
681 prefetch_fifo.push_back(obj);
682 }
683 if (UNLIKELY(prefetch_fifo.empty())) {
684 break;
685 }
686 obj = prefetch_fifo.front();
687 prefetch_fifo.pop_front();
688 } else {
689 if (UNLIKELY(mark_stack_pos_ == 0)) {
690 break;
691 }
692 obj = mark_stack_[--mark_stack_pos_];
693 }
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700694 DCHECK(obj != nullptr);
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700695 visitor(obj);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700696 }
697 }
698};
699
700class CardScanTask : public MarkStackTask<false> {
701 public:
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -0700702 CardScanTask(ThreadPool* thread_pool, MarkSweep* mark_sweep,
703 accounting::ContinuousSpaceBitmap* bitmap,
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700704 byte* begin, byte* end, byte minimum_age, size_t mark_stack_size,
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700705 Object** mark_stack_obj)
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700706 : MarkStackTask<false>(thread_pool, mark_sweep, mark_stack_size, mark_stack_obj),
707 bitmap_(bitmap),
708 begin_(begin),
709 end_(end),
710 minimum_age_(minimum_age) {
711 }
712
713 protected:
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -0700714 accounting::ContinuousSpaceBitmap* const bitmap_;
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700715 byte* const begin_;
716 byte* const end_;
717 const byte minimum_age_;
718
719 virtual void Finalize() {
720 delete this;
721 }
722
723 virtual void Run(Thread* self) NO_THREAD_SAFETY_ANALYSIS {
724 ScanObjectParallelVisitor visitor(this);
725 accounting::CardTable* card_table = mark_sweep_->GetHeap()->GetCardTable();
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700726 size_t cards_scanned = card_table->Scan(bitmap_, begin_, end_, visitor, minimum_age_);
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700727 VLOG(heap) << "Parallel scanning cards " << reinterpret_cast<void*>(begin_) << " - "
728 << reinterpret_cast<void*>(end_) << " = " << cards_scanned;
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700729 // Finish by emptying our local mark stack.
730 MarkStackTask::Run(self);
731 }
732};
733
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700734size_t MarkSweep::GetThreadCount(bool paused) const {
735 if (heap_->GetThreadPool() == nullptr || !heap_->CareAboutPauseTimes()) {
Mathieu Chartierbbd695c2014-04-16 09:48:48 -0700736 return 1;
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700737 }
738 if (paused) {
739 return heap_->GetParallelGCThreadCount() + 1;
740 } else {
741 return heap_->GetConcGCThreadCount() + 1;
742 }
743}
744
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700745void MarkSweep::ScanGrayObjects(bool paused, byte minimum_age) {
746 accounting::CardTable* card_table = GetHeap()->GetCardTable();
747 ThreadPool* thread_pool = GetHeap()->GetThreadPool();
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700748 size_t thread_count = GetThreadCount(paused);
749 // The parallel version with only one thread is faster for card scanning, TODO: fix.
Mathieu Chartierbbd695c2014-04-16 09:48:48 -0700750 if (kParallelCardScan && thread_count > 1) {
Mathieu Chartier720ef762013-08-17 14:46:54 -0700751 Thread* self = Thread::Current();
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700752 // Can't have a different split for each space since multiple spaces can have their cards being
753 // scanned at the same time.
754 timings_.StartSplit(paused ? "(Paused)ScanGrayObjects" : "ScanGrayObjects");
755 // Try to take some of the mark stack since we can pass this off to the worker tasks.
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700756 Object** mark_stack_begin = mark_stack_->Begin();
757 Object** mark_stack_end = mark_stack_->End();
Mathieu Chartier720ef762013-08-17 14:46:54 -0700758 const size_t mark_stack_size = mark_stack_end - mark_stack_begin;
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700759 // Estimated number of work tasks we will create.
760 const size_t mark_stack_tasks = GetHeap()->GetContinuousSpaces().size() * thread_count;
761 DCHECK_NE(mark_stack_tasks, 0U);
762 const size_t mark_stack_delta = std::min(CardScanTask::kMaxSize / 2,
763 mark_stack_size / mark_stack_tasks + 1);
764 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700765 if (space->GetMarkBitmap() == nullptr) {
766 continue;
767 }
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700768 byte* card_begin = space->Begin();
769 byte* card_end = space->End();
Hiroshi Yamauchi0941b042013-11-05 11:34:03 -0800770 // Align up the end address. For example, the image space's end
771 // may not be card-size-aligned.
772 card_end = AlignUp(card_end, accounting::CardTable::kCardSize);
773 DCHECK(IsAligned<accounting::CardTable::kCardSize>(card_begin));
774 DCHECK(IsAligned<accounting::CardTable::kCardSize>(card_end));
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700775 // Calculate how many bytes of heap we will scan,
776 const size_t address_range = card_end - card_begin;
777 // Calculate how much address range each task gets.
778 const size_t card_delta = RoundUp(address_range / thread_count + 1,
779 accounting::CardTable::kCardSize);
780 // Create the worker tasks for this space.
781 while (card_begin != card_end) {
782 // Add a range of cards.
783 size_t addr_remaining = card_end - card_begin;
784 size_t card_increment = std::min(card_delta, addr_remaining);
785 // Take from the back of the mark stack.
786 size_t mark_stack_remaining = mark_stack_end - mark_stack_begin;
787 size_t mark_stack_increment = std::min(mark_stack_delta, mark_stack_remaining);
788 mark_stack_end -= mark_stack_increment;
789 mark_stack_->PopBackCount(static_cast<int32_t>(mark_stack_increment));
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700790 DCHECK_EQ(mark_stack_end, mark_stack_->End());
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700791 // Add the new task to the thread pool.
792 auto* task = new CardScanTask(thread_pool, this, space->GetMarkBitmap(), card_begin,
793 card_begin + card_increment, minimum_age,
794 mark_stack_increment, mark_stack_end);
795 thread_pool->AddTask(self, task);
796 card_begin += card_increment;
797 }
798 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700799
Hiroshi Yamauchi0941b042013-11-05 11:34:03 -0800800 // Note: the card scan below may dirty new cards (and scan them)
801 // as a side effect when a Reference object is encountered and
802 // queued during the marking. See b/11465268.
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700803 thread_pool->SetMaxActiveWorkers(thread_count - 1);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700804 thread_pool->StartWorkers(self);
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700805 thread_pool->Wait(self, true, true);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700806 thread_pool->StopWorkers(self);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700807 timings_.EndSplit();
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700808 } else {
809 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700810 if (space->GetMarkBitmap() != nullptr) {
811 // Image spaces are handled properly since live == marked for them.
812 switch (space->GetGcRetentionPolicy()) {
813 case space::kGcRetentionPolicyNeverCollect:
814 timings_.StartSplit(paused ? "(Paused)ScanGrayImageSpaceObjects" :
815 "ScanGrayImageSpaceObjects");
816 break;
817 case space::kGcRetentionPolicyFullCollect:
818 timings_.StartSplit(paused ? "(Paused)ScanGrayZygoteSpaceObjects" :
819 "ScanGrayZygoteSpaceObjects");
820 break;
821 case space::kGcRetentionPolicyAlwaysCollect:
822 timings_.StartSplit(paused ? "(Paused)ScanGrayAllocSpaceObjects" :
823 "ScanGrayAllocSpaceObjects");
824 break;
825 }
826 ScanObjectVisitor visitor(this);
827 card_table->Scan(space->GetMarkBitmap(), space->Begin(), space->End(), visitor, minimum_age);
828 timings_.EndSplit();
829 }
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700830 }
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700831 }
832}
833
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700834class RecursiveMarkTask : public MarkStackTask<false> {
835 public:
836 RecursiveMarkTask(ThreadPool* thread_pool, MarkSweep* mark_sweep,
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -0700837 accounting::ContinuousSpaceBitmap* bitmap, uintptr_t begin, uintptr_t end)
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700838 : MarkStackTask<false>(thread_pool, mark_sweep, 0, NULL),
839 bitmap_(bitmap),
840 begin_(begin),
841 end_(end) {
842 }
843
844 protected:
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -0700845 accounting::ContinuousSpaceBitmap* const bitmap_;
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700846 const uintptr_t begin_;
847 const uintptr_t end_;
848
849 virtual void Finalize() {
850 delete this;
851 }
852
853 // Scans all of the objects
854 virtual void Run(Thread* self) NO_THREAD_SAFETY_ANALYSIS {
855 ScanObjectParallelVisitor visitor(this);
856 bitmap_->VisitMarkedRange(begin_, end_, visitor);
857 // Finish by emptying our local mark stack.
858 MarkStackTask::Run(self);
859 }
860};
861
Carl Shapiro58551df2011-07-24 03:09:51 -0700862// Populates the mark stack based on the set of marked objects and
863// recursively marks until the mark stack is emptied.
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800864void MarkSweep::RecursiveMark() {
Ian Rogers5fe9af72013-11-14 00:17:20 -0800865 TimingLogger::ScopedSplit split("RecursiveMark", &timings_);
Mathieu Chartiera1602f22014-01-13 17:19:19 -0800866 // RecursiveMark will build the lists of known instances of the Reference classes. See
867 // DelayReferenceReferent for details.
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700868 if (kUseRecursiveMark) {
869 const bool partial = GetGcType() == kGcTypePartial;
870 ScanObjectVisitor scan_visitor(this);
871 auto* self = Thread::Current();
872 ThreadPool* thread_pool = heap_->GetThreadPool();
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700873 size_t thread_count = GetThreadCount(false);
874 const bool parallel = kParallelRecursiveMark && thread_count > 1;
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700875 mark_stack_->Reset();
Mathieu Chartier02e25112013-08-14 16:14:24 -0700876 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700877 if ((space->GetGcRetentionPolicy() == space::kGcRetentionPolicyAlwaysCollect) ||
878 (!partial && space->GetGcRetentionPolicy() == space::kGcRetentionPolicyFullCollect)) {
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700879 current_space_bitmap_ = space->GetMarkBitmap();
880 if (current_space_bitmap_ == nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700881 continue;
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800882 }
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700883 if (parallel) {
884 // We will use the mark stack the future.
885 // CHECK(mark_stack_->IsEmpty());
886 // This function does not handle heap end increasing, so we must use the space end.
887 uintptr_t begin = reinterpret_cast<uintptr_t>(space->Begin());
888 uintptr_t end = reinterpret_cast<uintptr_t>(space->End());
889 atomic_finger_ = static_cast<int32_t>(0xFFFFFFFF);
890
891 // Create a few worker tasks.
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700892 const size_t n = thread_count * 2;
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700893 while (begin != end) {
894 uintptr_t start = begin;
895 uintptr_t delta = (end - begin) / n;
896 delta = RoundUp(delta, KB);
897 if (delta < 16 * KB) delta = end - begin;
898 begin += delta;
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700899 auto* task = new RecursiveMarkTask(thread_pool, this, current_space_bitmap_, start,
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700900 begin);
901 thread_pool->AddTask(self, task);
902 }
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700903 thread_pool->SetMaxActiveWorkers(thread_count - 1);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700904 thread_pool->StartWorkers(self);
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700905 thread_pool->Wait(self, true, true);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700906 thread_pool->StopWorkers(self);
907 } else {
908 // This function does not handle heap end increasing, so we must use the space end.
909 uintptr_t begin = reinterpret_cast<uintptr_t>(space->Begin());
910 uintptr_t end = reinterpret_cast<uintptr_t>(space->End());
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700911 current_space_bitmap_->VisitMarkedRange(begin, end, scan_visitor);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700912 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700913 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700914 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700915 }
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700916 ProcessMarkStack(false);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700917}
918
Mathieu Chartier83c8ee02014-01-28 14:50:23 -0800919mirror::Object* MarkSweep::IsMarkedCallback(mirror::Object* object, void* arg) {
Mathieu Chartier5712d5d2013-09-18 17:59:36 -0700920 if (reinterpret_cast<MarkSweep*>(arg)->IsMarked(object)) {
Mathieu Chartier6aa3df92013-09-17 15:17:28 -0700921 return object;
922 }
923 return nullptr;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700924}
925
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700926void MarkSweep::RecursiveMarkDirtyObjects(bool paused, byte minimum_age) {
927 ScanGrayObjects(paused, minimum_age);
928 ProcessMarkStack(paused);
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700929}
930
Carl Shapiro58551df2011-07-24 03:09:51 -0700931void MarkSweep::ReMarkRoots() {
Mathieu Chartier893263b2014-03-04 11:07:42 -0800932 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartier3bb57c72014-02-18 11:38:45 -0800933 timings_.StartSplit("(Paused)ReMarkRoots");
Mathieu Chartier893263b2014-03-04 11:07:42 -0800934 Runtime::Current()->VisitRoots(
935 MarkRootCallback, this, static_cast<VisitRootFlags>(kVisitRootFlagNewRoots |
936 kVisitRootFlagStopLoggingNewRoots |
937 kVisitRootFlagClearRootLog));
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700938 timings_.EndSplit();
Mathieu Chartier7bf9f192014-04-04 11:09:41 -0700939 if (kVerifyRootsMarked) {
Mathieu Chartier893263b2014-03-04 11:07:42 -0800940 timings_.StartSplit("(Paused)VerifyRoots");
941 Runtime::Current()->VisitRoots(VerifyRootMarked, this);
942 timings_.EndSplit();
943 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700944}
945
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -0700946void MarkSweep::SweepSystemWeaks(Thread* self) {
947 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700948 timings_.StartSplit("SweepSystemWeaks");
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -0700949 Runtime::Current()->SweepSystemWeaks(IsMarkedCallback, this);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700950 timings_.EndSplit();
Carl Shapiro58551df2011-07-24 03:09:51 -0700951}
952
Mathieu Chartier6aa3df92013-09-17 15:17:28 -0700953mirror::Object* MarkSweep::VerifySystemWeakIsLiveCallback(Object* obj, void* arg) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700954 reinterpret_cast<MarkSweep*>(arg)->VerifyIsLive(obj);
955 // We don't actually want to sweep the object, so lets return "marked"
Mathieu Chartier6aa3df92013-09-17 15:17:28 -0700956 return obj;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700957}
958
959void MarkSweep::VerifyIsLive(const Object* obj) {
Mathieu Chartier4aeec172014-03-27 16:09:46 -0700960 if (!heap_->GetLiveBitmap()->Test(obj)) {
Mathieu Chartierbbd695c2014-04-16 09:48:48 -0700961 if (std::find(heap_->allocation_stack_->Begin(), heap_->allocation_stack_->End(), obj) ==
962 heap_->allocation_stack_->End()) {
963 // Object not found!
964 heap_->DumpSpaces();
965 LOG(FATAL) << "Found dead object " << obj;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700966 }
967 }
968}
969
970void MarkSweep::VerifySystemWeaks() {
Mathieu Chartier6aa3df92013-09-17 15:17:28 -0700971 // Verify system weaks, uses a special object visitor which returns the input object.
972 Runtime::Current()->SweepSystemWeaks(VerifySystemWeakIsLiveCallback, this);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700973}
974
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700975class CheckpointMarkThreadRoots : public Closure {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700976 public:
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -0700977 explicit CheckpointMarkThreadRoots(MarkSweep* mark_sweep,
978 bool revoke_ros_alloc_thread_local_buffers_at_checkpoint)
979 : mark_sweep_(mark_sweep),
980 revoke_ros_alloc_thread_local_buffers_at_checkpoint_(
981 revoke_ros_alloc_thread_local_buffers_at_checkpoint) {
982 }
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700983
Mathieu Chartier4aeec172014-03-27 16:09:46 -0700984 virtual void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier3f966702013-09-04 16:50:05 -0700985 ATRACE_BEGIN("Marking thread roots");
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700986 // Note: self is not necessarily equal to thread since thread may be suspended.
987 Thread* self = Thread::Current();
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800988 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
989 << thread->GetState() << " thread " << thread << " self " << self;
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800990 thread->VisitRoots(MarkSweep::MarkRootParallelCallback, mark_sweep_);
Mathieu Chartier3f966702013-09-04 16:50:05 -0700991 ATRACE_END();
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -0700992 if (revoke_ros_alloc_thread_local_buffers_at_checkpoint_) {
993 ATRACE_BEGIN("RevokeRosAllocThreadLocalBuffers");
Hiroshi Yamauchic93c5302014-03-20 16:15:37 -0700994 mark_sweep_->GetHeap()->RevokeRosAllocThreadLocalBuffers(thread);
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -0700995 ATRACE_END();
Hiroshi Yamauchic93c5302014-03-20 16:15:37 -0700996 }
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700997 mark_sweep_->GetBarrier().Pass(self);
998 }
999
1000 private:
Mathieu Chartier4aeec172014-03-27 16:09:46 -07001001 MarkSweep* const mark_sweep_;
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -07001002 const bool revoke_ros_alloc_thread_local_buffers_at_checkpoint_;
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001003};
1004
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -07001005void MarkSweep::MarkRootsCheckpoint(Thread* self,
1006 bool revoke_ros_alloc_thread_local_buffers_at_checkpoint) {
1007 CheckpointMarkThreadRoots check_point(this, revoke_ros_alloc_thread_local_buffers_at_checkpoint);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001008 timings_.StartSplit("MarkRootsCheckpoint");
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001009 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Ian Rogers1d54e732013-05-02 21:10:01 -07001010 // Request the check point is run on all threads returning a count of the threads that must
1011 // run through the barrier including self.
1012 size_t barrier_count = thread_list->RunCheckpoint(&check_point);
1013 // Release locks then wait for all mutator threads to pass the barrier.
1014 // TODO: optimize to not release locks when there are no threads to wait for.
1015 Locks::heap_bitmap_lock_->ExclusiveUnlock(self);
1016 Locks::mutator_lock_->SharedUnlock(self);
Mathieu Chartier4aeec172014-03-27 16:09:46 -07001017 {
1018 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
1019 gc_barrier_->Increment(self, barrier_count);
1020 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001021 Locks::mutator_lock_->SharedLock(self);
1022 Locks::heap_bitmap_lock_->ExclusiveLock(self);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001023 timings_.EndSplit();
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001024}
1025
Ian Rogers1d54e732013-05-02 21:10:01 -07001026void MarkSweep::SweepArray(accounting::ObjectStack* allocations, bool swap_bitmaps) {
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001027 timings_.StartSplit("SweepArray");
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001028 Thread* self = Thread::Current();
1029 mirror::Object* chunk_free_buffer[kSweepArrayChunkFreeSize];
1030 size_t chunk_free_pos = 0;
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001031 size_t freed_bytes = 0;
1032 size_t freed_large_object_bytes = 0;
Hiroshi Yamauchib22a4512013-08-13 15:03:22 -07001033 size_t freed_objects = 0;
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001034 size_t freed_large_objects = 0;
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001035 // How many objects are left in the array, modified after each space is swept.
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -07001036 Object** objects = allocations->Begin();
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001037 size_t count = allocations->Size();
1038 // Change the order to ensure that the non-moving space last swept as an optimization.
1039 std::vector<space::ContinuousSpace*> sweep_spaces;
1040 space::ContinuousSpace* non_moving_space = nullptr;
1041 for (space::ContinuousSpace* space : heap_->GetContinuousSpaces()) {
Mathieu Chartier8d562102014-03-12 17:42:10 -07001042 if (space->IsAllocSpace() && !immune_region_.ContainsSpace(space) &&
1043 space->GetLiveBitmap() != nullptr) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001044 if (space == heap_->GetNonMovingSpace()) {
1045 non_moving_space = space;
1046 } else {
1047 sweep_spaces.push_back(space);
1048 }
1049 }
1050 }
1051 // Unlikely to sweep a significant amount of non_movable objects, so we do these after the after
1052 // the other alloc spaces as an optimization.
1053 if (non_moving_space != nullptr) {
1054 sweep_spaces.push_back(non_moving_space);
1055 }
1056 // Start by sweeping the continuous spaces.
1057 for (space::ContinuousSpace* space : sweep_spaces) {
1058 space::AllocSpace* alloc_space = space->AsAllocSpace();
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -07001059 accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
1060 accounting::ContinuousSpaceBitmap* mark_bitmap = space->GetMarkBitmap();
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001061 if (swap_bitmaps) {
1062 std::swap(live_bitmap, mark_bitmap);
1063 }
1064 Object** out = objects;
1065 for (size_t i = 0; i < count; ++i) {
1066 Object* obj = objects[i];
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08001067 if (kUseThreadLocalAllocationStack && obj == nullptr) {
1068 continue;
1069 }
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001070 if (space->HasAddress(obj)) {
1071 // This object is in the space, remove it from the array and add it to the sweep buffer
1072 // if needed.
1073 if (!mark_bitmap->Test(obj)) {
1074 if (chunk_free_pos >= kSweepArrayChunkFreeSize) {
1075 timings_.StartSplit("FreeList");
1076 freed_objects += chunk_free_pos;
1077 freed_bytes += alloc_space->FreeList(self, chunk_free_pos, chunk_free_buffer);
1078 timings_.EndSplit();
1079 chunk_free_pos = 0;
1080 }
1081 chunk_free_buffer[chunk_free_pos++] = obj;
1082 }
1083 } else {
1084 *(out++) = obj;
1085 }
1086 }
1087 if (chunk_free_pos > 0) {
1088 timings_.StartSplit("FreeList");
1089 freed_objects += chunk_free_pos;
1090 freed_bytes += alloc_space->FreeList(self, chunk_free_pos, chunk_free_buffer);
1091 timings_.EndSplit();
1092 chunk_free_pos = 0;
1093 }
1094 // All of the references which space contained are no longer in the allocation stack, update
1095 // the count.
1096 count = out - objects;
1097 }
1098 // Handle the large object space.
1099 space::LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
Mathieu Chartierbbd695c2014-04-16 09:48:48 -07001100 accounting::LargeObjectBitmap* large_live_objects = large_object_space->GetLiveBitmap();
1101 accounting::LargeObjectBitmap* large_mark_objects = large_object_space->GetMarkBitmap();
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001102 if (swap_bitmaps) {
1103 std::swap(large_live_objects, large_mark_objects);
1104 }
Brian Carlstrom02c8cc62013-07-18 15:54:44 -07001105 for (size_t i = 0; i < count; ++i) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001106 Object* obj = objects[i];
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001107 // Handle large objects.
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08001108 if (kUseThreadLocalAllocationStack && obj == nullptr) {
1109 continue;
1110 }
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001111 if (!large_mark_objects->Test(obj)) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001112 ++freed_large_objects;
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001113 freed_large_object_bytes += large_object_space->Free(self, obj);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001114 }
1115 }
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001116 timings_.EndSplit();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001117
Hiroshi Yamauchib22a4512013-08-13 15:03:22 -07001118 timings_.StartSplit("RecordFree");
Mathieu Chartiere76e70f2014-05-02 16:35:37 -07001119 VLOG(heap) << "Freed " << freed_objects << "/" << count << " objects with size "
1120 << PrettySize(freed_bytes);
1121 RecordFree(freed_objects, freed_bytes);
1122 RecordFreeLargeObjects(freed_large_objects, freed_large_object_bytes);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001123 timings_.EndSplit();
Ian Rogers1d54e732013-05-02 21:10:01 -07001124
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001125 timings_.StartSplit("ResetStack");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001126 allocations->Reset();
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001127 timings_.EndSplit();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001128}
1129
Ian Rogers1d54e732013-05-02 21:10:01 -07001130void MarkSweep::Sweep(bool swap_bitmaps) {
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -07001131 // Ensure that nobody inserted items in the live stack after we swapped the stacks.
1132 CHECK_GE(live_stack_freeze_size_, GetHeap()->GetLiveStack()->Size());
1133 // Mark everything allocated since the last as GC live so that we can sweep concurrently,
1134 // knowing that new allocations won't be marked as live.
1135 timings_.StartSplit("MarkStackAsLive");
1136 accounting::ObjectStack* live_stack = heap_->GetLiveStack();
1137 heap_->MarkAllocStackAsLive(live_stack);
1138 live_stack->Reset();
1139 timings_.EndSplit();
1140
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001141 DCHECK(mark_stack_->IsEmpty());
Mathieu Chartier02e25112013-08-14 16:14:24 -07001142 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Mathieu Chartiera1602f22014-01-13 17:19:19 -08001143 if (space->IsContinuousMemMapAllocSpace()) {
1144 space::ContinuousMemMapAllocSpace* alloc_space = space->AsContinuousMemMapAllocSpace();
Mathieu Chartierec050072014-01-07 16:00:07 -08001145 TimingLogger::ScopedSplit split(
Mathieu Chartiera1602f22014-01-13 17:19:19 -08001146 alloc_space->IsZygoteSpace() ? "SweepZygoteSpace" : "SweepMallocSpace", &timings_);
Mathieu Chartierec050072014-01-07 16:00:07 -08001147 size_t freed_objects = 0;
1148 size_t freed_bytes = 0;
Mathieu Chartiera1602f22014-01-13 17:19:19 -08001149 alloc_space->Sweep(swap_bitmaps, &freed_objects, &freed_bytes);
Mathieu Chartiere76e70f2014-05-02 16:35:37 -07001150 RecordFree(freed_objects, freed_bytes);
Carl Shapiro58551df2011-07-24 03:09:51 -07001151 }
1152 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001153 SweepLargeObjects(swap_bitmaps);
Carl Shapiro58551df2011-07-24 03:09:51 -07001154}
1155
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001156void MarkSweep::SweepLargeObjects(bool swap_bitmaps) {
Mathieu Chartierbbd695c2014-04-16 09:48:48 -07001157 TimingLogger::ScopedSplit split("SweepLargeObjects", &timings_);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001158 size_t freed_objects = 0;
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001159 size_t freed_bytes = 0;
Mathieu Chartierbbd695c2014-04-16 09:48:48 -07001160 heap_->GetLargeObjectsSpace()->Sweep(swap_bitmaps, &freed_objects, &freed_bytes);
Mathieu Chartiere76e70f2014-05-02 16:35:37 -07001161 RecordFreeLargeObjects(freed_objects, freed_bytes);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001162}
1163
Mathieu Chartier407f7022014-02-18 14:37:05 -08001164// Process the "referent" field in a java.lang.ref.Reference. If the referent has not yet been
1165// marked, put it on the appropriate list in the heap for later processing.
1166void MarkSweep::DelayReferenceReferent(mirror::Class* klass, mirror::Reference* ref) {
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001167 DCHECK(klass != nullptr);
Mathieu Chartier0e54cd02014-03-20 12:41:23 -07001168 if (kCountJavaLangRefs) {
1169 ++reference_count_;
1170 }
Mathieu Chartier407f7022014-02-18 14:37:05 -08001171 heap_->DelayReferenceReferent(klass, ref, IsMarkedCallback, this);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001172}
1173
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001174class MarkObjectVisitor {
1175 public:
Mathieu Chartier407f7022014-02-18 14:37:05 -08001176 explicit MarkObjectVisitor(MarkSweep* const mark_sweep) ALWAYS_INLINE : mark_sweep_(mark_sweep) {
1177 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001178
Mathieu Chartier407f7022014-02-18 14:37:05 -08001179 void operator()(Object* obj, MemberOffset offset, bool /* is_static */) const
1180 ALWAYS_INLINE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1181 EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001182 if (kCheckLocks) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001183 Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
1184 Locks::heap_bitmap_lock_->AssertExclusiveHeld(Thread::Current());
1185 }
Ian Rogersb0fa5dc2014-04-28 16:47:08 -07001186 mark_sweep_->MarkObject(obj->GetFieldObject<mirror::Object>(offset));
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001187 }
1188
1189 private:
1190 MarkSweep* const mark_sweep_;
1191};
1192
Carl Shapiro69759ea2011-07-21 18:13:35 -07001193// Scans an object reference. Determines the type of the reference
1194// and dispatches to a specialized scanning routine.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001195void MarkSweep::ScanObject(Object* obj) {
Mathieu Chartier407f7022014-02-18 14:37:05 -08001196 MarkObjectVisitor mark_visitor(this);
1197 DelayReferenceReferentVisitor ref_visitor(this);
1198 ScanObjectVisit(obj, mark_visitor, ref_visitor);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001199}
1200
Mathieu Chartier3bb57c72014-02-18 11:38:45 -08001201void MarkSweep::ProcessMarkStackPausedCallback(void* arg) {
Mathieu Chartier3bb57c72014-02-18 11:38:45 -08001202 reinterpret_cast<MarkSweep*>(arg)->ProcessMarkStack(true);
1203}
1204
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001205void MarkSweep::ProcessMarkStackParallel(size_t thread_count) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001206 Thread* self = Thread::Current();
1207 ThreadPool* thread_pool = GetHeap()->GetThreadPool();
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001208 const size_t chunk_size = std::min(mark_stack_->Size() / thread_count + 1,
1209 static_cast<size_t>(MarkStackTask<false>::kMaxSize));
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001210 CHECK_GT(chunk_size, 0U);
1211 // Split the current mark stack up into work tasks.
1212 for (mirror::Object **it = mark_stack_->Begin(), **end = mark_stack_->End(); it < end; ) {
1213 const size_t delta = std::min(static_cast<size_t>(end - it), chunk_size);
Mathieu Chartier0e54cd02014-03-20 12:41:23 -07001214 thread_pool->AddTask(self, new MarkStackTask<false>(thread_pool, this, delta, it));
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001215 it += delta;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001216 }
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001217 thread_pool->SetMaxActiveWorkers(thread_count - 1);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001218 thread_pool->StartWorkers(self);
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001219 thread_pool->Wait(self, true, true);
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001220 thread_pool->StopWorkers(self);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001221 mark_stack_->Reset();
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001222 CHECK_EQ(work_chunks_created_, work_chunks_deleted_) << " some of the work chunks were leaked";
Carl Shapiro69759ea2011-07-21 18:13:35 -07001223}
1224
Ian Rogers5d76c432011-10-31 21:42:49 -07001225// Scan anything that's on the mark stack.
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001226void MarkSweep::ProcessMarkStack(bool paused) {
Mathieu Chartier3bb57c72014-02-18 11:38:45 -08001227 timings_.StartSplit(paused ? "(Paused)ProcessMarkStack" : "ProcessMarkStack");
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001228 size_t thread_count = GetThreadCount(paused);
1229 if (kParallelProcessMarkStack && thread_count > 1 &&
1230 mark_stack_->Size() >= kMinimumParallelMarkStackSize) {
1231 ProcessMarkStackParallel(thread_count);
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001232 } else {
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001233 // TODO: Tune this.
1234 static const size_t kFifoSize = 4;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001235 BoundedFifoPowerOfTwo<Object*, kFifoSize> prefetch_fifo;
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001236 for (;;) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001237 Object* obj = NULL;
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001238 if (kUseMarkStackPrefetch) {
1239 while (!mark_stack_->IsEmpty() && prefetch_fifo.size() < kFifoSize) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001240 Object* obj = mark_stack_->PopBack();
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001241 DCHECK(obj != NULL);
1242 __builtin_prefetch(obj);
1243 prefetch_fifo.push_back(obj);
1244 }
1245 if (prefetch_fifo.empty()) {
1246 break;
1247 }
1248 obj = prefetch_fifo.front();
1249 prefetch_fifo.pop_front();
1250 } else {
1251 if (mark_stack_->IsEmpty()) {
1252 break;
1253 }
1254 obj = mark_stack_->PopBack();
1255 }
Mathieu Chartier4aeec172014-03-27 16:09:46 -07001256 DCHECK(obj != nullptr);
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001257 ScanObject(obj);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001258 }
1259 }
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001260 timings_.EndSplit();
Carl Shapiro69759ea2011-07-21 18:13:35 -07001261}
1262
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001263inline bool MarkSweep::IsMarked(const Object* object) const
1264 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
Mathieu Chartier8d562102014-03-12 17:42:10 -07001265 if (immune_region_.ContainsObject(object)) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001266 return true;
1267 }
Mathieu Chartier0e54cd02014-03-20 12:41:23 -07001268 if (current_space_bitmap_->HasAddress(object)) {
1269 return current_space_bitmap_->Test(object);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001270 }
Mathieu Chartier0e54cd02014-03-20 12:41:23 -07001271 return mark_bitmap_->Test(object);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001272}
1273
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001274void MarkSweep::FinishPhase() {
Ian Rogers5fe9af72013-11-14 00:17:20 -08001275 TimingLogger::ScopedSplit split("FinishPhase", &timings_);
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001276 if (kCountScannedTypes) {
1277 VLOG(gc) << "MarkSweep scanned classes=" << class_count_ << " arrays=" << array_count_
1278 << " other=" << other_count_;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001279 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001280 if (kCountTasks) {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001281 VLOG(gc) << "Total number of work chunks allocated: " << work_chunks_created_;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001282 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001283 if (kMeasureOverhead) {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001284 VLOG(gc) << "Overhead time " << PrettyDuration(overhead_time_);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001285 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001286 if (kProfileLargeObjects) {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001287 VLOG(gc) << "Large objects tested " << large_object_test_ << " marked " << large_object_mark_;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001288 }
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001289 if (kCountJavaLangRefs) {
1290 VLOG(gc) << "References scanned " << reference_count_;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001291 }
Mathieu Chartier0e54cd02014-03-20 12:41:23 -07001292 if (kCountMarkedObjects) {
1293 VLOG(gc) << "Marked: null=" << mark_null_count_ << " immune=" << mark_immune_count_
1294 << " fastpath=" << mark_fastpath_count_ << " slowpath=" << mark_slowpath_count_;
1295 }
Mathieu Chartier4aeec172014-03-27 16:09:46 -07001296 CHECK(mark_stack_->IsEmpty()); // Ensure that the mark stack is empty.
Mathieu Chartier5301cd22012-05-31 12:11:36 -07001297 mark_stack_->Reset();
Mathieu Chartier4aeec172014-03-27 16:09:46 -07001298 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
1299 heap_->ClearMarkedObjects();
Carl Shapiro69759ea2011-07-21 18:13:35 -07001300}
1301
Hiroshi Yamauchic93c5302014-03-20 16:15:37 -07001302void MarkSweep::RevokeAllThreadLocalBuffers() {
1303 if (kRevokeRosAllocThreadLocalBuffersAtCheckpoint && IsConcurrent()) {
1304 // If concurrent, rosalloc thread-local buffers are revoked at the
1305 // thread checkpoint. Bump pointer space thread-local buffers must
1306 // not be in use.
1307 GetHeap()->AssertAllBumpPointerSpaceThreadLocalBuffersAreRevoked();
1308 } else {
1309 timings_.StartSplit("(Paused)RevokeAllThreadLocalBuffers");
1310 GetHeap()->RevokeAllThreadLocalBuffers();
1311 timings_.EndSplit();
1312 }
1313}
1314
Ian Rogers1d54e732013-05-02 21:10:01 -07001315} // namespace collector
1316} // namespace gc
Carl Shapiro69759ea2011-07-21 18:13:35 -07001317} // namespace art