blob: ca2d0bd6db57c30750e251eb365f9da92b964fc8 [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 Chartier893263b2014-03-04 11:07:42 -080079static constexpr bool kVerifyRoots = 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)),
Ian Rogers62d6c772013-02-27 08:32:07 -0800102 large_object_lock_("mark sweep large object lock", kMarkSweepLargeObjectLock),
Mathieu Chartier958291c2013-08-27 18:14:55 -0700103 mark_stack_lock_("mark sweep mark stack lock", kMarkSweepMarkStackLock),
Mathieu Chartier590fee92013-09-13 13:46:47 -0700104 is_concurrent_(is_concurrent) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800105}
106
107void MarkSweep::InitializePhase() {
Ian Rogers1d54e732013-05-02 21:10:01 -0700108 timings_.Reset();
Ian Rogers5fe9af72013-11-14 00:17:20 -0800109 TimingLogger::ScopedSplit split("InitializePhase", &timings_);
Mathieu Chartiere53225c2013-08-19 10:59:11 -0700110 mark_stack_ = heap_->mark_stack_.get();
111 DCHECK(mark_stack_ != nullptr);
Mathieu Chartier8d562102014-03-12 17:42:10 -0700112 immune_region_.Reset();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800113 class_count_ = 0;
114 array_count_ = 0;
115 other_count_ = 0;
116 large_object_test_ = 0;
117 large_object_mark_ = 0;
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800118 overhead_time_ = 0;
119 work_chunks_created_ = 0;
120 work_chunks_deleted_ = 0;
121 reference_count_ = 0;
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700122 mark_null_count_ = 0;
123 mark_immune_count_ = 0;
124 mark_fastpath_count_ = 0;
125 mark_slowpath_count_ = 0;
126 FindDefaultSpaceBitmap();
127 {
128 // TODO: I don't think we should need heap bitmap lock to get the mark bitmap.
129 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
130 mark_bitmap_ = heap_->GetMarkBitmap();
131 }
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700132
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700133 // Do any pre GC verification.
Anwar Ghuloum46543222013-08-12 09:28:42 -0700134 timings_.NewSplit("PreGcVerification");
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800135 heap_->PreGcVerification(this);
136}
137
138void MarkSweep::ProcessReferences(Thread* self) {
Ian Rogers5fe9af72013-11-14 00:17:20 -0800139 TimingLogger::ScopedSplit split("ProcessReferences", &timings_);
Mathieu Chartier8e56c7e2012-11-20 13:25:50 -0800140 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier39e32612013-11-12 16:28:05 -0800141 GetHeap()->ProcessReferences(timings_, clear_soft_references_, &IsMarkedCallback,
Mathieu Chartier3bb57c72014-02-18 11:38:45 -0800142 &MarkObjectCallback, &ProcessMarkStackPausedCallback, this);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800143}
144
Mathieu Chartier601276a2014-03-20 15:12:30 -0700145void MarkSweep::PreProcessReferences() {
146 if (IsConcurrent()) {
147 // No reason to do this for non-concurrent GC since pre processing soft references only helps
148 // pauses.
149 timings_.NewSplit("PreProcessReferences");
150 GetHeap()->ProcessSoftReferences(timings_, clear_soft_references_, &IsMarkedCallback,
151 &MarkObjectCallback, &ProcessMarkStackPausedCallback, this);
152 }
Mathieu Chartier1ad27842014-03-19 17:08:17 -0700153}
154
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -0700155void MarkSweep::PausePhase() {
156 TimingLogger::ScopedSplit split("(Paused)PausePhase", &timings_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800157 Thread* self = Thread::Current();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800158 Locks::mutator_lock_->AssertExclusiveHeld(self);
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -0700159 if (IsConcurrent()) {
160 // Handle the dirty objects if we are a concurrent GC.
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800161 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800162 // Re-mark root set.
163 ReMarkRoots();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800164 // Scan dirty objects, this is only required if we are not doing concurrent GC.
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700165 RecursiveMarkDirtyObjects(true, accounting::CardTable::kCardDirty);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800166 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800167 ProcessReferences(self);
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -0700168 {
169 timings_.NewSplit("SwapStacks");
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800170 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -0700171 heap_->SwapStacks(self);
172 live_stack_freeze_size_ = heap_->GetLiveStack()->Size();
173 // Need to revoke all the thread local allocation stacks since we just swapped the allocation
174 // stacks and don't want anybody to allocate into the live stack.
Mathieu Chartierc22c59e2014-02-24 15:16:06 -0800175 RevokeAllThreadLocalAllocationStacks(self);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800176 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700177 timings_.StartSplit("PreSweepingGcVerification");
178 heap_->PreSweepingGcVerification(this);
179 timings_.EndSplit();
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -0700180 if (IsConcurrent()) {
181 // Disallow new system weaks to prevent a race which occurs when someone adds a new system
182 // weak before we sweep them. Since this new system weak may not be marked, the GC may
183 // incorrectly sweep it. This also fixes a race where interning may attempt to return a strong
184 // reference to a string that is about to be swept.
185 Runtime::Current()->DisallowNewSystemWeaks();
186 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800187}
188
Mathieu Chartierdda54f52014-02-24 09:58:40 -0800189void MarkSweep::PreCleanCards() {
190 // Don't do this for non concurrent GCs since they don't have any dirty cards.
191 if (kPreCleanCards && IsConcurrent()) {
192 Thread* self = Thread::Current();
193 CHECK(!Locks::mutator_lock_->IsExclusiveHeld(self));
194 // Process dirty cards and add dirty cards to mod union tables, also ages cards.
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -0800195 heap_->ProcessCards(timings_, false);
Mathieu Chartiereb7bbad2014-02-25 15:52:46 -0800196 // The checkpoint root marking is required to avoid a race condition which occurs if the
197 // following happens during a reference write:
198 // 1. mutator dirties the card (write barrier)
199 // 2. GC ages the card (the above ProcessCards call)
200 // 3. GC scans the object (the RecursiveMarkDirtyObjects call below)
201 // 4. mutator writes the value (corresponding to the write barrier in 1.)
202 // This causes the GC to age the card but not necessarily mark the reference which the mutator
203 // wrote into the object stored in the card.
204 // Having the checkpoint fixes this issue since it ensures that the card mark and the
205 // reference write are visible to the GC before the card is scanned (this is due to locks being
206 // acquired / released in the checkpoint code).
207 // The other roots are also marked to help reduce the pause.
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -0700208 MarkRootsCheckpoint(self, false);
Mathieu Chartierdda54f52014-02-24 09:58:40 -0800209 MarkNonThreadRoots();
Mathieu Chartier893263b2014-03-04 11:07:42 -0800210 MarkConcurrentRoots(
211 static_cast<VisitRootFlags>(kVisitRootFlagClearRootLog | kVisitRootFlagNewRoots));
Mathieu Chartierdda54f52014-02-24 09:58:40 -0800212 // Process the newly aged cards.
213 RecursiveMarkDirtyObjects(false, accounting::CardTable::kCardDirty - 1);
214 // TODO: Empty allocation stack to reduce the number of objects we need to test / mark as live
215 // in the next GC.
216 }
217}
218
Mathieu Chartierc22c59e2014-02-24 15:16:06 -0800219void MarkSweep::RevokeAllThreadLocalAllocationStacks(Thread* self) {
220 if (kUseThreadLocalAllocationStack) {
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -0700221 timings_.NewSplit("RevokeAllThreadLocalAllocationStacks");
Mathieu Chartierc22c59e2014-02-24 15:16:06 -0800222 Locks::mutator_lock_->AssertExclusiveHeld(self);
223 heap_->RevokeAllThreadLocalAllocationStacks(self);
224 }
225}
226
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800227void MarkSweep::MarkingPhase() {
Ian Rogers5fe9af72013-11-14 00:17:20 -0800228 TimingLogger::ScopedSplit split("MarkingPhase", &timings_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800229 Thread* self = Thread::Current();
230
231 BindBitmaps();
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700232 FindDefaultSpaceBitmap();
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700233
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800234 // Process dirty cards and add dirty cards to mod union tables.
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -0800235 heap_->ProcessCards(timings_, false);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800236
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800237 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier893263b2014-03-04 11:07:42 -0800238 MarkRoots(self);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800239 MarkReachableObjects();
Mathieu Chartierdda54f52014-02-24 09:58:40 -0800240 // Pre-clean dirtied cards to reduce pauses.
241 PreCleanCards();
Mathieu Chartier601276a2014-03-20 15:12:30 -0700242 PreProcessReferences();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800243}
244
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700245void MarkSweep::UpdateAndMarkModUnion() {
246 for (const auto& space : heap_->GetContinuousSpaces()) {
Mathieu Chartier8d562102014-03-12 17:42:10 -0700247 if (immune_region_.ContainsSpace(space)) {
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700248 const char* name = space->IsZygoteSpace() ? "UpdateAndMarkZygoteModUnionTable" :
249 "UpdateAndMarkImageModUnionTable";
Ian Rogers5fe9af72013-11-14 00:17:20 -0800250 TimingLogger::ScopedSplit split(name, &timings_);
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700251 accounting::ModUnionTable* mod_union_table = heap_->FindModUnionTableFromSpace(space);
252 CHECK(mod_union_table != nullptr);
Mathieu Chartier407f7022014-02-18 14:37:05 -0800253 mod_union_table->UpdateAndMarkReferences(MarkHeapReferenceCallback, this);
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700254 }
255 }
256}
257
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800258void MarkSweep::MarkReachableObjects() {
Mathieu Chartier4aeec172014-03-27 16:09:46 -0700259 UpdateAndMarkModUnion();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800260 // Recursively mark all the non-image bits set in the mark bitmap.
261 RecursiveMark();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800262}
263
264void MarkSweep::ReclaimPhase() {
Ian Rogers5fe9af72013-11-14 00:17:20 -0800265 TimingLogger::ScopedSplit split("ReclaimPhase", &timings_);
Mathieu Chartier720ef762013-08-17 14:46:54 -0700266 Thread* self = Thread::Current();
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -0700267 SweepSystemWeaks(self);
Mathieu Chartierc11d9b82013-09-19 10:01:59 -0700268 if (IsConcurrent()) {
269 Runtime::Current()->AllowNewSystemWeaks();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800270 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800271 {
272 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
273
274 // Reclaim unmarked objects.
Ian Rogers1d54e732013-05-02 21:10:01 -0700275 Sweep(false);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800276
277 // Swap the live and mark bitmaps for each space which we modified space. This is an
278 // optimization that enables us to not clear live bits inside of the sweep. Only swaps unbound
279 // bitmaps.
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700280 timings_.StartSplit("SwapBitmaps");
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800281 SwapBitmaps();
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700282 timings_.EndSplit();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800283
284 // Unbind the live and mark bitmaps.
Mathieu Chartiera1602f22014-01-13 17:19:19 -0800285 TimingLogger::ScopedSplit split("UnBindBitmaps", &timings_);
286 GetHeap()->UnBindBitmaps();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800287 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800288}
289
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700290void MarkSweep::FindDefaultSpaceBitmap() {
Ian Rogers5fe9af72013-11-14 00:17:20 -0800291 TimingLogger::ScopedSplit split("FindDefaultMarkBitmap", &timings_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700292 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700293 accounting::SpaceBitmap* bitmap = space->GetMarkBitmap();
294 if (bitmap != nullptr &&
295 space->GetGcRetentionPolicy() == space::kGcRetentionPolicyAlwaysCollect) {
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700296 current_space_bitmap_ = bitmap;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700297 return;
298 }
299 }
300 GetHeap()->DumpSpaces();
301 LOG(FATAL) << "Could not find a default mark bitmap";
302}
303
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800304void MarkSweep::ExpandMarkStack() {
Mathieu Chartierba311b42013-08-27 13:02:30 -0700305 ResizeMarkStack(mark_stack_->Capacity() * 2);
306}
307
308void MarkSweep::ResizeMarkStack(size_t new_size) {
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800309 // Rare case, no need to have Thread::Current be a parameter.
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800310 if (UNLIKELY(mark_stack_->Size() < mark_stack_->Capacity())) {
311 // Someone else acquired the lock and expanded the mark stack before us.
312 return;
313 }
Mathieu Chartier02e25112013-08-14 16:14:24 -0700314 std::vector<Object*> temp(mark_stack_->Begin(), mark_stack_->End());
Mathieu Chartierba311b42013-08-27 13:02:30 -0700315 CHECK_LE(mark_stack_->Size(), new_size);
316 mark_stack_->Resize(new_size);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700317 for (const auto& obj : temp) {
318 mark_stack_->PushBack(obj);
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800319 }
320}
321
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700322inline void MarkSweep::MarkObjectNonNullParallel(Object* obj) {
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800323 DCHECK(obj != NULL);
324 if (MarkObjectParallel(obj)) {
Mathieu Chartierba311b42013-08-27 13:02:30 -0700325 MutexLock mu(Thread::Current(), mark_stack_lock_);
326 if (UNLIKELY(mark_stack_->Size() >= mark_stack_->Capacity())) {
Mathieu Chartier184e3222013-08-03 14:02:57 -0700327 ExpandMarkStack();
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800328 }
Mathieu Chartierba311b42013-08-27 13:02:30 -0700329 // The object must be pushed on to the mark stack.
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700330 mark_stack_->PushBack(obj);
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800331 }
332}
333
Mathieu Chartier3bb57c72014-02-18 11:38:45 -0800334mirror::Object* MarkSweep::MarkObjectCallback(mirror::Object* obj, void* arg) {
Mathieu Chartier39e32612013-11-12 16:28:05 -0800335 MarkSweep* mark_sweep = reinterpret_cast<MarkSweep*>(arg);
336 mark_sweep->MarkObject(obj);
Mathieu Chartier39e32612013-11-12 16:28:05 -0800337 return obj;
338}
339
Mathieu Chartier407f7022014-02-18 14:37:05 -0800340void MarkSweep::MarkHeapReferenceCallback(mirror::HeapReference<mirror::Object>* ref, void* arg) {
341 reinterpret_cast<MarkSweep*>(arg)->MarkObject(ref->AsMirrorPtr());
342}
343
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700344inline void MarkSweep::MarkObjectNonNull(Object* obj) {
345 DCHECK(obj != nullptr);
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -0700346 if (kUseBakerOrBrooksReadBarrier) {
347 // Verify all the objects have the correct pointer installed.
348 obj->AssertReadBarrierPointer();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800349 }
Mathieu Chartier8d562102014-03-12 17:42:10 -0700350 if (immune_region_.ContainsObject(obj)) {
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700351 if (kCountMarkedObjects) {
352 ++mark_immune_count_;
353 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700354 DCHECK(IsMarked(obj));
Carl Shapiro69759ea2011-07-21 18:13:35 -0700355 return;
356 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700357 // Try to take advantage of locality of references within a space, failing this find the space
358 // the hard way.
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700359 accounting::SpaceBitmap* object_bitmap = current_space_bitmap_;
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700360 if (UNLIKELY(!object_bitmap->HasAddress(obj))) {
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700361 object_bitmap = mark_bitmap_->GetContinuousSpaceBitmap(obj);
362 if (kCountMarkedObjects) {
363 ++mark_slowpath_count_;
364 }
365 if (UNLIKELY(object_bitmap == nullptr)) {
Mathieu Chartier9642c962013-08-05 17:40:36 -0700366 MarkLargeObject(obj, true);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700367 return;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700368 }
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700369 } else if (kCountMarkedObjects) {
370 ++mark_fastpath_count_;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700371 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700372 // This object was not previously marked.
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700373 if (!object_bitmap->Set(obj)) {
374 PushOnMarkStack(obj);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700375 }
376}
377
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700378inline void MarkSweep::PushOnMarkStack(Object* obj) {
379 if (UNLIKELY(mark_stack_->Size() >= mark_stack_->Capacity())) {
380 // Lock is not needed but is here anyways to please annotalysis.
381 MutexLock mu(Thread::Current(), mark_stack_lock_);
382 ExpandMarkStack();
383 }
384 // The object must be pushed on to the mark stack.
385 mark_stack_->PushBack(obj);
386}
387
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700388// Rare case, probably not worth inlining since it will increase instruction cache miss rate.
Mathieu Chartier9642c962013-08-05 17:40:36 -0700389bool MarkSweep::MarkLargeObject(const Object* obj, bool set) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700390 // TODO: support >1 discontinuous space.
391 space::LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
Mathieu Chartierdb7f37d2014-01-10 11:09:06 -0800392 accounting::ObjectSet* large_objects = large_object_space->GetMarkObjects();
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700393 if (kProfileLargeObjects) {
394 ++large_object_test_;
395 }
396 if (UNLIKELY(!large_objects->Test(obj))) {
Mathieu Chartier4fcb8d32013-07-15 12:43:36 -0700397 if (!large_object_space->Contains(obj)) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700398 LOG(ERROR) << "Tried to mark " << obj << " not contained by any spaces";
399 LOG(ERROR) << "Attempting see if it's a bad root";
400 VerifyRoots();
401 LOG(FATAL) << "Can't mark bad root";
402 }
403 if (kProfileLargeObjects) {
404 ++large_object_mark_;
405 }
Mathieu Chartier9642c962013-08-05 17:40:36 -0700406 if (set) {
407 large_objects->Set(obj);
408 } else {
409 large_objects->Clear(obj);
410 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700411 return true;
412 }
413 return false;
414}
415
416inline bool MarkSweep::MarkObjectParallel(const Object* obj) {
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700417 DCHECK(obj != nullptr);
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -0700418 if (kUseBakerOrBrooksReadBarrier) {
419 // Verify all the objects have the correct pointer installed.
420 obj->AssertReadBarrierPointer();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800421 }
Mathieu Chartier8d562102014-03-12 17:42:10 -0700422 if (immune_region_.ContainsObject(obj)) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700423 DCHECK(IsMarked(obj));
424 return false;
425 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700426 // Try to take advantage of locality of references within a space, failing this find the space
427 // the hard way.
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700428 accounting::SpaceBitmap* object_bitmap = current_space_bitmap_;
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700429 if (UNLIKELY(!object_bitmap->HasAddress(obj))) {
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700430 accounting::SpaceBitmap* new_bitmap = mark_bitmap_->GetContinuousSpaceBitmap(obj);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700431 if (new_bitmap != NULL) {
432 object_bitmap = new_bitmap;
433 } else {
434 // TODO: Remove the Thread::Current here?
435 // TODO: Convert this to some kind of atomic marking?
436 MutexLock mu(Thread::Current(), large_object_lock_);
Mathieu Chartier9642c962013-08-05 17:40:36 -0700437 return MarkLargeObject(obj, true);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700438 }
439 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700440 // Return true if the object was not previously marked.
441 return !object_bitmap->AtomicTestAndSet(obj);
442}
443
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700444// Used to mark objects when processing the mark stack. If an object is null, it is not marked.
445inline void MarkSweep::MarkObject(Object* obj) {
446 if (obj != nullptr) {
Mathieu Chartier9642c962013-08-05 17:40:36 -0700447 MarkObjectNonNull(obj);
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700448 } else if (kCountMarkedObjects) {
449 ++mark_null_count_;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700450 }
451}
452
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700453void MarkSweep::MarkRootParallelCallback(Object** root, void* arg, uint32_t /*thread_id*/,
Mathieu Chartier815873e2014-02-13 18:02:13 -0800454 RootType /*root_type*/) {
Mathieu Chartier815873e2014-02-13 18:02:13 -0800455 reinterpret_cast<MarkSweep*>(arg)->MarkObjectNonNullParallel(*root);
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800456}
457
Mathieu Chartier893263b2014-03-04 11:07:42 -0800458void MarkSweep::VerifyRootMarked(Object** root, void* arg, uint32_t /*thread_id*/,
459 RootType /*root_type*/) {
460 CHECK(reinterpret_cast<MarkSweep*>(arg)->IsMarked(*root));
461}
462
Mathieu Chartier815873e2014-02-13 18:02:13 -0800463void MarkSweep::MarkRootCallback(Object** root, void* arg, uint32_t /*thread_id*/,
464 RootType /*root_type*/) {
Mathieu Chartier815873e2014-02-13 18:02:13 -0800465 reinterpret_cast<MarkSweep*>(arg)->MarkObjectNonNull(*root);
466}
467
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700468void MarkSweep::VerifyRootCallback(const Object* root, void* arg, size_t vreg,
Ian Rogers40e3bac2012-11-20 00:09:14 -0800469 const StackVisitor* visitor) {
470 reinterpret_cast<MarkSweep*>(arg)->VerifyRoot(root, vreg, visitor);
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700471}
472
Ian Rogers40e3bac2012-11-20 00:09:14 -0800473void MarkSweep::VerifyRoot(const Object* root, size_t vreg, const StackVisitor* visitor) {
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700474 // See if the root is on any space bitmap.
Ian Rogers1d54e732013-05-02 21:10:01 -0700475 if (GetHeap()->GetLiveBitmap()->GetContinuousSpaceBitmap(root) == NULL) {
476 space::LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
Mathieu Chartier4202b742012-10-17 17:51:25 -0700477 if (!large_object_space->Contains(root)) {
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700478 LOG(ERROR) << "Found invalid root: " << root;
Ian Rogers40e3bac2012-11-20 00:09:14 -0800479 if (visitor != NULL) {
480 LOG(ERROR) << visitor->DescribeLocation() << " in VReg: " << vreg;
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700481 }
482 }
483 }
484}
485
486void MarkSweep::VerifyRoots() {
487 Runtime::Current()->GetThreadList()->VerifyRoots(VerifyRootCallback, this);
488}
489
Mathieu Chartier893263b2014-03-04 11:07:42 -0800490void MarkSweep::MarkRoots(Thread* self) {
491 if (Locks::mutator_lock_->IsExclusiveHeld(self)) {
492 // If we exclusively hold the mutator lock, all threads must be suspended.
493 timings_.StartSplit("MarkRoots");
494 Runtime::Current()->VisitRoots(MarkRootCallback, this);
495 timings_.EndSplit();
496 RevokeAllThreadLocalAllocationStacks(self);
497 } else {
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -0700498 MarkRootsCheckpoint(self, kRevokeRosAllocThreadLocalBuffersAtCheckpoint);
Mathieu Chartier893263b2014-03-04 11:07:42 -0800499 // At this point the live stack should no longer have any mutators which push into it.
500 MarkNonThreadRoots();
501 MarkConcurrentRoots(
502 static_cast<VisitRootFlags>(kVisitRootFlagAllRoots | kVisitRootFlagStartLoggingNewRoots));
503 }
Mathieu Chartier9ebae1f2012-10-15 17:38:16 -0700504}
505
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700506void MarkSweep::MarkNonThreadRoots() {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700507 timings_.StartSplit("MarkNonThreadRoots");
Mathieu Chartier423d2a32013-09-12 17:33:56 -0700508 Runtime::Current()->VisitNonThreadRoots(MarkRootCallback, this);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700509 timings_.EndSplit();
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700510}
511
Mathieu Chartier893263b2014-03-04 11:07:42 -0800512void MarkSweep::MarkConcurrentRoots(VisitRootFlags flags) {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700513 timings_.StartSplit("MarkConcurrentRoots");
Ian Rogers1d54e732013-05-02 21:10:01 -0700514 // Visit all runtime roots and clear dirty flags.
Mathieu Chartier893263b2014-03-04 11:07:42 -0800515 Runtime::Current()->VisitConcurrentRoots(MarkRootCallback, this, flags);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700516 timings_.EndSplit();
Carl Shapiro69759ea2011-07-21 18:13:35 -0700517}
518
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700519class ScanObjectVisitor {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700520 public:
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700521 explicit ScanObjectVisitor(MarkSweep* const mark_sweep) ALWAYS_INLINE
522 : mark_sweep_(mark_sweep) {}
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700523
Mathieu Chartier407f7022014-02-18 14:37:05 -0800524 void operator()(Object* obj) const ALWAYS_INLINE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
525 EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700526 if (kCheckLocks) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800527 Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
528 Locks::heap_bitmap_lock_->AssertExclusiveHeld(Thread::Current());
529 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700530 mark_sweep_->ScanObject(obj);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700531 }
532
533 private:
534 MarkSweep* const mark_sweep_;
535};
536
Mathieu Chartier407f7022014-02-18 14:37:05 -0800537class DelayReferenceReferentVisitor {
538 public:
539 explicit DelayReferenceReferentVisitor(MarkSweep* collector) : collector_(collector) {
540 }
541
542 void operator()(mirror::Class* klass, mirror::Reference* ref) const
543 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
544 EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
545 collector_->DelayReferenceReferent(klass, ref);
546 }
547
548 private:
549 MarkSweep* const collector_;
550};
551
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700552template <bool kUseFinger = false>
553class MarkStackTask : public Task {
554 public:
555 MarkStackTask(ThreadPool* thread_pool, MarkSweep* mark_sweep, size_t mark_stack_size,
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700556 Object** mark_stack)
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700557 : mark_sweep_(mark_sweep),
558 thread_pool_(thread_pool),
559 mark_stack_pos_(mark_stack_size) {
560 // We may have to copy part of an existing mark stack when another mark stack overflows.
561 if (mark_stack_size != 0) {
562 DCHECK(mark_stack != NULL);
563 // TODO: Check performance?
564 std::copy(mark_stack, mark_stack + mark_stack_size, mark_stack_);
Ian Rogers1d54e732013-05-02 21:10:01 -0700565 }
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700566 if (kCountTasks) {
567 ++mark_sweep_->work_chunks_created_;
568 }
569 }
570
571 static const size_t kMaxSize = 1 * KB;
572
573 protected:
Mathieu Chartier407f7022014-02-18 14:37:05 -0800574 class MarkObjectParallelVisitor {
575 public:
576 explicit MarkObjectParallelVisitor(MarkStackTask<kUseFinger>* chunk_task,
577 MarkSweep* mark_sweep) ALWAYS_INLINE
578 : chunk_task_(chunk_task), mark_sweep_(mark_sweep) {}
579
580 void operator()(Object* obj, MemberOffset offset, bool /* static */) const ALWAYS_INLINE
581 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
582 mirror::Object* ref = obj->GetFieldObject<mirror::Object>(offset, false);
583 if (ref != nullptr && mark_sweep_->MarkObjectParallel(ref)) {
584 if (kUseFinger) {
585 android_memory_barrier();
586 if (reinterpret_cast<uintptr_t>(ref) >=
587 static_cast<uintptr_t>(mark_sweep_->atomic_finger_)) {
588 return;
589 }
590 }
591 chunk_task_->MarkStackPush(ref);
592 }
593 }
594
595 private:
596 MarkStackTask<kUseFinger>* const chunk_task_;
597 MarkSweep* const mark_sweep_;
598 };
599
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700600 class ScanObjectParallelVisitor {
601 public:
602 explicit ScanObjectParallelVisitor(MarkStackTask<kUseFinger>* chunk_task) ALWAYS_INLINE
603 : chunk_task_(chunk_task) {}
604
Mathieu Chartier407f7022014-02-18 14:37:05 -0800605 // No thread safety analysis since multiple threads will use this visitor.
606 void operator()(Object* obj) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
607 EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
608 MarkSweep* const mark_sweep = chunk_task_->mark_sweep_;
609 MarkObjectParallelVisitor mark_visitor(chunk_task_, mark_sweep);
610 DelayReferenceReferentVisitor ref_visitor(mark_sweep);
611 mark_sweep->ScanObjectVisit(obj, mark_visitor, ref_visitor);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700612 }
613
614 private:
615 MarkStackTask<kUseFinger>* const chunk_task_;
616 };
617
618 virtual ~MarkStackTask() {
619 // Make sure that we have cleared our mark stack.
620 DCHECK_EQ(mark_stack_pos_, 0U);
621 if (kCountTasks) {
622 ++mark_sweep_->work_chunks_deleted_;
623 }
624 }
625
626 MarkSweep* const mark_sweep_;
627 ThreadPool* const thread_pool_;
628 // Thread local mark stack for this task.
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700629 Object* mark_stack_[kMaxSize];
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700630 // Mark stack position.
631 size_t mark_stack_pos_;
632
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700633 void MarkStackPush(Object* obj) ALWAYS_INLINE {
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700634 if (UNLIKELY(mark_stack_pos_ == kMaxSize)) {
635 // Mark stack overflow, give 1/2 the stack to the thread pool as a new work task.
636 mark_stack_pos_ /= 2;
637 auto* task = new MarkStackTask(thread_pool_, mark_sweep_, kMaxSize - mark_stack_pos_,
638 mark_stack_ + mark_stack_pos_);
639 thread_pool_->AddTask(Thread::Current(), task);
640 }
641 DCHECK(obj != nullptr);
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700642 DCHECK_LT(mark_stack_pos_, kMaxSize);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700643 mark_stack_[mark_stack_pos_++] = obj;
644 }
645
646 virtual void Finalize() {
647 delete this;
648 }
649
650 // Scans all of the objects
Mathieu Chartier407f7022014-02-18 14:37:05 -0800651 virtual void Run(Thread* self) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
652 EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700653 ScanObjectParallelVisitor visitor(this);
654 // TODO: Tune this.
655 static const size_t kFifoSize = 4;
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700656 BoundedFifoPowerOfTwo<Object*, kFifoSize> prefetch_fifo;
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700657 for (;;) {
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700658 Object* obj = nullptr;
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700659 if (kUseMarkStackPrefetch) {
660 while (mark_stack_pos_ != 0 && prefetch_fifo.size() < kFifoSize) {
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700661 Object* obj = mark_stack_[--mark_stack_pos_];
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700662 DCHECK(obj != nullptr);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700663 __builtin_prefetch(obj);
664 prefetch_fifo.push_back(obj);
665 }
666 if (UNLIKELY(prefetch_fifo.empty())) {
667 break;
668 }
669 obj = prefetch_fifo.front();
670 prefetch_fifo.pop_front();
671 } else {
672 if (UNLIKELY(mark_stack_pos_ == 0)) {
673 break;
674 }
675 obj = mark_stack_[--mark_stack_pos_];
676 }
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700677 DCHECK(obj != nullptr);
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700678 visitor(obj);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700679 }
680 }
681};
682
683class CardScanTask : public MarkStackTask<false> {
684 public:
685 CardScanTask(ThreadPool* thread_pool, MarkSweep* mark_sweep, accounting::SpaceBitmap* bitmap,
686 byte* begin, byte* end, byte minimum_age, size_t mark_stack_size,
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700687 Object** mark_stack_obj)
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700688 : MarkStackTask<false>(thread_pool, mark_sweep, mark_stack_size, mark_stack_obj),
689 bitmap_(bitmap),
690 begin_(begin),
691 end_(end),
692 minimum_age_(minimum_age) {
693 }
694
695 protected:
696 accounting::SpaceBitmap* const bitmap_;
697 byte* const begin_;
698 byte* const end_;
699 const byte minimum_age_;
700
701 virtual void Finalize() {
702 delete this;
703 }
704
705 virtual void Run(Thread* self) NO_THREAD_SAFETY_ANALYSIS {
706 ScanObjectParallelVisitor visitor(this);
707 accounting::CardTable* card_table = mark_sweep_->GetHeap()->GetCardTable();
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700708 size_t cards_scanned = card_table->Scan(bitmap_, begin_, end_, visitor, minimum_age_);
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700709 VLOG(heap) << "Parallel scanning cards " << reinterpret_cast<void*>(begin_) << " - "
710 << reinterpret_cast<void*>(end_) << " = " << cards_scanned;
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700711 // Finish by emptying our local mark stack.
712 MarkStackTask::Run(self);
713 }
714};
715
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700716size_t MarkSweep::GetThreadCount(bool paused) const {
717 if (heap_->GetThreadPool() == nullptr || !heap_->CareAboutPauseTimes()) {
718 return 0;
719 }
720 if (paused) {
721 return heap_->GetParallelGCThreadCount() + 1;
722 } else {
723 return heap_->GetConcGCThreadCount() + 1;
724 }
725}
726
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700727void MarkSweep::ScanGrayObjects(bool paused, byte minimum_age) {
728 accounting::CardTable* card_table = GetHeap()->GetCardTable();
729 ThreadPool* thread_pool = GetHeap()->GetThreadPool();
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700730 size_t thread_count = GetThreadCount(paused);
731 // The parallel version with only one thread is faster for card scanning, TODO: fix.
732 if (kParallelCardScan && thread_count > 0) {
Mathieu Chartier720ef762013-08-17 14:46:54 -0700733 Thread* self = Thread::Current();
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700734 // Can't have a different split for each space since multiple spaces can have their cards being
735 // scanned at the same time.
736 timings_.StartSplit(paused ? "(Paused)ScanGrayObjects" : "ScanGrayObjects");
737 // 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 -0700738 Object** mark_stack_begin = mark_stack_->Begin();
739 Object** mark_stack_end = mark_stack_->End();
Mathieu Chartier720ef762013-08-17 14:46:54 -0700740 const size_t mark_stack_size = mark_stack_end - mark_stack_begin;
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700741 // Estimated number of work tasks we will create.
742 const size_t mark_stack_tasks = GetHeap()->GetContinuousSpaces().size() * thread_count;
743 DCHECK_NE(mark_stack_tasks, 0U);
744 const size_t mark_stack_delta = std::min(CardScanTask::kMaxSize / 2,
745 mark_stack_size / mark_stack_tasks + 1);
746 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700747 if (space->GetMarkBitmap() == nullptr) {
748 continue;
749 }
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700750 byte* card_begin = space->Begin();
751 byte* card_end = space->End();
Hiroshi Yamauchi0941b042013-11-05 11:34:03 -0800752 // Align up the end address. For example, the image space's end
753 // may not be card-size-aligned.
754 card_end = AlignUp(card_end, accounting::CardTable::kCardSize);
755 DCHECK(IsAligned<accounting::CardTable::kCardSize>(card_begin));
756 DCHECK(IsAligned<accounting::CardTable::kCardSize>(card_end));
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700757 // Calculate how many bytes of heap we will scan,
758 const size_t address_range = card_end - card_begin;
759 // Calculate how much address range each task gets.
760 const size_t card_delta = RoundUp(address_range / thread_count + 1,
761 accounting::CardTable::kCardSize);
762 // Create the worker tasks for this space.
763 while (card_begin != card_end) {
764 // Add a range of cards.
765 size_t addr_remaining = card_end - card_begin;
766 size_t card_increment = std::min(card_delta, addr_remaining);
767 // Take from the back of the mark stack.
768 size_t mark_stack_remaining = mark_stack_end - mark_stack_begin;
769 size_t mark_stack_increment = std::min(mark_stack_delta, mark_stack_remaining);
770 mark_stack_end -= mark_stack_increment;
771 mark_stack_->PopBackCount(static_cast<int32_t>(mark_stack_increment));
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700772 DCHECK_EQ(mark_stack_end, mark_stack_->End());
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700773 // Add the new task to the thread pool.
774 auto* task = new CardScanTask(thread_pool, this, space->GetMarkBitmap(), card_begin,
775 card_begin + card_increment, minimum_age,
776 mark_stack_increment, mark_stack_end);
777 thread_pool->AddTask(self, task);
778 card_begin += card_increment;
779 }
780 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700781
Hiroshi Yamauchi0941b042013-11-05 11:34:03 -0800782 // Note: the card scan below may dirty new cards (and scan them)
783 // as a side effect when a Reference object is encountered and
784 // queued during the marking. See b/11465268.
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700785 thread_pool->SetMaxActiveWorkers(thread_count - 1);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700786 thread_pool->StartWorkers(self);
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700787 thread_pool->Wait(self, true, true);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700788 thread_pool->StopWorkers(self);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700789 timings_.EndSplit();
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700790 } else {
791 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700792 if (space->GetMarkBitmap() != nullptr) {
793 // Image spaces are handled properly since live == marked for them.
794 switch (space->GetGcRetentionPolicy()) {
795 case space::kGcRetentionPolicyNeverCollect:
796 timings_.StartSplit(paused ? "(Paused)ScanGrayImageSpaceObjects" :
797 "ScanGrayImageSpaceObjects");
798 break;
799 case space::kGcRetentionPolicyFullCollect:
800 timings_.StartSplit(paused ? "(Paused)ScanGrayZygoteSpaceObjects" :
801 "ScanGrayZygoteSpaceObjects");
802 break;
803 case space::kGcRetentionPolicyAlwaysCollect:
804 timings_.StartSplit(paused ? "(Paused)ScanGrayAllocSpaceObjects" :
805 "ScanGrayAllocSpaceObjects");
806 break;
807 }
808 ScanObjectVisitor visitor(this);
809 card_table->Scan(space->GetMarkBitmap(), space->Begin(), space->End(), visitor, minimum_age);
810 timings_.EndSplit();
811 }
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700812 }
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700813 }
814}
815
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700816class RecursiveMarkTask : public MarkStackTask<false> {
817 public:
818 RecursiveMarkTask(ThreadPool* thread_pool, MarkSweep* mark_sweep,
819 accounting::SpaceBitmap* bitmap, uintptr_t begin, uintptr_t end)
820 : MarkStackTask<false>(thread_pool, mark_sweep, 0, NULL),
821 bitmap_(bitmap),
822 begin_(begin),
823 end_(end) {
824 }
825
826 protected:
827 accounting::SpaceBitmap* const bitmap_;
828 const uintptr_t begin_;
829 const uintptr_t end_;
830
831 virtual void Finalize() {
832 delete this;
833 }
834
835 // Scans all of the objects
836 virtual void Run(Thread* self) NO_THREAD_SAFETY_ANALYSIS {
837 ScanObjectParallelVisitor visitor(this);
838 bitmap_->VisitMarkedRange(begin_, end_, visitor);
839 // Finish by emptying our local mark stack.
840 MarkStackTask::Run(self);
841 }
842};
843
Carl Shapiro58551df2011-07-24 03:09:51 -0700844// Populates the mark stack based on the set of marked objects and
845// recursively marks until the mark stack is emptied.
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800846void MarkSweep::RecursiveMark() {
Ian Rogers5fe9af72013-11-14 00:17:20 -0800847 TimingLogger::ScopedSplit split("RecursiveMark", &timings_);
Mathieu Chartiera1602f22014-01-13 17:19:19 -0800848 // RecursiveMark will build the lists of known instances of the Reference classes. See
849 // DelayReferenceReferent for details.
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700850 if (kUseRecursiveMark) {
851 const bool partial = GetGcType() == kGcTypePartial;
852 ScanObjectVisitor scan_visitor(this);
853 auto* self = Thread::Current();
854 ThreadPool* thread_pool = heap_->GetThreadPool();
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700855 size_t thread_count = GetThreadCount(false);
856 const bool parallel = kParallelRecursiveMark && thread_count > 1;
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700857 mark_stack_->Reset();
Mathieu Chartier02e25112013-08-14 16:14:24 -0700858 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700859 if ((space->GetGcRetentionPolicy() == space::kGcRetentionPolicyAlwaysCollect) ||
860 (!partial && space->GetGcRetentionPolicy() == space::kGcRetentionPolicyFullCollect)) {
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700861 current_space_bitmap_ = space->GetMarkBitmap();
862 if (current_space_bitmap_ == nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700863 continue;
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800864 }
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700865 if (parallel) {
866 // We will use the mark stack the future.
867 // CHECK(mark_stack_->IsEmpty());
868 // This function does not handle heap end increasing, so we must use the space end.
869 uintptr_t begin = reinterpret_cast<uintptr_t>(space->Begin());
870 uintptr_t end = reinterpret_cast<uintptr_t>(space->End());
871 atomic_finger_ = static_cast<int32_t>(0xFFFFFFFF);
872
873 // Create a few worker tasks.
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700874 const size_t n = thread_count * 2;
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700875 while (begin != end) {
876 uintptr_t start = begin;
877 uintptr_t delta = (end - begin) / n;
878 delta = RoundUp(delta, KB);
879 if (delta < 16 * KB) delta = end - begin;
880 begin += delta;
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700881 auto* task = new RecursiveMarkTask(thread_pool, this, current_space_bitmap_, start,
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700882 begin);
883 thread_pool->AddTask(self, task);
884 }
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700885 thread_pool->SetMaxActiveWorkers(thread_count - 1);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700886 thread_pool->StartWorkers(self);
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700887 thread_pool->Wait(self, true, true);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700888 thread_pool->StopWorkers(self);
889 } else {
890 // This function does not handle heap end increasing, so we must use the space end.
891 uintptr_t begin = reinterpret_cast<uintptr_t>(space->Begin());
892 uintptr_t end = reinterpret_cast<uintptr_t>(space->End());
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700893 current_space_bitmap_->VisitMarkedRange(begin, end, scan_visitor);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700894 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700895 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700896 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700897 }
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700898 ProcessMarkStack(false);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700899}
900
Mathieu Chartier83c8ee02014-01-28 14:50:23 -0800901mirror::Object* MarkSweep::IsMarkedCallback(mirror::Object* object, void* arg) {
Mathieu Chartier5712d5d2013-09-18 17:59:36 -0700902 if (reinterpret_cast<MarkSweep*>(arg)->IsMarked(object)) {
Mathieu Chartier6aa3df92013-09-17 15:17:28 -0700903 return object;
904 }
905 return nullptr;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700906}
907
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700908void MarkSweep::RecursiveMarkDirtyObjects(bool paused, byte minimum_age) {
909 ScanGrayObjects(paused, minimum_age);
910 ProcessMarkStack(paused);
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700911}
912
Carl Shapiro58551df2011-07-24 03:09:51 -0700913void MarkSweep::ReMarkRoots() {
Mathieu Chartier893263b2014-03-04 11:07:42 -0800914 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartier3bb57c72014-02-18 11:38:45 -0800915 timings_.StartSplit("(Paused)ReMarkRoots");
Mathieu Chartier893263b2014-03-04 11:07:42 -0800916 Runtime::Current()->VisitRoots(
917 MarkRootCallback, this, static_cast<VisitRootFlags>(kVisitRootFlagNewRoots |
918 kVisitRootFlagStopLoggingNewRoots |
919 kVisitRootFlagClearRootLog));
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700920 timings_.EndSplit();
Mathieu Chartier893263b2014-03-04 11:07:42 -0800921 if (kVerifyRoots) {
922 timings_.StartSplit("(Paused)VerifyRoots");
923 Runtime::Current()->VisitRoots(VerifyRootMarked, this);
924 timings_.EndSplit();
925 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700926}
927
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -0700928void MarkSweep::SweepSystemWeaks(Thread* self) {
929 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700930 timings_.StartSplit("SweepSystemWeaks");
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -0700931 Runtime::Current()->SweepSystemWeaks(IsMarkedCallback, this);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700932 timings_.EndSplit();
Carl Shapiro58551df2011-07-24 03:09:51 -0700933}
934
Mathieu Chartier6aa3df92013-09-17 15:17:28 -0700935mirror::Object* MarkSweep::VerifySystemWeakIsLiveCallback(Object* obj, void* arg) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700936 reinterpret_cast<MarkSweep*>(arg)->VerifyIsLive(obj);
937 // We don't actually want to sweep the object, so lets return "marked"
Mathieu Chartier6aa3df92013-09-17 15:17:28 -0700938 return obj;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700939}
940
941void MarkSweep::VerifyIsLive(const Object* obj) {
Mathieu Chartier4aeec172014-03-27 16:09:46 -0700942 if (!heap_->GetLiveBitmap()->Test(obj)) {
943 space::LargeObjectSpace* large_object_space = heap_->GetLargeObjectsSpace();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700944 if (!large_object_space->GetLiveObjects()->Test(obj)) {
Mathieu Chartier4aeec172014-03-27 16:09:46 -0700945 if (std::find(heap_->allocation_stack_->Begin(), heap_->allocation_stack_->End(), obj) ==
946 heap_->allocation_stack_->End()) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700947 // Object not found!
Mathieu Chartier4aeec172014-03-27 16:09:46 -0700948 heap_->DumpSpaces();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700949 LOG(FATAL) << "Found dead object " << obj;
950 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700951 }
952 }
953}
954
955void MarkSweep::VerifySystemWeaks() {
Mathieu Chartier6aa3df92013-09-17 15:17:28 -0700956 // Verify system weaks, uses a special object visitor which returns the input object.
957 Runtime::Current()->SweepSystemWeaks(VerifySystemWeakIsLiveCallback, this);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700958}
959
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700960class CheckpointMarkThreadRoots : public Closure {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700961 public:
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -0700962 explicit CheckpointMarkThreadRoots(MarkSweep* mark_sweep,
963 bool revoke_ros_alloc_thread_local_buffers_at_checkpoint)
964 : mark_sweep_(mark_sweep),
965 revoke_ros_alloc_thread_local_buffers_at_checkpoint_(
966 revoke_ros_alloc_thread_local_buffers_at_checkpoint) {
967 }
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700968
Mathieu Chartier4aeec172014-03-27 16:09:46 -0700969 virtual void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier3f966702013-09-04 16:50:05 -0700970 ATRACE_BEGIN("Marking thread roots");
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700971 // Note: self is not necessarily equal to thread since thread may be suspended.
972 Thread* self = Thread::Current();
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800973 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
974 << thread->GetState() << " thread " << thread << " self " << self;
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800975 thread->VisitRoots(MarkSweep::MarkRootParallelCallback, mark_sweep_);
Mathieu Chartier3f966702013-09-04 16:50:05 -0700976 ATRACE_END();
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -0700977 if (revoke_ros_alloc_thread_local_buffers_at_checkpoint_) {
978 ATRACE_BEGIN("RevokeRosAllocThreadLocalBuffers");
Hiroshi Yamauchic93c5302014-03-20 16:15:37 -0700979 mark_sweep_->GetHeap()->RevokeRosAllocThreadLocalBuffers(thread);
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -0700980 ATRACE_END();
Hiroshi Yamauchic93c5302014-03-20 16:15:37 -0700981 }
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700982 mark_sweep_->GetBarrier().Pass(self);
983 }
984
985 private:
Mathieu Chartier4aeec172014-03-27 16:09:46 -0700986 MarkSweep* const mark_sweep_;
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -0700987 const bool revoke_ros_alloc_thread_local_buffers_at_checkpoint_;
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700988};
989
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -0700990void MarkSweep::MarkRootsCheckpoint(Thread* self,
991 bool revoke_ros_alloc_thread_local_buffers_at_checkpoint) {
992 CheckpointMarkThreadRoots check_point(this, revoke_ros_alloc_thread_local_buffers_at_checkpoint);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700993 timings_.StartSplit("MarkRootsCheckpoint");
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700994 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Ian Rogers1d54e732013-05-02 21:10:01 -0700995 // Request the check point is run on all threads returning a count of the threads that must
996 // run through the barrier including self.
997 size_t barrier_count = thread_list->RunCheckpoint(&check_point);
998 // Release locks then wait for all mutator threads to pass the barrier.
999 // TODO: optimize to not release locks when there are no threads to wait for.
1000 Locks::heap_bitmap_lock_->ExclusiveUnlock(self);
1001 Locks::mutator_lock_->SharedUnlock(self);
Mathieu Chartier4aeec172014-03-27 16:09:46 -07001002 {
1003 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
1004 gc_barrier_->Increment(self, barrier_count);
1005 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001006 Locks::mutator_lock_->SharedLock(self);
1007 Locks::heap_bitmap_lock_->ExclusiveLock(self);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001008 timings_.EndSplit();
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001009}
1010
Ian Rogers1d54e732013-05-02 21:10:01 -07001011void MarkSweep::SweepArray(accounting::ObjectStack* allocations, bool swap_bitmaps) {
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001012 timings_.StartSplit("SweepArray");
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001013 Thread* self = Thread::Current();
1014 mirror::Object* chunk_free_buffer[kSweepArrayChunkFreeSize];
1015 size_t chunk_free_pos = 0;
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001016 size_t freed_bytes = 0;
1017 size_t freed_large_object_bytes = 0;
Hiroshi Yamauchib22a4512013-08-13 15:03:22 -07001018 size_t freed_objects = 0;
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001019 size_t freed_large_objects = 0;
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001020 // How many objects are left in the array, modified after each space is swept.
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -07001021 Object** objects = allocations->Begin();
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001022 size_t count = allocations->Size();
1023 // Change the order to ensure that the non-moving space last swept as an optimization.
1024 std::vector<space::ContinuousSpace*> sweep_spaces;
1025 space::ContinuousSpace* non_moving_space = nullptr;
1026 for (space::ContinuousSpace* space : heap_->GetContinuousSpaces()) {
Mathieu Chartier8d562102014-03-12 17:42:10 -07001027 if (space->IsAllocSpace() && !immune_region_.ContainsSpace(space) &&
1028 space->GetLiveBitmap() != nullptr) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001029 if (space == heap_->GetNonMovingSpace()) {
1030 non_moving_space = space;
1031 } else {
1032 sweep_spaces.push_back(space);
1033 }
1034 }
1035 }
1036 // Unlikely to sweep a significant amount of non_movable objects, so we do these after the after
1037 // the other alloc spaces as an optimization.
1038 if (non_moving_space != nullptr) {
1039 sweep_spaces.push_back(non_moving_space);
1040 }
1041 // Start by sweeping the continuous spaces.
1042 for (space::ContinuousSpace* space : sweep_spaces) {
1043 space::AllocSpace* alloc_space = space->AsAllocSpace();
1044 accounting::SpaceBitmap* live_bitmap = space->GetLiveBitmap();
1045 accounting::SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
1046 if (swap_bitmaps) {
1047 std::swap(live_bitmap, mark_bitmap);
1048 }
1049 Object** out = objects;
1050 for (size_t i = 0; i < count; ++i) {
1051 Object* obj = objects[i];
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08001052 if (kUseThreadLocalAllocationStack && obj == nullptr) {
1053 continue;
1054 }
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001055 if (space->HasAddress(obj)) {
1056 // This object is in the space, remove it from the array and add it to the sweep buffer
1057 // if needed.
1058 if (!mark_bitmap->Test(obj)) {
1059 if (chunk_free_pos >= kSweepArrayChunkFreeSize) {
1060 timings_.StartSplit("FreeList");
1061 freed_objects += chunk_free_pos;
1062 freed_bytes += alloc_space->FreeList(self, chunk_free_pos, chunk_free_buffer);
1063 timings_.EndSplit();
1064 chunk_free_pos = 0;
1065 }
1066 chunk_free_buffer[chunk_free_pos++] = obj;
1067 }
1068 } else {
1069 *(out++) = obj;
1070 }
1071 }
1072 if (chunk_free_pos > 0) {
1073 timings_.StartSplit("FreeList");
1074 freed_objects += chunk_free_pos;
1075 freed_bytes += alloc_space->FreeList(self, chunk_free_pos, chunk_free_buffer);
1076 timings_.EndSplit();
1077 chunk_free_pos = 0;
1078 }
1079 // All of the references which space contained are no longer in the allocation stack, update
1080 // the count.
1081 count = out - objects;
1082 }
1083 // Handle the large object space.
1084 space::LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
Mathieu Chartierdb7f37d2014-01-10 11:09:06 -08001085 accounting::ObjectSet* large_live_objects = large_object_space->GetLiveObjects();
1086 accounting::ObjectSet* large_mark_objects = large_object_space->GetMarkObjects();
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001087 if (swap_bitmaps) {
1088 std::swap(large_live_objects, large_mark_objects);
1089 }
Brian Carlstrom02c8cc62013-07-18 15:54:44 -07001090 for (size_t i = 0; i < count; ++i) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001091 Object* obj = objects[i];
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001092 // Handle large objects.
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08001093 if (kUseThreadLocalAllocationStack && obj == nullptr) {
1094 continue;
1095 }
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001096 if (!large_mark_objects->Test(obj)) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001097 ++freed_large_objects;
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001098 freed_large_object_bytes += large_object_space->Free(self, obj);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001099 }
1100 }
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001101 timings_.EndSplit();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001102
Hiroshi Yamauchib22a4512013-08-13 15:03:22 -07001103 timings_.StartSplit("RecordFree");
Mathieu Chartier40e978b2012-09-07 11:38:36 -07001104 VLOG(heap) << "Freed " << freed_objects << "/" << count
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001105 << " objects with size " << PrettySize(freed_bytes);
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001106 heap_->RecordFree(freed_objects + freed_large_objects, freed_bytes + freed_large_object_bytes);
Ian Rogersb122a4b2013-11-19 18:00:50 -08001107 freed_objects_.FetchAndAdd(freed_objects);
1108 freed_large_objects_.FetchAndAdd(freed_large_objects);
1109 freed_bytes_.FetchAndAdd(freed_bytes);
1110 freed_large_object_bytes_.FetchAndAdd(freed_large_object_bytes);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001111 timings_.EndSplit();
Ian Rogers1d54e732013-05-02 21:10:01 -07001112
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001113 timings_.StartSplit("ResetStack");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001114 allocations->Reset();
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001115 timings_.EndSplit();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001116}
1117
Ian Rogers1d54e732013-05-02 21:10:01 -07001118void MarkSweep::Sweep(bool swap_bitmaps) {
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -07001119 // Ensure that nobody inserted items in the live stack after we swapped the stacks.
1120 CHECK_GE(live_stack_freeze_size_, GetHeap()->GetLiveStack()->Size());
1121 // Mark everything allocated since the last as GC live so that we can sweep concurrently,
1122 // knowing that new allocations won't be marked as live.
1123 timings_.StartSplit("MarkStackAsLive");
1124 accounting::ObjectStack* live_stack = heap_->GetLiveStack();
1125 heap_->MarkAllocStackAsLive(live_stack);
1126 live_stack->Reset();
1127 timings_.EndSplit();
1128
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001129 DCHECK(mark_stack_->IsEmpty());
Ian Rogers5fe9af72013-11-14 00:17:20 -08001130 TimingLogger::ScopedSplit("Sweep", &timings_);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001131 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Mathieu Chartiera1602f22014-01-13 17:19:19 -08001132 if (space->IsContinuousMemMapAllocSpace()) {
1133 space::ContinuousMemMapAllocSpace* alloc_space = space->AsContinuousMemMapAllocSpace();
Mathieu Chartierec050072014-01-07 16:00:07 -08001134 TimingLogger::ScopedSplit split(
Mathieu Chartiera1602f22014-01-13 17:19:19 -08001135 alloc_space->IsZygoteSpace() ? "SweepZygoteSpace" : "SweepMallocSpace", &timings_);
Mathieu Chartierec050072014-01-07 16:00:07 -08001136 size_t freed_objects = 0;
1137 size_t freed_bytes = 0;
Mathieu Chartiera1602f22014-01-13 17:19:19 -08001138 alloc_space->Sweep(swap_bitmaps, &freed_objects, &freed_bytes);
Mathieu Chartierec050072014-01-07 16:00:07 -08001139 heap_->RecordFree(freed_objects, freed_bytes);
1140 freed_objects_.FetchAndAdd(freed_objects);
1141 freed_bytes_.FetchAndAdd(freed_bytes);
Carl Shapiro58551df2011-07-24 03:09:51 -07001142 }
1143 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001144 SweepLargeObjects(swap_bitmaps);
Carl Shapiro58551df2011-07-24 03:09:51 -07001145}
1146
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001147void MarkSweep::SweepLargeObjects(bool swap_bitmaps) {
Ian Rogers5fe9af72013-11-14 00:17:20 -08001148 TimingLogger::ScopedSplit("SweepLargeObjects", &timings_);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001149 size_t freed_objects = 0;
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001150 size_t freed_bytes = 0;
Mathieu Chartierdb7f37d2014-01-10 11:09:06 -08001151 GetHeap()->GetLargeObjectsSpace()->Sweep(swap_bitmaps, &freed_objects, &freed_bytes);
Ian Rogersb122a4b2013-11-19 18:00:50 -08001152 freed_large_objects_.FetchAndAdd(freed_objects);
1153 freed_large_object_bytes_.FetchAndAdd(freed_bytes);
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001154 GetHeap()->RecordFree(freed_objects, freed_bytes);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001155}
1156
Mathieu Chartier407f7022014-02-18 14:37:05 -08001157// Process the "referent" field in a java.lang.ref.Reference. If the referent has not yet been
1158// marked, put it on the appropriate list in the heap for later processing.
1159void MarkSweep::DelayReferenceReferent(mirror::Class* klass, mirror::Reference* ref) {
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001160 DCHECK(klass != nullptr);
Mathieu Chartier0e54cd02014-03-20 12:41:23 -07001161 if (kCountJavaLangRefs) {
1162 ++reference_count_;
1163 }
Mathieu Chartier407f7022014-02-18 14:37:05 -08001164 heap_->DelayReferenceReferent(klass, ref, IsMarkedCallback, this);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001165}
1166
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001167class MarkObjectVisitor {
1168 public:
Mathieu Chartier407f7022014-02-18 14:37:05 -08001169 explicit MarkObjectVisitor(MarkSweep* const mark_sweep) ALWAYS_INLINE : mark_sweep_(mark_sweep) {
1170 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001171
Mathieu Chartier407f7022014-02-18 14:37:05 -08001172 void operator()(Object* obj, MemberOffset offset, bool /* is_static */) const
1173 ALWAYS_INLINE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1174 EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001175 if (kCheckLocks) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001176 Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
1177 Locks::heap_bitmap_lock_->AssertExclusiveHeld(Thread::Current());
1178 }
Mathieu Chartier407f7022014-02-18 14:37:05 -08001179 mark_sweep_->MarkObject(obj->GetFieldObject<mirror::Object>(offset, false));
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001180 }
1181
1182 private:
1183 MarkSweep* const mark_sweep_;
1184};
1185
Carl Shapiro69759ea2011-07-21 18:13:35 -07001186// Scans an object reference. Determines the type of the reference
1187// and dispatches to a specialized scanning routine.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001188void MarkSweep::ScanObject(Object* obj) {
Mathieu Chartier407f7022014-02-18 14:37:05 -08001189 MarkObjectVisitor mark_visitor(this);
1190 DelayReferenceReferentVisitor ref_visitor(this);
1191 ScanObjectVisit(obj, mark_visitor, ref_visitor);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001192}
1193
Mathieu Chartier3bb57c72014-02-18 11:38:45 -08001194void MarkSweep::ProcessMarkStackPausedCallback(void* arg) {
Mathieu Chartier3bb57c72014-02-18 11:38:45 -08001195 reinterpret_cast<MarkSweep*>(arg)->ProcessMarkStack(true);
1196}
1197
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001198void MarkSweep::ProcessMarkStackParallel(size_t thread_count) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001199 Thread* self = Thread::Current();
1200 ThreadPool* thread_pool = GetHeap()->GetThreadPool();
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001201 const size_t chunk_size = std::min(mark_stack_->Size() / thread_count + 1,
1202 static_cast<size_t>(MarkStackTask<false>::kMaxSize));
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001203 CHECK_GT(chunk_size, 0U);
1204 // Split the current mark stack up into work tasks.
1205 for (mirror::Object **it = mark_stack_->Begin(), **end = mark_stack_->End(); it < end; ) {
1206 const size_t delta = std::min(static_cast<size_t>(end - it), chunk_size);
Mathieu Chartier0e54cd02014-03-20 12:41:23 -07001207 thread_pool->AddTask(self, new MarkStackTask<false>(thread_pool, this, delta, it));
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001208 it += delta;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001209 }
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001210 thread_pool->SetMaxActiveWorkers(thread_count - 1);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001211 thread_pool->StartWorkers(self);
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001212 thread_pool->Wait(self, true, true);
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001213 thread_pool->StopWorkers(self);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001214 mark_stack_->Reset();
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001215 CHECK_EQ(work_chunks_created_, work_chunks_deleted_) << " some of the work chunks were leaked";
Carl Shapiro69759ea2011-07-21 18:13:35 -07001216}
1217
Ian Rogers5d76c432011-10-31 21:42:49 -07001218// Scan anything that's on the mark stack.
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001219void MarkSweep::ProcessMarkStack(bool paused) {
Mathieu Chartier3bb57c72014-02-18 11:38:45 -08001220 timings_.StartSplit(paused ? "(Paused)ProcessMarkStack" : "ProcessMarkStack");
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001221 size_t thread_count = GetThreadCount(paused);
1222 if (kParallelProcessMarkStack && thread_count > 1 &&
1223 mark_stack_->Size() >= kMinimumParallelMarkStackSize) {
1224 ProcessMarkStackParallel(thread_count);
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001225 } else {
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001226 // TODO: Tune this.
1227 static const size_t kFifoSize = 4;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001228 BoundedFifoPowerOfTwo<Object*, kFifoSize> prefetch_fifo;
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001229 for (;;) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001230 Object* obj = NULL;
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001231 if (kUseMarkStackPrefetch) {
1232 while (!mark_stack_->IsEmpty() && prefetch_fifo.size() < kFifoSize) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001233 Object* obj = mark_stack_->PopBack();
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001234 DCHECK(obj != NULL);
1235 __builtin_prefetch(obj);
1236 prefetch_fifo.push_back(obj);
1237 }
1238 if (prefetch_fifo.empty()) {
1239 break;
1240 }
1241 obj = prefetch_fifo.front();
1242 prefetch_fifo.pop_front();
1243 } else {
1244 if (mark_stack_->IsEmpty()) {
1245 break;
1246 }
1247 obj = mark_stack_->PopBack();
1248 }
Mathieu Chartier4aeec172014-03-27 16:09:46 -07001249 DCHECK(obj != nullptr);
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001250 ScanObject(obj);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001251 }
1252 }
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001253 timings_.EndSplit();
Carl Shapiro69759ea2011-07-21 18:13:35 -07001254}
1255
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001256inline bool MarkSweep::IsMarked(const Object* object) const
1257 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
Mathieu Chartier8d562102014-03-12 17:42:10 -07001258 if (immune_region_.ContainsObject(object)) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001259 return true;
1260 }
Mathieu Chartier0e54cd02014-03-20 12:41:23 -07001261 if (current_space_bitmap_->HasAddress(object)) {
1262 return current_space_bitmap_->Test(object);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001263 }
Mathieu Chartier0e54cd02014-03-20 12:41:23 -07001264 return mark_bitmap_->Test(object);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001265}
1266
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001267void MarkSweep::FinishPhase() {
Ian Rogers5fe9af72013-11-14 00:17:20 -08001268 TimingLogger::ScopedSplit split("FinishPhase", &timings_);
Anwar Ghuloum46543222013-08-12 09:28:42 -07001269 // Can't enqueue references if we hold the mutator lock.
Anwar Ghuloum46543222013-08-12 09:28:42 -07001270 timings_.NewSplit("PostGcVerification");
Mathieu Chartier4aeec172014-03-27 16:09:46 -07001271 heap_->PostGcVerification(this);
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001272 if (kCountScannedTypes) {
1273 VLOG(gc) << "MarkSweep scanned classes=" << class_count_ << " arrays=" << array_count_
1274 << " other=" << other_count_;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001275 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001276 if (kCountTasks) {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001277 VLOG(gc) << "Total number of work chunks allocated: " << work_chunks_created_;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001278 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001279 if (kMeasureOverhead) {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001280 VLOG(gc) << "Overhead time " << PrettyDuration(overhead_time_);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001281 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001282 if (kProfileLargeObjects) {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001283 VLOG(gc) << "Large objects tested " << large_object_test_ << " marked " << large_object_mark_;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001284 }
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001285 if (kCountJavaLangRefs) {
1286 VLOG(gc) << "References scanned " << reference_count_;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001287 }
Mathieu Chartier0e54cd02014-03-20 12:41:23 -07001288 if (kCountMarkedObjects) {
1289 VLOG(gc) << "Marked: null=" << mark_null_count_ << " immune=" << mark_immune_count_
1290 << " fastpath=" << mark_fastpath_count_ << " slowpath=" << mark_slowpath_count_;
1291 }
Mathieu Chartier4aeec172014-03-27 16:09:46 -07001292 CHECK(mark_stack_->IsEmpty()); // Ensure that the mark stack is empty.
Mathieu Chartier5301cd22012-05-31 12:11:36 -07001293 mark_stack_->Reset();
Mathieu Chartier4aeec172014-03-27 16:09:46 -07001294 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
1295 heap_->ClearMarkedObjects();
Carl Shapiro69759ea2011-07-21 18:13:35 -07001296}
1297
Hiroshi Yamauchic93c5302014-03-20 16:15:37 -07001298void MarkSweep::RevokeAllThreadLocalBuffers() {
1299 if (kRevokeRosAllocThreadLocalBuffersAtCheckpoint && IsConcurrent()) {
1300 // If concurrent, rosalloc thread-local buffers are revoked at the
1301 // thread checkpoint. Bump pointer space thread-local buffers must
1302 // not be in use.
1303 GetHeap()->AssertAllBumpPointerSpaceThreadLocalBuffersAreRevoked();
1304 } else {
1305 timings_.StartSplit("(Paused)RevokeAllThreadLocalBuffers");
1306 GetHeap()->RevokeAllThreadLocalBuffers();
1307 timings_.EndSplit();
1308 }
1309}
1310
Ian Rogers1d54e732013-05-02 21:10:01 -07001311} // namespace collector
1312} // namespace gc
Carl Shapiro69759ea2011-07-21 18:13:35 -07001313} // namespace art