blob: 8b9f60efb2debe5bd4695e653bf6d13c3cd0a9f8 [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"
30#include "gc/accounting/heap_bitmap.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"
Elliott Hughes410c0c82011-09-01 17:58:25 -070037#include "indirect_reference_table.h"
38#include "intern_table.h"
Ian Rogers81d425b2012-09-27 16:03:43 -070039#include "jni_internal.h"
Elliott Hughesc33a32b2011-10-11 18:18:07 -070040#include "monitor.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080041#include "mark_sweep-inl.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070042#include "mirror/art_field.h"
43#include "mirror/art_field-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080044#include "mirror/class-inl.h"
45#include "mirror/class_loader.h"
46#include "mirror/dex_cache.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080047#include "mirror/object-inl.h"
48#include "mirror/object_array.h"
49#include "mirror/object_array-inl.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070050#include "runtime.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070051#include "thread-inl.h"
Mathieu Chartier6f1c9492012-10-15 12:08:41 -070052#include "thread_list.h"
Ian Rogers08254272012-10-23 17:49:23 -070053#include "verifier/method_verifier.h"
Carl Shapiro69759ea2011-07-21 18:13:35 -070054
Brian Carlstromea46f952013-07-30 01:26:50 -070055using ::art::mirror::ArtField;
Brian Carlstrom3e3d5912013-07-18 00:19:45 -070056using ::art::mirror::Class;
Brian Carlstrom3e3d5912013-07-18 00:19:45 -070057using ::art::mirror::Object;
58using ::art::mirror::ObjectArray;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080059
Carl Shapiro69759ea2011-07-21 18:13:35 -070060namespace art {
Ian Rogers1d54e732013-05-02 21:10:01 -070061namespace gc {
62namespace collector {
Carl Shapiro69759ea2011-07-21 18:13:35 -070063
Mathieu Chartier02b6a782012-10-26 13:51:26 -070064// Performance options.
Mathieu Chartiereb7bbad2014-02-25 15:52:46 -080065static constexpr bool kUseRecursiveMark = false;
66static constexpr bool kUseMarkStackPrefetch = true;
67static constexpr size_t kSweepArrayChunkFreeSize = 1024;
68static constexpr bool kPreCleanCards = true;
Mathieu Chartier94c32c52013-08-09 11:14:04 -070069
70// Parallelism options.
Mathieu Chartiereb7bbad2014-02-25 15:52:46 -080071static constexpr bool kParallelCardScan = true;
72static constexpr bool kParallelRecursiveMark = true;
Mathieu Chartier94c32c52013-08-09 11:14:04 -070073// Don't attempt to parallelize mark stack processing unless the mark stack is at least n
74// elements. This is temporary until we reduce the overhead caused by allocating tasks, etc.. Not
75// having this can add overhead in ProcessReferences since we may end up doing many calls of
76// ProcessMarkStack with very small mark stacks.
Mathieu Chartiereb7bbad2014-02-25 15:52:46 -080077static constexpr size_t kMinimumParallelMarkStackSize = 128;
78static constexpr bool kParallelProcessMarkStack = true;
Mathieu Chartier858f1c52012-10-17 17:45:55 -070079
Mathieu Chartier02b6a782012-10-26 13:51:26 -070080// Profiling and information flags.
Mathieu Chartiereb7bbad2014-02-25 15:52:46 -080081static constexpr bool kCountClassesMarked = false;
82static constexpr bool kProfileLargeObjects = false;
83static constexpr bool kMeasureOverhead = false;
84static constexpr bool kCountTasks = false;
85static constexpr bool kCountJavaLangRefs = false;
Mathieu Chartier94c32c52013-08-09 11:14:04 -070086
87// Turn off kCheckLocks when profiling the GC since it slows the GC down by up to 40%.
Mathieu Chartiereb7bbad2014-02-25 15:52:46 -080088static constexpr bool kCheckLocks = kDebugLocking;
Mathieu Chartier893263b2014-03-04 11:07:42 -080089static constexpr bool kVerifyRoots = kIsDebugBuild;
Mathieu Chartier02b6a782012-10-26 13:51:26 -070090
Mathieu Chartier2b82db42012-11-14 17:29:05 -080091void MarkSweep::BindBitmaps() {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -070092 timings_.StartSplit("BindBitmaps");
Mathieu Chartier2b82db42012-11-14 17:29:05 -080093 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -080094 // Mark all of the spaces we never collect as immune.
Mathieu Chartier94c32c52013-08-09 11:14:04 -070095 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Ian Rogers1d54e732013-05-02 21:10:01 -070096 if (space->GetGcRetentionPolicy() == space::kGcRetentionPolicyNeverCollect) {
Mathieu Chartier8d562102014-03-12 17:42:10 -070097 CHECK(immune_region_.AddContinuousSpace(space)) << "Failed to add space " << *space;
Mathieu Chartier2b82db42012-11-14 17:29:05 -080098 }
99 }
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700100 timings_.EndSplit();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800101}
102
Ian Rogers1d54e732013-05-02 21:10:01 -0700103MarkSweep::MarkSweep(Heap* heap, bool is_concurrent, const std::string& name_prefix)
104 : GarbageCollector(heap,
Mathieu Chartier590fee92013-09-13 13:46:47 -0700105 name_prefix +
Ian Rogers1d54e732013-05-02 21:10:01 -0700106 (is_concurrent ? "concurrent mark sweep": "mark sweep")),
107 current_mark_bitmap_(NULL),
Ian Rogers1d54e732013-05-02 21:10:01 -0700108 mark_stack_(NULL),
Ian Rogers906457c2013-11-13 23:28:08 -0800109 live_stack_freeze_size_(0),
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800110 gc_barrier_(new Barrier(0)),
Ian Rogers62d6c772013-02-27 08:32:07 -0800111 large_object_lock_("mark sweep large object lock", kMarkSweepLargeObjectLock),
Mathieu Chartier958291c2013-08-27 18:14:55 -0700112 mark_stack_lock_("mark sweep mark stack lock", kMarkSweepMarkStackLock),
Mathieu Chartier590fee92013-09-13 13:46:47 -0700113 is_concurrent_(is_concurrent) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800114}
115
116void MarkSweep::InitializePhase() {
Ian Rogers1d54e732013-05-02 21:10:01 -0700117 timings_.Reset();
Ian Rogers5fe9af72013-11-14 00:17:20 -0800118 TimingLogger::ScopedSplit split("InitializePhase", &timings_);
Mathieu Chartiere53225c2013-08-19 10:59:11 -0700119 mark_stack_ = heap_->mark_stack_.get();
120 DCHECK(mark_stack_ != nullptr);
Mathieu Chartier8d562102014-03-12 17:42:10 -0700121 immune_region_.Reset();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800122 class_count_ = 0;
123 array_count_ = 0;
124 other_count_ = 0;
125 large_object_test_ = 0;
126 large_object_mark_ = 0;
127 classes_marked_ = 0;
128 overhead_time_ = 0;
129 work_chunks_created_ = 0;
130 work_chunks_deleted_ = 0;
131 reference_count_ = 0;
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700132
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700133 FindDefaultMarkBitmap();
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700134
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700135 // Do any pre GC verification.
Anwar Ghuloum46543222013-08-12 09:28:42 -0700136 timings_.NewSplit("PreGcVerification");
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800137 heap_->PreGcVerification(this);
138}
139
140void MarkSweep::ProcessReferences(Thread* self) {
Ian Rogers5fe9af72013-11-14 00:17:20 -0800141 TimingLogger::ScopedSplit split("ProcessReferences", &timings_);
Mathieu Chartier8e56c7e2012-11-20 13:25:50 -0800142 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier39e32612013-11-12 16:28:05 -0800143 GetHeap()->ProcessReferences(timings_, clear_soft_references_, &IsMarkedCallback,
Mathieu Chartier3bb57c72014-02-18 11:38:45 -0800144 &MarkObjectCallback, &ProcessMarkStackPausedCallback, this);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800145}
146
147bool MarkSweep::HandleDirtyObjectsPhase() {
Mathieu Chartier3bb57c72014-02-18 11:38:45 -0800148 TimingLogger::ScopedSplit split("(Paused)HandleDirtyObjectsPhase", &timings_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800149 Thread* self = Thread::Current();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800150 Locks::mutator_lock_->AssertExclusiveHeld(self);
151
152 {
153 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
154
155 // Re-mark root set.
156 ReMarkRoots();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800157
158 // Scan dirty objects, this is only required if we are not doing concurrent GC.
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700159 RecursiveMarkDirtyObjects(true, accounting::CardTable::kCardDirty);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800160 }
161
162 ProcessReferences(self);
163
164 // Only need to do this if we have the card mark verification on, and only during concurrent GC.
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700165 if (GetHeap()->verify_missing_card_marks_ || GetHeap()->verify_pre_gc_heap_||
166 GetHeap()->verify_post_gc_heap_) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800167 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
168 // This second sweep makes sure that we don't have any objects in the live stack which point to
169 // freed objects. These cause problems since their references may be previously freed objects.
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700170 SweepArray(GetHeap()->allocation_stack_.get(), false);
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -0800171 // Since SweepArray() above resets the (active) allocation
172 // stack. Need to revoke the thread-local allocation stacks that
173 // point into it.
Mathieu Chartierc22c59e2014-02-24 15:16:06 -0800174 RevokeAllThreadLocalAllocationStacks(self);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800175 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700176
177 timings_.StartSplit("PreSweepingGcVerification");
178 heap_->PreSweepingGcVerification(this);
179 timings_.EndSplit();
180
181 // Ensure that nobody inserted items in the live stack after we swapped the stacks.
182 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
183 CHECK_GE(live_stack_freeze_size_, GetHeap()->GetLiveStack()->Size());
Mathieu Chartierc11d9b82013-09-19 10:01:59 -0700184
185 // Disallow new system weaks to prevent a race which occurs when someone adds a new system
186 // weak before we sweep them. Since this new system weak may not be marked, the GC may
187 // incorrectly sweep it. This also fixes a race where interning may attempt to return a strong
188 // reference to a string that is about to be swept.
189 Runtime::Current()->DisallowNewSystemWeaks();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800190 return true;
191}
192
193bool MarkSweep::IsConcurrent() const {
194 return is_concurrent_;
195}
196
Mathieu Chartierdda54f52014-02-24 09:58:40 -0800197void MarkSweep::PreCleanCards() {
198 // Don't do this for non concurrent GCs since they don't have any dirty cards.
199 if (kPreCleanCards && IsConcurrent()) {
200 Thread* self = Thread::Current();
201 CHECK(!Locks::mutator_lock_->IsExclusiveHeld(self));
202 // Process dirty cards and add dirty cards to mod union tables, also ages cards.
203 heap_->ProcessCards(timings_);
Mathieu Chartiereb7bbad2014-02-25 15:52:46 -0800204 // The checkpoint root marking is required to avoid a race condition which occurs if the
205 // following happens during a reference write:
206 // 1. mutator dirties the card (write barrier)
207 // 2. GC ages the card (the above ProcessCards call)
208 // 3. GC scans the object (the RecursiveMarkDirtyObjects call below)
209 // 4. mutator writes the value (corresponding to the write barrier in 1.)
210 // This causes the GC to age the card but not necessarily mark the reference which the mutator
211 // wrote into the object stored in the card.
212 // Having the checkpoint fixes this issue since it ensures that the card mark and the
213 // reference write are visible to the GC before the card is scanned (this is due to locks being
214 // acquired / released in the checkpoint code).
215 // The other roots are also marked to help reduce the pause.
Mathieu Chartierdda54f52014-02-24 09:58:40 -0800216 MarkThreadRoots(self);
217 // TODO: Only mark the dirty roots.
218 MarkNonThreadRoots();
Mathieu Chartier893263b2014-03-04 11:07:42 -0800219 MarkConcurrentRoots(
220 static_cast<VisitRootFlags>(kVisitRootFlagClearRootLog | kVisitRootFlagNewRoots));
Mathieu Chartierdda54f52014-02-24 09:58:40 -0800221 // Process the newly aged cards.
222 RecursiveMarkDirtyObjects(false, accounting::CardTable::kCardDirty - 1);
223 // TODO: Empty allocation stack to reduce the number of objects we need to test / mark as live
224 // in the next GC.
225 }
226}
227
Mathieu Chartierc22c59e2014-02-24 15:16:06 -0800228void MarkSweep::RevokeAllThreadLocalAllocationStacks(Thread* self) {
229 if (kUseThreadLocalAllocationStack) {
230 Locks::mutator_lock_->AssertExclusiveHeld(self);
231 heap_->RevokeAllThreadLocalAllocationStacks(self);
232 }
233}
234
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800235void MarkSweep::MarkingPhase() {
Ian Rogers5fe9af72013-11-14 00:17:20 -0800236 TimingLogger::ScopedSplit split("MarkingPhase", &timings_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800237 Thread* self = Thread::Current();
238
239 BindBitmaps();
240 FindDefaultMarkBitmap();
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700241
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800242 // Process dirty cards and add dirty cards to mod union tables.
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700243 heap_->ProcessCards(timings_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800244
245 // Need to do this before the checkpoint since we don't want any threads to add references to
246 // the live stack during the recursive mark.
Anwar Ghuloum46543222013-08-12 09:28:42 -0700247 timings_.NewSplit("SwapStacks");
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -0800248 heap_->SwapStacks(self);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800249
250 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier893263b2014-03-04 11:07:42 -0800251 MarkRoots(self);
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700252 live_stack_freeze_size_ = heap_->GetLiveStack()->Size();
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700253 UpdateAndMarkModUnion();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800254 MarkReachableObjects();
Mathieu Chartierdda54f52014-02-24 09:58:40 -0800255 // Pre-clean dirtied cards to reduce pauses.
256 PreCleanCards();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800257}
258
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700259void MarkSweep::UpdateAndMarkModUnion() {
260 for (const auto& space : heap_->GetContinuousSpaces()) {
Mathieu Chartier8d562102014-03-12 17:42:10 -0700261 if (immune_region_.ContainsSpace(space)) {
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700262 const char* name = space->IsZygoteSpace() ? "UpdateAndMarkZygoteModUnionTable" :
263 "UpdateAndMarkImageModUnionTable";
Ian Rogers5fe9af72013-11-14 00:17:20 -0800264 TimingLogger::ScopedSplit split(name, &timings_);
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700265 accounting::ModUnionTable* mod_union_table = heap_->FindModUnionTableFromSpace(space);
266 CHECK(mod_union_table != nullptr);
Mathieu Chartier815873e2014-02-13 18:02:13 -0800267 mod_union_table->UpdateAndMarkReferences(MarkObjectCallback, this);
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700268 }
269 }
270}
271
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700272void MarkSweep::MarkThreadRoots(Thread* self) {
273 MarkRootsCheckpoint(self);
274}
275
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800276void MarkSweep::MarkReachableObjects() {
277 // Mark everything allocated since the last as GC live so that we can sweep concurrently,
278 // knowing that new allocations won't be marked as live.
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700279 timings_.StartSplit("MarkStackAsLive");
Ian Rogers1d54e732013-05-02 21:10:01 -0700280 accounting::ObjectStack* live_stack = heap_->GetLiveStack();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700281 heap_->MarkAllocStackAsLive(live_stack);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800282 live_stack->Reset();
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700283 timings_.EndSplit();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800284 // Recursively mark all the non-image bits set in the mark bitmap.
285 RecursiveMark();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800286}
287
288void MarkSweep::ReclaimPhase() {
Ian Rogers5fe9af72013-11-14 00:17:20 -0800289 TimingLogger::ScopedSplit split("ReclaimPhase", &timings_);
Mathieu Chartier720ef762013-08-17 14:46:54 -0700290 Thread* self = Thread::Current();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800291
292 if (!IsConcurrent()) {
293 ProcessReferences(self);
Mathieu Chartierc11d9b82013-09-19 10:01:59 -0700294 }
295
296 {
297 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
298 SweepSystemWeaks();
299 }
300
301 if (IsConcurrent()) {
302 Runtime::Current()->AllowNewSystemWeaks();
303
Ian Rogers5fe9af72013-11-14 00:17:20 -0800304 TimingLogger::ScopedSplit split("UnMarkAllocStack", &timings_);
Mathieu Chartier9642c962013-08-05 17:40:36 -0700305 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700306 accounting::ObjectStack* allocation_stack = GetHeap()->allocation_stack_.get();
Mathieu Chartierdda54f52014-02-24 09:58:40 -0800307 if (!kPreCleanCards) {
308 // The allocation stack contains things allocated since the start of the GC. These may have
309 // been marked during this GC meaning they won't be eligible for reclaiming in the next
310 // sticky GC. Unmark these objects so that they are eligible for reclaiming in the next
311 // sticky GC.
312 // There is a race here which is safely handled. Another thread such as the hprof could
313 // have flushed the alloc stack after we resumed the threads. This is safe however, since
314 // reseting the allocation stack zeros it out with madvise. This means that we will either
315 // read NULLs or attempt to unmark a newly allocated object which will not be marked in the
316 // first place.
317 // We can't do this if we pre-clean cards since we will unmark objects which are no longer on
318 // a dirty card since we aged cards during the pre-cleaning process.
319 mirror::Object** end = allocation_stack->End();
320 for (mirror::Object** it = allocation_stack->Begin(); it != end; ++it) {
321 const Object* obj = *it;
322 if (obj != nullptr) {
323 UnMarkObjectNonNull(obj);
324 }
Mathieu Chartier9642c962013-08-05 17:40:36 -0700325 }
326 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800327 }
328
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800329 {
330 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
331
332 // Reclaim unmarked objects.
Ian Rogers1d54e732013-05-02 21:10:01 -0700333 Sweep(false);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800334
335 // Swap the live and mark bitmaps for each space which we modified space. This is an
336 // optimization that enables us to not clear live bits inside of the sweep. Only swaps unbound
337 // bitmaps.
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700338 timings_.StartSplit("SwapBitmaps");
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800339 SwapBitmaps();
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700340 timings_.EndSplit();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800341
342 // Unbind the live and mark bitmaps.
Mathieu Chartiera1602f22014-01-13 17:19:19 -0800343 TimingLogger::ScopedSplit split("UnBindBitmaps", &timings_);
344 GetHeap()->UnBindBitmaps();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800345 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800346}
347
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700348void MarkSweep::FindDefaultMarkBitmap() {
Ian Rogers5fe9af72013-11-14 00:17:20 -0800349 TimingLogger::ScopedSplit split("FindDefaultMarkBitmap", &timings_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700350 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700351 accounting::SpaceBitmap* bitmap = space->GetMarkBitmap();
352 if (bitmap != nullptr &&
353 space->GetGcRetentionPolicy() == space::kGcRetentionPolicyAlwaysCollect) {
354 current_mark_bitmap_ = bitmap;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700355 CHECK(current_mark_bitmap_ != NULL);
356 return;
357 }
358 }
359 GetHeap()->DumpSpaces();
360 LOG(FATAL) << "Could not find a default mark bitmap";
361}
362
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800363void MarkSweep::ExpandMarkStack() {
Mathieu Chartierba311b42013-08-27 13:02:30 -0700364 ResizeMarkStack(mark_stack_->Capacity() * 2);
365}
366
367void MarkSweep::ResizeMarkStack(size_t new_size) {
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800368 // Rare case, no need to have Thread::Current be a parameter.
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800369 if (UNLIKELY(mark_stack_->Size() < mark_stack_->Capacity())) {
370 // Someone else acquired the lock and expanded the mark stack before us.
371 return;
372 }
Mathieu Chartier02e25112013-08-14 16:14:24 -0700373 std::vector<Object*> temp(mark_stack_->Begin(), mark_stack_->End());
Mathieu Chartierba311b42013-08-27 13:02:30 -0700374 CHECK_LE(mark_stack_->Size(), new_size);
375 mark_stack_->Resize(new_size);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700376 for (const auto& obj : temp) {
377 mark_stack_->PushBack(obj);
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800378 }
379}
380
Mathieu Chartier9642c962013-08-05 17:40:36 -0700381inline void MarkSweep::MarkObjectNonNullParallel(const Object* obj) {
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800382 DCHECK(obj != NULL);
383 if (MarkObjectParallel(obj)) {
Mathieu Chartierba311b42013-08-27 13:02:30 -0700384 MutexLock mu(Thread::Current(), mark_stack_lock_);
385 if (UNLIKELY(mark_stack_->Size() >= mark_stack_->Capacity())) {
Mathieu Chartier184e3222013-08-03 14:02:57 -0700386 ExpandMarkStack();
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800387 }
Mathieu Chartierba311b42013-08-27 13:02:30 -0700388 // The object must be pushed on to the mark stack.
389 mark_stack_->PushBack(const_cast<Object*>(obj));
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800390 }
391}
392
Mathieu Chartier3bb57c72014-02-18 11:38:45 -0800393mirror::Object* MarkSweep::MarkObjectCallback(mirror::Object* obj, void* arg) {
Mathieu Chartier39e32612013-11-12 16:28:05 -0800394 MarkSweep* mark_sweep = reinterpret_cast<MarkSweep*>(arg);
395 mark_sweep->MarkObject(obj);
Mathieu Chartier39e32612013-11-12 16:28:05 -0800396 return obj;
397}
398
Mathieu Chartier9642c962013-08-05 17:40:36 -0700399inline void MarkSweep::UnMarkObjectNonNull(const Object* obj) {
Mathieu Chartier8d562102014-03-12 17:42:10 -0700400 DCHECK(!immune_region_.ContainsObject(obj));
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800401
402 if (kUseBrooksPointer) {
403 // Verify all the objects have the correct Brooks pointer installed.
404 obj->AssertSelfBrooksPointer();
405 }
406
Mathieu Chartier9642c962013-08-05 17:40:36 -0700407 // Try to take advantage of locality of references within a space, failing this find the space
408 // the hard way.
409 accounting::SpaceBitmap* object_bitmap = current_mark_bitmap_;
410 if (UNLIKELY(!object_bitmap->HasAddress(obj))) {
411 accounting::SpaceBitmap* new_bitmap = heap_->GetMarkBitmap()->GetContinuousSpaceBitmap(obj);
412 if (LIKELY(new_bitmap != NULL)) {
413 object_bitmap = new_bitmap;
414 } else {
415 MarkLargeObject(obj, false);
416 return;
417 }
418 }
419
420 DCHECK(object_bitmap->HasAddress(obj));
421 object_bitmap->Clear(obj);
422}
423
424inline void MarkSweep::MarkObjectNonNull(const Object* obj) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700425 DCHECK(obj != NULL);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700426
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800427 if (kUseBrooksPointer) {
428 // Verify all the objects have the correct Brooks pointer installed.
429 obj->AssertSelfBrooksPointer();
430 }
431
Mathieu Chartier8d562102014-03-12 17:42:10 -0700432 if (immune_region_.ContainsObject(obj)) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700433 DCHECK(IsMarked(obj));
Carl Shapiro69759ea2011-07-21 18:13:35 -0700434 return;
435 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700436
437 // Try to take advantage of locality of references within a space, failing this find the space
438 // the hard way.
Ian Rogers1d54e732013-05-02 21:10:01 -0700439 accounting::SpaceBitmap* object_bitmap = current_mark_bitmap_;
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700440 if (UNLIKELY(!object_bitmap->HasAddress(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700441 accounting::SpaceBitmap* new_bitmap = heap_->GetMarkBitmap()->GetContinuousSpaceBitmap(obj);
442 if (LIKELY(new_bitmap != NULL)) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700443 object_bitmap = new_bitmap;
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700444 } else {
Mathieu Chartier9642c962013-08-05 17:40:36 -0700445 MarkLargeObject(obj, true);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700446 return;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700447 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700448 }
449
Carl Shapiro69759ea2011-07-21 18:13:35 -0700450 // This object was not previously marked.
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700451 if (!object_bitmap->Test(obj)) {
452 object_bitmap->Set(obj);
Mathieu Chartier184e3222013-08-03 14:02:57 -0700453 if (UNLIKELY(mark_stack_->Size() >= mark_stack_->Capacity())) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700454 // Lock is not needed but is here anyways to please annotalysis.
455 MutexLock mu(Thread::Current(), mark_stack_lock_);
Mathieu Chartier184e3222013-08-03 14:02:57 -0700456 ExpandMarkStack();
Carl Shapiro69759ea2011-07-21 18:13:35 -0700457 }
Mathieu Chartier184e3222013-08-03 14:02:57 -0700458 // The object must be pushed on to the mark stack.
459 mark_stack_->PushBack(const_cast<Object*>(obj));
Carl Shapiro69759ea2011-07-21 18:13:35 -0700460 }
461}
462
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700463// Rare case, probably not worth inlining since it will increase instruction cache miss rate.
Mathieu Chartier9642c962013-08-05 17:40:36 -0700464bool MarkSweep::MarkLargeObject(const Object* obj, bool set) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700465 // TODO: support >1 discontinuous space.
466 space::LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
Mathieu Chartierdb7f37d2014-01-10 11:09:06 -0800467 accounting::ObjectSet* large_objects = large_object_space->GetMarkObjects();
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700468 if (kProfileLargeObjects) {
469 ++large_object_test_;
470 }
471 if (UNLIKELY(!large_objects->Test(obj))) {
Mathieu Chartier4fcb8d32013-07-15 12:43:36 -0700472 if (!large_object_space->Contains(obj)) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700473 LOG(ERROR) << "Tried to mark " << obj << " not contained by any spaces";
474 LOG(ERROR) << "Attempting see if it's a bad root";
475 VerifyRoots();
476 LOG(FATAL) << "Can't mark bad root";
477 }
478 if (kProfileLargeObjects) {
479 ++large_object_mark_;
480 }
Mathieu Chartier9642c962013-08-05 17:40:36 -0700481 if (set) {
482 large_objects->Set(obj);
483 } else {
484 large_objects->Clear(obj);
485 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700486 return true;
487 }
488 return false;
489}
490
491inline bool MarkSweep::MarkObjectParallel(const Object* obj) {
492 DCHECK(obj != NULL);
493
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800494 if (kUseBrooksPointer) {
495 // Verify all the objects have the correct Brooks pointer installed.
496 obj->AssertSelfBrooksPointer();
497 }
498
Mathieu Chartier8d562102014-03-12 17:42:10 -0700499 if (immune_region_.ContainsObject(obj)) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700500 DCHECK(IsMarked(obj));
501 return false;
502 }
503
504 // Try to take advantage of locality of references within a space, failing this find the space
505 // the hard way.
Ian Rogers1d54e732013-05-02 21:10:01 -0700506 accounting::SpaceBitmap* object_bitmap = current_mark_bitmap_;
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700507 if (UNLIKELY(!object_bitmap->HasAddress(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700508 accounting::SpaceBitmap* new_bitmap = heap_->GetMarkBitmap()->GetContinuousSpaceBitmap(obj);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700509 if (new_bitmap != NULL) {
510 object_bitmap = new_bitmap;
511 } else {
512 // TODO: Remove the Thread::Current here?
513 // TODO: Convert this to some kind of atomic marking?
514 MutexLock mu(Thread::Current(), large_object_lock_);
Mathieu Chartier9642c962013-08-05 17:40:36 -0700515 return MarkLargeObject(obj, true);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700516 }
517 }
518
519 // Return true if the object was not previously marked.
520 return !object_bitmap->AtomicTestAndSet(obj);
521}
522
Carl Shapiro69759ea2011-07-21 18:13:35 -0700523// Used to mark objects when recursing. Recursion is done by moving
524// the finger across the bitmaps in address order and marking child
525// objects. Any newly-marked objects whose addresses are lower than
526// the finger won't be visited by the bitmap scan, so those objects
527// need to be added to the mark stack.
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700528inline void MarkSweep::MarkObject(const Object* obj) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700529 if (obj != NULL) {
Mathieu Chartier9642c962013-08-05 17:40:36 -0700530 MarkObjectNonNull(obj);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700531 }
532}
533
Mathieu Chartier815873e2014-02-13 18:02:13 -0800534void MarkSweep::MarkRootParallelCallback(mirror::Object** root, void* arg, uint32_t /*thread_id*/,
535 RootType /*root_type*/) {
Mathieu Chartier815873e2014-02-13 18:02:13 -0800536 reinterpret_cast<MarkSweep*>(arg)->MarkObjectNonNullParallel(*root);
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800537}
538
Mathieu Chartier893263b2014-03-04 11:07:42 -0800539void MarkSweep::VerifyRootMarked(Object** root, void* arg, uint32_t /*thread_id*/,
540 RootType /*root_type*/) {
541 CHECK(reinterpret_cast<MarkSweep*>(arg)->IsMarked(*root));
542}
543
Mathieu Chartier815873e2014-02-13 18:02:13 -0800544void MarkSweep::MarkRootCallback(Object** root, void* arg, uint32_t /*thread_id*/,
545 RootType /*root_type*/) {
Mathieu Chartier815873e2014-02-13 18:02:13 -0800546 reinterpret_cast<MarkSweep*>(arg)->MarkObjectNonNull(*root);
547}
548
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700549void MarkSweep::VerifyRootCallback(const Object* root, void* arg, size_t vreg,
Ian Rogers40e3bac2012-11-20 00:09:14 -0800550 const StackVisitor* visitor) {
551 reinterpret_cast<MarkSweep*>(arg)->VerifyRoot(root, vreg, visitor);
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700552}
553
Ian Rogers40e3bac2012-11-20 00:09:14 -0800554void MarkSweep::VerifyRoot(const Object* root, size_t vreg, const StackVisitor* visitor) {
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700555 // See if the root is on any space bitmap.
Ian Rogers1d54e732013-05-02 21:10:01 -0700556 if (GetHeap()->GetLiveBitmap()->GetContinuousSpaceBitmap(root) == NULL) {
557 space::LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
Mathieu Chartier4202b742012-10-17 17:51:25 -0700558 if (!large_object_space->Contains(root)) {
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700559 LOG(ERROR) << "Found invalid root: " << root;
Ian Rogers40e3bac2012-11-20 00:09:14 -0800560 if (visitor != NULL) {
561 LOG(ERROR) << visitor->DescribeLocation() << " in VReg: " << vreg;
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700562 }
563 }
564 }
565}
566
567void MarkSweep::VerifyRoots() {
568 Runtime::Current()->GetThreadList()->VerifyRoots(VerifyRootCallback, this);
569}
570
Mathieu Chartier893263b2014-03-04 11:07:42 -0800571void MarkSweep::MarkRoots(Thread* self) {
572 if (Locks::mutator_lock_->IsExclusiveHeld(self)) {
573 // If we exclusively hold the mutator lock, all threads must be suspended.
574 timings_.StartSplit("MarkRoots");
575 Runtime::Current()->VisitRoots(MarkRootCallback, this);
576 timings_.EndSplit();
577 RevokeAllThreadLocalAllocationStacks(self);
578 } else {
579 MarkThreadRoots(self);
580 // At this point the live stack should no longer have any mutators which push into it.
581 MarkNonThreadRoots();
582 MarkConcurrentRoots(
583 static_cast<VisitRootFlags>(kVisitRootFlagAllRoots | kVisitRootFlagStartLoggingNewRoots));
584 }
Mathieu Chartier9ebae1f2012-10-15 17:38:16 -0700585}
586
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700587void MarkSweep::MarkNonThreadRoots() {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700588 timings_.StartSplit("MarkNonThreadRoots");
Mathieu Chartier423d2a32013-09-12 17:33:56 -0700589 Runtime::Current()->VisitNonThreadRoots(MarkRootCallback, this);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700590 timings_.EndSplit();
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700591}
592
Mathieu Chartier893263b2014-03-04 11:07:42 -0800593void MarkSweep::MarkConcurrentRoots(VisitRootFlags flags) {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700594 timings_.StartSplit("MarkConcurrentRoots");
Ian Rogers1d54e732013-05-02 21:10:01 -0700595 // Visit all runtime roots and clear dirty flags.
Mathieu Chartier893263b2014-03-04 11:07:42 -0800596 Runtime::Current()->VisitConcurrentRoots(MarkRootCallback, this, flags);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700597 timings_.EndSplit();
Carl Shapiro69759ea2011-07-21 18:13:35 -0700598}
599
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700600class ScanObjectVisitor {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700601 public:
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700602 explicit ScanObjectVisitor(MarkSweep* const mark_sweep) ALWAYS_INLINE
603 : mark_sweep_(mark_sweep) {}
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700604
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800605 // TODO: Fixme when anotatalysis works with visitors.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700606 void operator()(Object* obj) const ALWAYS_INLINE NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700607 if (kCheckLocks) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800608 Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
609 Locks::heap_bitmap_lock_->AssertExclusiveHeld(Thread::Current());
610 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700611 mark_sweep_->ScanObject(obj);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700612 }
613
614 private:
615 MarkSweep* const mark_sweep_;
616};
617
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700618template <bool kUseFinger = false>
619class MarkStackTask : public Task {
620 public:
621 MarkStackTask(ThreadPool* thread_pool, MarkSweep* mark_sweep, size_t mark_stack_size,
622 const Object** mark_stack)
623 : mark_sweep_(mark_sweep),
624 thread_pool_(thread_pool),
625 mark_stack_pos_(mark_stack_size) {
626 // We may have to copy part of an existing mark stack when another mark stack overflows.
627 if (mark_stack_size != 0) {
628 DCHECK(mark_stack != NULL);
629 // TODO: Check performance?
630 std::copy(mark_stack, mark_stack + mark_stack_size, mark_stack_);
Ian Rogers1d54e732013-05-02 21:10:01 -0700631 }
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700632 if (kCountTasks) {
633 ++mark_sweep_->work_chunks_created_;
634 }
635 }
636
637 static const size_t kMaxSize = 1 * KB;
638
639 protected:
640 class ScanObjectParallelVisitor {
641 public:
642 explicit ScanObjectParallelVisitor(MarkStackTask<kUseFinger>* chunk_task) ALWAYS_INLINE
643 : chunk_task_(chunk_task) {}
644
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700645 void operator()(Object* obj) const {
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700646 MarkSweep* mark_sweep = chunk_task_->mark_sweep_;
647 mark_sweep->ScanObjectVisit(obj,
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700648 [mark_sweep, this](Object* /* obj */, Object* ref, const MemberOffset& /* offset */,
Bernhard Rosenkränzer46053622013-12-12 02:15:52 +0100649 bool /* is_static */) ALWAYS_INLINE_LAMBDA {
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700650 if (ref != nullptr && mark_sweep->MarkObjectParallel(ref)) {
651 if (kUseFinger) {
652 android_memory_barrier();
653 if (reinterpret_cast<uintptr_t>(ref) >=
654 static_cast<uintptr_t>(mark_sweep->atomic_finger_)) {
655 return;
656 }
657 }
658 chunk_task_->MarkStackPush(ref);
659 }
660 });
661 }
662
663 private:
664 MarkStackTask<kUseFinger>* const chunk_task_;
665 };
666
667 virtual ~MarkStackTask() {
668 // Make sure that we have cleared our mark stack.
669 DCHECK_EQ(mark_stack_pos_, 0U);
670 if (kCountTasks) {
671 ++mark_sweep_->work_chunks_deleted_;
672 }
673 }
674
675 MarkSweep* const mark_sweep_;
676 ThreadPool* const thread_pool_;
677 // Thread local mark stack for this task.
678 const Object* mark_stack_[kMaxSize];
679 // Mark stack position.
680 size_t mark_stack_pos_;
681
682 void MarkStackPush(const Object* obj) ALWAYS_INLINE {
683 if (UNLIKELY(mark_stack_pos_ == kMaxSize)) {
684 // Mark stack overflow, give 1/2 the stack to the thread pool as a new work task.
685 mark_stack_pos_ /= 2;
686 auto* task = new MarkStackTask(thread_pool_, mark_sweep_, kMaxSize - mark_stack_pos_,
687 mark_stack_ + mark_stack_pos_);
688 thread_pool_->AddTask(Thread::Current(), task);
689 }
690 DCHECK(obj != nullptr);
691 DCHECK(mark_stack_pos_ < kMaxSize);
692 mark_stack_[mark_stack_pos_++] = obj;
693 }
694
695 virtual void Finalize() {
696 delete this;
697 }
698
699 // Scans all of the objects
700 virtual void Run(Thread* self) {
701 ScanObjectParallelVisitor visitor(this);
702 // TODO: Tune this.
703 static const size_t kFifoSize = 4;
704 BoundedFifoPowerOfTwo<const Object*, kFifoSize> prefetch_fifo;
705 for (;;) {
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700706 const Object* obj = nullptr;
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700707 if (kUseMarkStackPrefetch) {
708 while (mark_stack_pos_ != 0 && prefetch_fifo.size() < kFifoSize) {
709 const Object* obj = mark_stack_[--mark_stack_pos_];
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700710 DCHECK(obj != nullptr);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700711 __builtin_prefetch(obj);
712 prefetch_fifo.push_back(obj);
713 }
714 if (UNLIKELY(prefetch_fifo.empty())) {
715 break;
716 }
717 obj = prefetch_fifo.front();
718 prefetch_fifo.pop_front();
719 } else {
720 if (UNLIKELY(mark_stack_pos_ == 0)) {
721 break;
722 }
723 obj = mark_stack_[--mark_stack_pos_];
724 }
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700725 DCHECK(obj != nullptr);
726 visitor(const_cast<mirror::Object*>(obj));
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700727 }
728 }
729};
730
731class CardScanTask : public MarkStackTask<false> {
732 public:
733 CardScanTask(ThreadPool* thread_pool, MarkSweep* mark_sweep, accounting::SpaceBitmap* bitmap,
734 byte* begin, byte* end, byte minimum_age, size_t mark_stack_size,
735 const Object** mark_stack_obj)
736 : MarkStackTask<false>(thread_pool, mark_sweep, mark_stack_size, mark_stack_obj),
737 bitmap_(bitmap),
738 begin_(begin),
739 end_(end),
740 minimum_age_(minimum_age) {
741 }
742
743 protected:
744 accounting::SpaceBitmap* const bitmap_;
745 byte* const begin_;
746 byte* const end_;
747 const byte minimum_age_;
748
749 virtual void Finalize() {
750 delete this;
751 }
752
753 virtual void Run(Thread* self) NO_THREAD_SAFETY_ANALYSIS {
754 ScanObjectParallelVisitor visitor(this);
755 accounting::CardTable* card_table = mark_sweep_->GetHeap()->GetCardTable();
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700756 size_t cards_scanned = card_table->Scan(bitmap_, begin_, end_, visitor, minimum_age_);
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700757 VLOG(heap) << "Parallel scanning cards " << reinterpret_cast<void*>(begin_) << " - "
758 << reinterpret_cast<void*>(end_) << " = " << cards_scanned;
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700759 // Finish by emptying our local mark stack.
760 MarkStackTask::Run(self);
761 }
762};
763
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700764size_t MarkSweep::GetThreadCount(bool paused) const {
765 if (heap_->GetThreadPool() == nullptr || !heap_->CareAboutPauseTimes()) {
766 return 0;
767 }
768 if (paused) {
769 return heap_->GetParallelGCThreadCount() + 1;
770 } else {
771 return heap_->GetConcGCThreadCount() + 1;
772 }
773}
774
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700775void MarkSweep::ScanGrayObjects(bool paused, byte minimum_age) {
776 accounting::CardTable* card_table = GetHeap()->GetCardTable();
777 ThreadPool* thread_pool = GetHeap()->GetThreadPool();
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700778 size_t thread_count = GetThreadCount(paused);
779 // The parallel version with only one thread is faster for card scanning, TODO: fix.
780 if (kParallelCardScan && thread_count > 0) {
Mathieu Chartier720ef762013-08-17 14:46:54 -0700781 Thread* self = Thread::Current();
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700782 // Can't have a different split for each space since multiple spaces can have their cards being
783 // scanned at the same time.
784 timings_.StartSplit(paused ? "(Paused)ScanGrayObjects" : "ScanGrayObjects");
785 // Try to take some of the mark stack since we can pass this off to the worker tasks.
786 const Object** mark_stack_begin = const_cast<const Object**>(mark_stack_->Begin());
787 const Object** mark_stack_end = const_cast<const Object**>(mark_stack_->End());
Mathieu Chartier720ef762013-08-17 14:46:54 -0700788 const size_t mark_stack_size = mark_stack_end - mark_stack_begin;
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700789 // Estimated number of work tasks we will create.
790 const size_t mark_stack_tasks = GetHeap()->GetContinuousSpaces().size() * thread_count;
791 DCHECK_NE(mark_stack_tasks, 0U);
792 const size_t mark_stack_delta = std::min(CardScanTask::kMaxSize / 2,
793 mark_stack_size / mark_stack_tasks + 1);
794 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700795 if (space->GetMarkBitmap() == nullptr) {
796 continue;
797 }
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700798 byte* card_begin = space->Begin();
799 byte* card_end = space->End();
Hiroshi Yamauchi0941b042013-11-05 11:34:03 -0800800 // Align up the end address. For example, the image space's end
801 // may not be card-size-aligned.
802 card_end = AlignUp(card_end, accounting::CardTable::kCardSize);
803 DCHECK(IsAligned<accounting::CardTable::kCardSize>(card_begin));
804 DCHECK(IsAligned<accounting::CardTable::kCardSize>(card_end));
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700805 // Calculate how many bytes of heap we will scan,
806 const size_t address_range = card_end - card_begin;
807 // Calculate how much address range each task gets.
808 const size_t card_delta = RoundUp(address_range / thread_count + 1,
809 accounting::CardTable::kCardSize);
810 // Create the worker tasks for this space.
811 while (card_begin != card_end) {
812 // Add a range of cards.
813 size_t addr_remaining = card_end - card_begin;
814 size_t card_increment = std::min(card_delta, addr_remaining);
815 // Take from the back of the mark stack.
816 size_t mark_stack_remaining = mark_stack_end - mark_stack_begin;
817 size_t mark_stack_increment = std::min(mark_stack_delta, mark_stack_remaining);
818 mark_stack_end -= mark_stack_increment;
819 mark_stack_->PopBackCount(static_cast<int32_t>(mark_stack_increment));
Ian Rogersb48b9eb2014-02-28 16:20:21 -0800820 DCHECK_EQ(mark_stack_end, const_cast<const art::mirror::Object **>(mark_stack_->End()));
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700821 // Add the new task to the thread pool.
822 auto* task = new CardScanTask(thread_pool, this, space->GetMarkBitmap(), card_begin,
823 card_begin + card_increment, minimum_age,
824 mark_stack_increment, mark_stack_end);
825 thread_pool->AddTask(self, task);
826 card_begin += card_increment;
827 }
828 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700829
Hiroshi Yamauchi0941b042013-11-05 11:34:03 -0800830 // Note: the card scan below may dirty new cards (and scan them)
831 // as a side effect when a Reference object is encountered and
832 // queued during the marking. See b/11465268.
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700833 thread_pool->SetMaxActiveWorkers(thread_count - 1);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700834 thread_pool->StartWorkers(self);
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700835 thread_pool->Wait(self, true, true);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700836 thread_pool->StopWorkers(self);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700837 timings_.EndSplit();
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700838 } else {
839 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700840 if (space->GetMarkBitmap() != nullptr) {
841 // Image spaces are handled properly since live == marked for them.
842 switch (space->GetGcRetentionPolicy()) {
843 case space::kGcRetentionPolicyNeverCollect:
844 timings_.StartSplit(paused ? "(Paused)ScanGrayImageSpaceObjects" :
845 "ScanGrayImageSpaceObjects");
846 break;
847 case space::kGcRetentionPolicyFullCollect:
848 timings_.StartSplit(paused ? "(Paused)ScanGrayZygoteSpaceObjects" :
849 "ScanGrayZygoteSpaceObjects");
850 break;
851 case space::kGcRetentionPolicyAlwaysCollect:
852 timings_.StartSplit(paused ? "(Paused)ScanGrayAllocSpaceObjects" :
853 "ScanGrayAllocSpaceObjects");
854 break;
855 }
856 ScanObjectVisitor visitor(this);
857 card_table->Scan(space->GetMarkBitmap(), space->Begin(), space->End(), visitor, minimum_age);
858 timings_.EndSplit();
859 }
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700860 }
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700861 }
862}
863
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700864class RecursiveMarkTask : public MarkStackTask<false> {
865 public:
866 RecursiveMarkTask(ThreadPool* thread_pool, MarkSweep* mark_sweep,
867 accounting::SpaceBitmap* bitmap, uintptr_t begin, uintptr_t end)
868 : MarkStackTask<false>(thread_pool, mark_sweep, 0, NULL),
869 bitmap_(bitmap),
870 begin_(begin),
871 end_(end) {
872 }
873
874 protected:
875 accounting::SpaceBitmap* const bitmap_;
876 const uintptr_t begin_;
877 const uintptr_t end_;
878
879 virtual void Finalize() {
880 delete this;
881 }
882
883 // Scans all of the objects
884 virtual void Run(Thread* self) NO_THREAD_SAFETY_ANALYSIS {
885 ScanObjectParallelVisitor visitor(this);
886 bitmap_->VisitMarkedRange(begin_, end_, visitor);
887 // Finish by emptying our local mark stack.
888 MarkStackTask::Run(self);
889 }
890};
891
Carl Shapiro58551df2011-07-24 03:09:51 -0700892// Populates the mark stack based on the set of marked objects and
893// recursively marks until the mark stack is emptied.
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800894void MarkSweep::RecursiveMark() {
Ian Rogers5fe9af72013-11-14 00:17:20 -0800895 TimingLogger::ScopedSplit split("RecursiveMark", &timings_);
Mathieu Chartiera1602f22014-01-13 17:19:19 -0800896 // RecursiveMark will build the lists of known instances of the Reference classes. See
897 // DelayReferenceReferent for details.
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700898 if (kUseRecursiveMark) {
899 const bool partial = GetGcType() == kGcTypePartial;
900 ScanObjectVisitor scan_visitor(this);
901 auto* self = Thread::Current();
902 ThreadPool* thread_pool = heap_->GetThreadPool();
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700903 size_t thread_count = GetThreadCount(false);
904 const bool parallel = kParallelRecursiveMark && thread_count > 1;
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700905 mark_stack_->Reset();
Mathieu Chartier02e25112013-08-14 16:14:24 -0700906 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700907 if ((space->GetGcRetentionPolicy() == space::kGcRetentionPolicyAlwaysCollect) ||
908 (!partial && space->GetGcRetentionPolicy() == space::kGcRetentionPolicyFullCollect)) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800909 current_mark_bitmap_ = space->GetMarkBitmap();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700910 if (current_mark_bitmap_ == nullptr) {
911 continue;
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800912 }
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700913 if (parallel) {
914 // We will use the mark stack the future.
915 // CHECK(mark_stack_->IsEmpty());
916 // This function does not handle heap end increasing, so we must use the space end.
917 uintptr_t begin = reinterpret_cast<uintptr_t>(space->Begin());
918 uintptr_t end = reinterpret_cast<uintptr_t>(space->End());
919 atomic_finger_ = static_cast<int32_t>(0xFFFFFFFF);
920
921 // Create a few worker tasks.
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700922 const size_t n = thread_count * 2;
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700923 while (begin != end) {
924 uintptr_t start = begin;
925 uintptr_t delta = (end - begin) / n;
926 delta = RoundUp(delta, KB);
927 if (delta < 16 * KB) delta = end - begin;
928 begin += delta;
929 auto* task = new RecursiveMarkTask(thread_pool, this, current_mark_bitmap_, start,
930 begin);
931 thread_pool->AddTask(self, task);
932 }
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700933 thread_pool->SetMaxActiveWorkers(thread_count - 1);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700934 thread_pool->StartWorkers(self);
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700935 thread_pool->Wait(self, true, true);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700936 thread_pool->StopWorkers(self);
937 } else {
938 // This function does not handle heap end increasing, so we must use the space end.
939 uintptr_t begin = reinterpret_cast<uintptr_t>(space->Begin());
940 uintptr_t end = reinterpret_cast<uintptr_t>(space->End());
941 current_mark_bitmap_->VisitMarkedRange(begin, end, scan_visitor);
942 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700943 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700944 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700945 }
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700946 ProcessMarkStack(false);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700947}
948
Mathieu Chartier83c8ee02014-01-28 14:50:23 -0800949mirror::Object* MarkSweep::IsMarkedCallback(mirror::Object* object, void* arg) {
Mathieu Chartier5712d5d2013-09-18 17:59:36 -0700950 if (reinterpret_cast<MarkSweep*>(arg)->IsMarked(object)) {
Mathieu Chartier6aa3df92013-09-17 15:17:28 -0700951 return object;
952 }
953 return nullptr;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700954}
955
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700956void MarkSweep::RecursiveMarkDirtyObjects(bool paused, byte minimum_age) {
957 ScanGrayObjects(paused, minimum_age);
958 ProcessMarkStack(paused);
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700959}
960
Carl Shapiro58551df2011-07-24 03:09:51 -0700961void MarkSweep::ReMarkRoots() {
Mathieu Chartier893263b2014-03-04 11:07:42 -0800962 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartier3bb57c72014-02-18 11:38:45 -0800963 timings_.StartSplit("(Paused)ReMarkRoots");
Mathieu Chartier893263b2014-03-04 11:07:42 -0800964 Runtime::Current()->VisitRoots(
965 MarkRootCallback, this, static_cast<VisitRootFlags>(kVisitRootFlagNewRoots |
966 kVisitRootFlagStopLoggingNewRoots |
967 kVisitRootFlagClearRootLog));
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700968 timings_.EndSplit();
Mathieu Chartier893263b2014-03-04 11:07:42 -0800969 if (kVerifyRoots) {
970 timings_.StartSplit("(Paused)VerifyRoots");
971 Runtime::Current()->VisitRoots(VerifyRootMarked, this);
972 timings_.EndSplit();
973 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700974}
975
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700976void MarkSweep::SweepSystemWeaks() {
977 Runtime* runtime = Runtime::Current();
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700978 timings_.StartSplit("SweepSystemWeaks");
Mathieu Chartier39e32612013-11-12 16:28:05 -0800979 runtime->SweepSystemWeaks(IsMarkedCallback, this);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700980 timings_.EndSplit();
Carl Shapiro58551df2011-07-24 03:09:51 -0700981}
982
Mathieu Chartier6aa3df92013-09-17 15:17:28 -0700983mirror::Object* MarkSweep::VerifySystemWeakIsLiveCallback(Object* obj, void* arg) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700984 reinterpret_cast<MarkSweep*>(arg)->VerifyIsLive(obj);
985 // We don't actually want to sweep the object, so lets return "marked"
Mathieu Chartier6aa3df92013-09-17 15:17:28 -0700986 return obj;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700987}
988
989void MarkSweep::VerifyIsLive(const Object* obj) {
990 Heap* heap = GetHeap();
991 if (!heap->GetLiveBitmap()->Test(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700992 space::LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700993 if (!large_object_space->GetLiveObjects()->Test(obj)) {
994 if (std::find(heap->allocation_stack_->Begin(), heap->allocation_stack_->End(), obj) ==
995 heap->allocation_stack_->End()) {
996 // Object not found!
997 heap->DumpSpaces();
998 LOG(FATAL) << "Found dead object " << obj;
999 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001000 }
1001 }
1002}
1003
1004void MarkSweep::VerifySystemWeaks() {
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001005 // Verify system weaks, uses a special object visitor which returns the input object.
1006 Runtime::Current()->SweepSystemWeaks(VerifySystemWeakIsLiveCallback, this);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001007}
1008
Mathieu Chartier0e4627e2012-10-23 16:13:36 -07001009class CheckpointMarkThreadRoots : public Closure {
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001010 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001011 explicit CheckpointMarkThreadRoots(MarkSweep* mark_sweep) : mark_sweep_(mark_sweep) {}
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001012
1013 virtual void Run(Thread* thread) NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier3f966702013-09-04 16:50:05 -07001014 ATRACE_BEGIN("Marking thread roots");
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001015 // Note: self is not necessarily equal to thread since thread may be suspended.
1016 Thread* self = Thread::Current();
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001017 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
1018 << thread->GetState() << " thread " << thread << " self " << self;
Mathieu Chartierac86a7c2012-11-12 15:03:16 -08001019 thread->VisitRoots(MarkSweep::MarkRootParallelCallback, mark_sweep_);
Mathieu Chartier3f966702013-09-04 16:50:05 -07001020 ATRACE_END();
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08001021 if (kUseThreadLocalAllocationStack) {
1022 thread->RevokeThreadLocalAllocationStack();
1023 }
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001024 mark_sweep_->GetBarrier().Pass(self);
1025 }
1026
1027 private:
1028 MarkSweep* mark_sweep_;
1029};
1030
Ian Rogers1d54e732013-05-02 21:10:01 -07001031void MarkSweep::MarkRootsCheckpoint(Thread* self) {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001032 CheckpointMarkThreadRoots check_point(this);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001033 timings_.StartSplit("MarkRootsCheckpoint");
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001034 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Ian Rogers1d54e732013-05-02 21:10:01 -07001035 // Request the check point is run on all threads returning a count of the threads that must
1036 // run through the barrier including self.
1037 size_t barrier_count = thread_list->RunCheckpoint(&check_point);
1038 // Release locks then wait for all mutator threads to pass the barrier.
1039 // TODO: optimize to not release locks when there are no threads to wait for.
1040 Locks::heap_bitmap_lock_->ExclusiveUnlock(self);
1041 Locks::mutator_lock_->SharedUnlock(self);
1042 ThreadState old_state = self->SetState(kWaitingForCheckPointsToRun);
1043 CHECK_EQ(old_state, kWaitingPerformingGc);
1044 gc_barrier_->Increment(self, barrier_count);
1045 self->SetState(kWaitingPerformingGc);
1046 Locks::mutator_lock_->SharedLock(self);
1047 Locks::heap_bitmap_lock_->ExclusiveLock(self);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001048 timings_.EndSplit();
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001049}
1050
Ian Rogers1d54e732013-05-02 21:10:01 -07001051void MarkSweep::SweepArray(accounting::ObjectStack* allocations, bool swap_bitmaps) {
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001052 timings_.StartSplit("SweepArray");
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001053 Thread* self = Thread::Current();
1054 mirror::Object* chunk_free_buffer[kSweepArrayChunkFreeSize];
1055 size_t chunk_free_pos = 0;
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001056 size_t freed_bytes = 0;
1057 size_t freed_large_object_bytes = 0;
Hiroshi Yamauchib22a4512013-08-13 15:03:22 -07001058 size_t freed_objects = 0;
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001059 size_t freed_large_objects = 0;
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001060 // How many objects are left in the array, modified after each space is swept.
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001061 Object** objects = const_cast<Object**>(allocations->Begin());
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001062 size_t count = allocations->Size();
1063 // Change the order to ensure that the non-moving space last swept as an optimization.
1064 std::vector<space::ContinuousSpace*> sweep_spaces;
1065 space::ContinuousSpace* non_moving_space = nullptr;
1066 for (space::ContinuousSpace* space : heap_->GetContinuousSpaces()) {
Mathieu Chartier8d562102014-03-12 17:42:10 -07001067 if (space->IsAllocSpace() && !immune_region_.ContainsSpace(space) &&
1068 space->GetLiveBitmap() != nullptr) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001069 if (space == heap_->GetNonMovingSpace()) {
1070 non_moving_space = space;
1071 } else {
1072 sweep_spaces.push_back(space);
1073 }
1074 }
1075 }
1076 // Unlikely to sweep a significant amount of non_movable objects, so we do these after the after
1077 // the other alloc spaces as an optimization.
1078 if (non_moving_space != nullptr) {
1079 sweep_spaces.push_back(non_moving_space);
1080 }
1081 // Start by sweeping the continuous spaces.
1082 for (space::ContinuousSpace* space : sweep_spaces) {
1083 space::AllocSpace* alloc_space = space->AsAllocSpace();
1084 accounting::SpaceBitmap* live_bitmap = space->GetLiveBitmap();
1085 accounting::SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
1086 if (swap_bitmaps) {
1087 std::swap(live_bitmap, mark_bitmap);
1088 }
1089 Object** out = objects;
1090 for (size_t i = 0; i < count; ++i) {
1091 Object* obj = objects[i];
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08001092 if (kUseThreadLocalAllocationStack && obj == nullptr) {
1093 continue;
1094 }
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001095 if (space->HasAddress(obj)) {
1096 // This object is in the space, remove it from the array and add it to the sweep buffer
1097 // if needed.
1098 if (!mark_bitmap->Test(obj)) {
1099 if (chunk_free_pos >= kSweepArrayChunkFreeSize) {
1100 timings_.StartSplit("FreeList");
1101 freed_objects += chunk_free_pos;
1102 freed_bytes += alloc_space->FreeList(self, chunk_free_pos, chunk_free_buffer);
1103 timings_.EndSplit();
1104 chunk_free_pos = 0;
1105 }
1106 chunk_free_buffer[chunk_free_pos++] = obj;
1107 }
1108 } else {
1109 *(out++) = obj;
1110 }
1111 }
1112 if (chunk_free_pos > 0) {
1113 timings_.StartSplit("FreeList");
1114 freed_objects += chunk_free_pos;
1115 freed_bytes += alloc_space->FreeList(self, chunk_free_pos, chunk_free_buffer);
1116 timings_.EndSplit();
1117 chunk_free_pos = 0;
1118 }
1119 // All of the references which space contained are no longer in the allocation stack, update
1120 // the count.
1121 count = out - objects;
1122 }
1123 // Handle the large object space.
1124 space::LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
Mathieu Chartierdb7f37d2014-01-10 11:09:06 -08001125 accounting::ObjectSet* large_live_objects = large_object_space->GetLiveObjects();
1126 accounting::ObjectSet* large_mark_objects = large_object_space->GetMarkObjects();
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001127 if (swap_bitmaps) {
1128 std::swap(large_live_objects, large_mark_objects);
1129 }
Brian Carlstrom02c8cc62013-07-18 15:54:44 -07001130 for (size_t i = 0; i < count; ++i) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001131 Object* obj = objects[i];
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001132 // Handle large objects.
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08001133 if (kUseThreadLocalAllocationStack && obj == nullptr) {
1134 continue;
1135 }
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001136 if (!large_mark_objects->Test(obj)) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001137 ++freed_large_objects;
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001138 freed_large_object_bytes += large_object_space->Free(self, obj);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001139 }
1140 }
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001141 timings_.EndSplit();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001142
Hiroshi Yamauchib22a4512013-08-13 15:03:22 -07001143 timings_.StartSplit("RecordFree");
Mathieu Chartier40e978b2012-09-07 11:38:36 -07001144 VLOG(heap) << "Freed " << freed_objects << "/" << count
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001145 << " objects with size " << PrettySize(freed_bytes);
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001146 heap_->RecordFree(freed_objects + freed_large_objects, freed_bytes + freed_large_object_bytes);
Ian Rogersb122a4b2013-11-19 18:00:50 -08001147 freed_objects_.FetchAndAdd(freed_objects);
1148 freed_large_objects_.FetchAndAdd(freed_large_objects);
1149 freed_bytes_.FetchAndAdd(freed_bytes);
1150 freed_large_object_bytes_.FetchAndAdd(freed_large_object_bytes);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001151 timings_.EndSplit();
Ian Rogers1d54e732013-05-02 21:10:01 -07001152
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001153 timings_.StartSplit("ResetStack");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001154 allocations->Reset();
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001155 timings_.EndSplit();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001156}
1157
Ian Rogers1d54e732013-05-02 21:10:01 -07001158void MarkSweep::Sweep(bool swap_bitmaps) {
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001159 DCHECK(mark_stack_->IsEmpty());
Ian Rogers5fe9af72013-11-14 00:17:20 -08001160 TimingLogger::ScopedSplit("Sweep", &timings_);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001161 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Mathieu Chartiera1602f22014-01-13 17:19:19 -08001162 if (space->IsContinuousMemMapAllocSpace()) {
1163 space::ContinuousMemMapAllocSpace* alloc_space = space->AsContinuousMemMapAllocSpace();
Mathieu Chartierec050072014-01-07 16:00:07 -08001164 TimingLogger::ScopedSplit split(
Mathieu Chartiera1602f22014-01-13 17:19:19 -08001165 alloc_space->IsZygoteSpace() ? "SweepZygoteSpace" : "SweepMallocSpace", &timings_);
Mathieu Chartierec050072014-01-07 16:00:07 -08001166 size_t freed_objects = 0;
1167 size_t freed_bytes = 0;
Mathieu Chartiera1602f22014-01-13 17:19:19 -08001168 alloc_space->Sweep(swap_bitmaps, &freed_objects, &freed_bytes);
Mathieu Chartierec050072014-01-07 16:00:07 -08001169 heap_->RecordFree(freed_objects, freed_bytes);
1170 freed_objects_.FetchAndAdd(freed_objects);
1171 freed_bytes_.FetchAndAdd(freed_bytes);
Carl Shapiro58551df2011-07-24 03:09:51 -07001172 }
1173 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001174 SweepLargeObjects(swap_bitmaps);
Carl Shapiro58551df2011-07-24 03:09:51 -07001175}
1176
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001177void MarkSweep::SweepLargeObjects(bool swap_bitmaps) {
Ian Rogers5fe9af72013-11-14 00:17:20 -08001178 TimingLogger::ScopedSplit("SweepLargeObjects", &timings_);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001179 size_t freed_objects = 0;
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001180 size_t freed_bytes = 0;
Mathieu Chartierdb7f37d2014-01-10 11:09:06 -08001181 GetHeap()->GetLargeObjectsSpace()->Sweep(swap_bitmaps, &freed_objects, &freed_bytes);
Ian Rogersb122a4b2013-11-19 18:00:50 -08001182 freed_large_objects_.FetchAndAdd(freed_objects);
1183 freed_large_object_bytes_.FetchAndAdd(freed_bytes);
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001184 GetHeap()->RecordFree(freed_objects, freed_bytes);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001185}
1186
Carl Shapiro69759ea2011-07-21 18:13:35 -07001187// Process the "referent" field in a java.lang.ref.Reference. If the
1188// referent has not yet been marked, put it on the appropriate list in
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001189// the heap for later processing.
1190void MarkSweep::DelayReferenceReferent(mirror::Class* klass, Object* obj) {
1191 DCHECK(klass != nullptr);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001192 DCHECK(klass->IsReferenceClass());
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001193 DCHECK(obj != NULL);
Mathieu Chartier39e32612013-11-12 16:28:05 -08001194 heap_->DelayReferenceReferent(klass, obj, IsMarkedCallback, this);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001195}
1196
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001197class MarkObjectVisitor {
1198 public:
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001199 explicit MarkObjectVisitor(MarkSweep* const mark_sweep) ALWAYS_INLINE : mark_sweep_(mark_sweep) {}
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001200
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001201 // TODO: Fixme when anotatalysis works with visitors.
Brian Carlstromdf629502013-07-17 22:39:56 -07001202 void operator()(const Object* /* obj */, const Object* ref, const MemberOffset& /* offset */,
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001203 bool /* is_static */) const ALWAYS_INLINE
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001204 NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001205 if (kCheckLocks) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001206 Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
1207 Locks::heap_bitmap_lock_->AssertExclusiveHeld(Thread::Current());
1208 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001209 mark_sweep_->MarkObject(ref);
1210 }
1211
1212 private:
1213 MarkSweep* const mark_sweep_;
1214};
1215
Carl Shapiro69759ea2011-07-21 18:13:35 -07001216// Scans an object reference. Determines the type of the reference
1217// and dispatches to a specialized scanning routine.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001218void MarkSweep::ScanObject(Object* obj) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001219 MarkObjectVisitor visitor(this);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001220 ScanObjectVisit(obj, visitor);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001221}
1222
Mathieu Chartier3bb57c72014-02-18 11:38:45 -08001223void MarkSweep::ProcessMarkStackPausedCallback(void* arg) {
1224 DCHECK(arg != nullptr);
1225 reinterpret_cast<MarkSweep*>(arg)->ProcessMarkStack(true);
1226}
1227
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001228void MarkSweep::ProcessMarkStackParallel(size_t thread_count) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001229 Thread* self = Thread::Current();
1230 ThreadPool* thread_pool = GetHeap()->GetThreadPool();
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001231 const size_t chunk_size = std::min(mark_stack_->Size() / thread_count + 1,
1232 static_cast<size_t>(MarkStackTask<false>::kMaxSize));
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001233 CHECK_GT(chunk_size, 0U);
1234 // Split the current mark stack up into work tasks.
1235 for (mirror::Object **it = mark_stack_->Begin(), **end = mark_stack_->End(); it < end; ) {
1236 const size_t delta = std::min(static_cast<size_t>(end - it), chunk_size);
1237 thread_pool->AddTask(self, new MarkStackTask<false>(thread_pool, this, delta,
1238 const_cast<const mirror::Object**>(it)));
1239 it += delta;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001240 }
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001241 thread_pool->SetMaxActiveWorkers(thread_count - 1);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001242 thread_pool->StartWorkers(self);
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001243 thread_pool->Wait(self, true, true);
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001244 thread_pool->StopWorkers(self);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001245 mark_stack_->Reset();
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001246 CHECK_EQ(work_chunks_created_, work_chunks_deleted_) << " some of the work chunks were leaked";
Carl Shapiro69759ea2011-07-21 18:13:35 -07001247}
1248
Ian Rogers5d76c432011-10-31 21:42:49 -07001249// Scan anything that's on the mark stack.
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001250void MarkSweep::ProcessMarkStack(bool paused) {
Mathieu Chartier3bb57c72014-02-18 11:38:45 -08001251 timings_.StartSplit(paused ? "(Paused)ProcessMarkStack" : "ProcessMarkStack");
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001252 size_t thread_count = GetThreadCount(paused);
1253 if (kParallelProcessMarkStack && thread_count > 1 &&
1254 mark_stack_->Size() >= kMinimumParallelMarkStackSize) {
1255 ProcessMarkStackParallel(thread_count);
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001256 } else {
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001257 // TODO: Tune this.
1258 static const size_t kFifoSize = 4;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001259 BoundedFifoPowerOfTwo<Object*, kFifoSize> prefetch_fifo;
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001260 for (;;) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001261 Object* obj = NULL;
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001262 if (kUseMarkStackPrefetch) {
1263 while (!mark_stack_->IsEmpty() && prefetch_fifo.size() < kFifoSize) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001264 Object* obj = mark_stack_->PopBack();
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001265 DCHECK(obj != NULL);
1266 __builtin_prefetch(obj);
1267 prefetch_fifo.push_back(obj);
1268 }
1269 if (prefetch_fifo.empty()) {
1270 break;
1271 }
1272 obj = prefetch_fifo.front();
1273 prefetch_fifo.pop_front();
1274 } else {
1275 if (mark_stack_->IsEmpty()) {
1276 break;
1277 }
1278 obj = mark_stack_->PopBack();
1279 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001280 DCHECK(obj != NULL);
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001281 ScanObject(obj);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001282 }
1283 }
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001284 timings_.EndSplit();
Carl Shapiro69759ea2011-07-21 18:13:35 -07001285}
1286
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001287inline bool MarkSweep::IsMarked(const Object* object) const
1288 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
Mathieu Chartier8d562102014-03-12 17:42:10 -07001289 if (immune_region_.ContainsObject(object)) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001290 return true;
1291 }
1292 DCHECK(current_mark_bitmap_ != NULL);
1293 if (current_mark_bitmap_->HasAddress(object)) {
1294 return current_mark_bitmap_->Test(object);
1295 }
1296 return heap_->GetMarkBitmap()->Test(object);
1297}
1298
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001299void MarkSweep::FinishPhase() {
Ian Rogers5fe9af72013-11-14 00:17:20 -08001300 TimingLogger::ScopedSplit split("FinishPhase", &timings_);
Anwar Ghuloum46543222013-08-12 09:28:42 -07001301 // Can't enqueue references if we hold the mutator lock.
Ian Rogers1d54e732013-05-02 21:10:01 -07001302 Heap* heap = GetHeap();
Anwar Ghuloum46543222013-08-12 09:28:42 -07001303 timings_.NewSplit("PostGcVerification");
Ian Rogers1d54e732013-05-02 21:10:01 -07001304 heap->PostGcVerification(this);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001305
1306 // Update the cumulative statistics
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001307 total_freed_objects_ += GetFreedObjects() + GetFreedLargeObjects();
1308 total_freed_bytes_ += GetFreedBytes() + GetFreedLargeObjectBytes();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001309
1310 // Ensure that the mark stack is empty.
1311 CHECK(mark_stack_->IsEmpty());
1312
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001313 if (kCountScannedTypes) {
1314 VLOG(gc) << "MarkSweep scanned classes=" << class_count_ << " arrays=" << array_count_
1315 << " other=" << other_count_;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001316 }
1317
1318 if (kCountTasks) {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001319 VLOG(gc) << "Total number of work chunks allocated: " << work_chunks_created_;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001320 }
1321
1322 if (kMeasureOverhead) {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001323 VLOG(gc) << "Overhead time " << PrettyDuration(overhead_time_);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001324 }
1325
1326 if (kProfileLargeObjects) {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001327 VLOG(gc) << "Large objects tested " << large_object_test_ << " marked " << large_object_mark_;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001328 }
1329
1330 if (kCountClassesMarked) {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001331 VLOG(gc) << "Classes marked " << classes_marked_;
1332 }
1333
1334 if (kCountJavaLangRefs) {
1335 VLOG(gc) << "References scanned " << reference_count_;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001336 }
1337
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001338 // Update the cumulative loggers.
1339 cumulative_timings_.Start();
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001340 cumulative_timings_.AddLogger(timings_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001341 cumulative_timings_.End();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001342
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001343 // Clear all of the spaces' mark bitmaps.
Mathieu Chartier02e25112013-08-14 16:14:24 -07001344 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001345 accounting::SpaceBitmap* bitmap = space->GetMarkBitmap();
1346 if (bitmap != nullptr &&
1347 space->GetGcRetentionPolicy() != space::kGcRetentionPolicyNeverCollect) {
1348 bitmap->Clear();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001349 }
1350 }
Mathieu Chartier5301cd22012-05-31 12:11:36 -07001351 mark_stack_->Reset();
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001352
1353 // Reset the marked large objects.
Ian Rogers1d54e732013-05-02 21:10:01 -07001354 space::LargeObjectSpace* large_objects = GetHeap()->GetLargeObjectsSpace();
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001355 large_objects->GetMarkObjects()->Clear();
Carl Shapiro69759ea2011-07-21 18:13:35 -07001356}
1357
Ian Rogers1d54e732013-05-02 21:10:01 -07001358} // namespace collector
1359} // namespace gc
Carl Shapiro69759ea2011-07-21 18:13:35 -07001360} // namespace art