blob: 61b3f09a4c92d58f82d2bd63945481a397a11f4e [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 Chartier94c32c52013-08-09 11:14:04 -070065constexpr bool kUseRecursiveMark = false;
66constexpr bool kUseMarkStackPrefetch = true;
67constexpr size_t kSweepArrayChunkFreeSize = 1024;
68
69// Parallelism options.
70constexpr bool kParallelCardScan = true;
71constexpr bool kParallelRecursiveMark = true;
72// Don't attempt to parallelize mark stack processing unless the mark stack is at least n
73// elements. This is temporary until we reduce the overhead caused by allocating tasks, etc.. Not
74// having this can add overhead in ProcessReferences since we may end up doing many calls of
75// ProcessMarkStack with very small mark stacks.
76constexpr size_t kMinimumParallelMarkStackSize = 128;
77constexpr bool kParallelProcessMarkStack = true;
Mathieu Chartier858f1c52012-10-17 17:45:55 -070078
Mathieu Chartier02b6a782012-10-26 13:51:26 -070079// Profiling and information flags.
Mathieu Chartier94c32c52013-08-09 11:14:04 -070080constexpr bool kCountClassesMarked = false;
81constexpr bool kProfileLargeObjects = false;
82constexpr bool kMeasureOverhead = false;
83constexpr bool kCountTasks = false;
84constexpr bool kCountJavaLangRefs = false;
85
86// Turn off kCheckLocks when profiling the GC since it slows the GC down by up to 40%.
87constexpr bool kCheckLocks = kDebugLocking;
Mathieu Chartier02b6a782012-10-26 13:51:26 -070088
Ian Rogers1d54e732013-05-02 21:10:01 -070089void MarkSweep::ImmuneSpace(space::ContinuousSpace* space) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -080090 // Bind live to mark bitmap if necessary.
91 if (space->GetLiveBitmap() != space->GetMarkBitmap()) {
92 BindLiveToMarkBitmap(space);
93 }
94
95 // Add the space to the immune region.
Mathieu Chartier590fee92013-09-13 13:46:47 -070096 // TODO: Use space limits instead of current end_ since the end_ can be changed by dlmalloc
97 // callbacks.
Mathieu Chartier2b82db42012-11-14 17:29:05 -080098 if (immune_begin_ == NULL) {
99 DCHECK(immune_end_ == NULL);
100 SetImmuneRange(reinterpret_cast<Object*>(space->Begin()),
101 reinterpret_cast<Object*>(space->End()));
102 } else {
Mathieu Chartier02e25112013-08-14 16:14:24 -0700103 const space::ContinuousSpace* prev_space = nullptr;
Ian Rogers1d54e732013-05-02 21:10:01 -0700104 // Find out if the previous space is immune.
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700105 for (const space::ContinuousSpace* cur_space : GetHeap()->GetContinuousSpaces()) {
Mathieu Chartier02e25112013-08-14 16:14:24 -0700106 if (cur_space == space) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700107 break;
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800108 }
Mathieu Chartier02e25112013-08-14 16:14:24 -0700109 prev_space = cur_space;
Ian Rogers1d54e732013-05-02 21:10:01 -0700110 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700111 // If previous space was immune, then extend the immune region. Relies on continuous spaces
112 // being sorted by Heap::AddContinuousSpace.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700113 if (prev_space != nullptr && IsImmuneSpace(prev_space)) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800114 immune_begin_ = std::min(reinterpret_cast<Object*>(space->Begin()), immune_begin_);
115 immune_end_ = std::max(reinterpret_cast<Object*>(space->End()), immune_end_);
116 }
117 }
118}
119
Mathieu Chartier590fee92013-09-13 13:46:47 -0700120bool MarkSweep::IsImmuneSpace(const space::ContinuousSpace* space) const {
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700121 return
122 immune_begin_ <= reinterpret_cast<Object*>(space->Begin()) &&
123 immune_end_ >= reinterpret_cast<Object*>(space->End());
124}
125
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800126void MarkSweep::BindBitmaps() {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700127 timings_.StartSplit("BindBitmaps");
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800128 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800129 // Mark all of the spaces we never collect as immune.
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700130 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700131 if (space->GetGcRetentionPolicy() == space::kGcRetentionPolicyNeverCollect) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800132 ImmuneSpace(space);
133 }
134 }
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700135 timings_.EndSplit();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800136}
137
Ian Rogers1d54e732013-05-02 21:10:01 -0700138MarkSweep::MarkSweep(Heap* heap, bool is_concurrent, const std::string& name_prefix)
139 : GarbageCollector(heap,
Mathieu Chartier590fee92013-09-13 13:46:47 -0700140 name_prefix +
Ian Rogers1d54e732013-05-02 21:10:01 -0700141 (is_concurrent ? "concurrent mark sweep": "mark sweep")),
142 current_mark_bitmap_(NULL),
Ian Rogers1d54e732013-05-02 21:10:01 -0700143 mark_stack_(NULL),
Ian Rogers1d54e732013-05-02 21:10:01 -0700144 immune_begin_(NULL),
145 immune_end_(NULL),
146 soft_reference_list_(NULL),
147 weak_reference_list_(NULL),
148 finalizer_reference_list_(NULL),
149 phantom_reference_list_(NULL),
150 cleared_reference_list_(NULL),
Ian Rogers906457c2013-11-13 23:28:08 -0800151 live_stack_freeze_size_(0),
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800152 gc_barrier_(new Barrier(0)),
Ian Rogers62d6c772013-02-27 08:32:07 -0800153 large_object_lock_("mark sweep large object lock", kMarkSweepLargeObjectLock),
Mathieu Chartier958291c2013-08-27 18:14:55 -0700154 mark_stack_lock_("mark sweep mark stack lock", kMarkSweepMarkStackLock),
Mathieu Chartier590fee92013-09-13 13:46:47 -0700155 is_concurrent_(is_concurrent) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800156}
157
158void MarkSweep::InitializePhase() {
Ian Rogers1d54e732013-05-02 21:10:01 -0700159 timings_.Reset();
Ian Rogers5fe9af72013-11-14 00:17:20 -0800160 TimingLogger::ScopedSplit split("InitializePhase", &timings_);
Mathieu Chartiere53225c2013-08-19 10:59:11 -0700161 mark_stack_ = heap_->mark_stack_.get();
162 DCHECK(mark_stack_ != nullptr);
163 SetImmuneRange(nullptr, nullptr);
164 soft_reference_list_ = nullptr;
165 weak_reference_list_ = nullptr;
166 finalizer_reference_list_ = nullptr;
167 phantom_reference_list_ = nullptr;
168 cleared_reference_list_ = nullptr;
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800169 class_count_ = 0;
170 array_count_ = 0;
171 other_count_ = 0;
172 large_object_test_ = 0;
173 large_object_mark_ = 0;
174 classes_marked_ = 0;
175 overhead_time_ = 0;
176 work_chunks_created_ = 0;
177 work_chunks_deleted_ = 0;
178 reference_count_ = 0;
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700179
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700180 FindDefaultMarkBitmap();
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700181
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700182 // Do any pre GC verification.
Anwar Ghuloum46543222013-08-12 09:28:42 -0700183 timings_.NewSplit("PreGcVerification");
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800184 heap_->PreGcVerification(this);
185}
186
187void MarkSweep::ProcessReferences(Thread* self) {
Ian Rogers5fe9af72013-11-14 00:17:20 -0800188 TimingLogger::ScopedSplit split("ProcessReferences", &timings_);
Mathieu Chartier8e56c7e2012-11-20 13:25:50 -0800189 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier39e32612013-11-12 16:28:05 -0800190 GetHeap()->ProcessReferences(timings_, clear_soft_references_, &IsMarkedCallback,
191 &RecursiveMarkObjectCallback, this);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800192}
193
194bool MarkSweep::HandleDirtyObjectsPhase() {
Ian Rogers5fe9af72013-11-14 00:17:20 -0800195 TimingLogger::ScopedSplit split("HandleDirtyObjectsPhase", &timings_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800196 Thread* self = Thread::Current();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800197 Locks::mutator_lock_->AssertExclusiveHeld(self);
198
199 {
200 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
201
202 // Re-mark root set.
203 ReMarkRoots();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800204
205 // Scan dirty objects, this is only required if we are not doing concurrent GC.
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700206 RecursiveMarkDirtyObjects(true, accounting::CardTable::kCardDirty);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800207 }
208
209 ProcessReferences(self);
210
211 // 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 -0700212 if (GetHeap()->verify_missing_card_marks_ || GetHeap()->verify_pre_gc_heap_||
213 GetHeap()->verify_post_gc_heap_) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800214 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
215 // This second sweep makes sure that we don't have any objects in the live stack which point to
216 // freed objects. These cause problems since their references may be previously freed objects.
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700217 SweepArray(GetHeap()->allocation_stack_.get(), false);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800218 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700219
220 timings_.StartSplit("PreSweepingGcVerification");
221 heap_->PreSweepingGcVerification(this);
222 timings_.EndSplit();
223
224 // Ensure that nobody inserted items in the live stack after we swapped the stacks.
225 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
226 CHECK_GE(live_stack_freeze_size_, GetHeap()->GetLiveStack()->Size());
Mathieu Chartierc11d9b82013-09-19 10:01:59 -0700227
228 // Disallow new system weaks to prevent a race which occurs when someone adds a new system
229 // weak before we sweep them. Since this new system weak may not be marked, the GC may
230 // incorrectly sweep it. This also fixes a race where interning may attempt to return a strong
231 // reference to a string that is about to be swept.
232 Runtime::Current()->DisallowNewSystemWeaks();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800233 return true;
234}
235
236bool MarkSweep::IsConcurrent() const {
237 return is_concurrent_;
238}
239
240void MarkSweep::MarkingPhase() {
Ian Rogers5fe9af72013-11-14 00:17:20 -0800241 TimingLogger::ScopedSplit split("MarkingPhase", &timings_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800242 Thread* self = Thread::Current();
243
244 BindBitmaps();
245 FindDefaultMarkBitmap();
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700246
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800247 // Process dirty cards and add dirty cards to mod union tables.
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700248 heap_->ProcessCards(timings_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800249
250 // Need to do this before the checkpoint since we don't want any threads to add references to
251 // the live stack during the recursive mark.
Anwar Ghuloum46543222013-08-12 09:28:42 -0700252 timings_.NewSplit("SwapStacks");
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700253 heap_->SwapStacks();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800254
255 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
256 if (Locks::mutator_lock_->IsExclusiveHeld(self)) {
257 // If we exclusively hold the mutator lock, all threads must be suspended.
258 MarkRoots();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800259 } else {
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700260 MarkThreadRoots(self);
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700261 // At this point the live stack should no longer have any mutators which push into it.
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800262 MarkNonThreadRoots();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800263 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700264 live_stack_freeze_size_ = heap_->GetLiveStack()->Size();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800265 MarkConcurrentRoots();
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700266 UpdateAndMarkModUnion();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800267 MarkReachableObjects();
268}
269
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700270void MarkSweep::UpdateAndMarkModUnion() {
271 for (const auto& space : heap_->GetContinuousSpaces()) {
272 if (IsImmuneSpace(space)) {
273 const char* name = space->IsZygoteSpace() ? "UpdateAndMarkZygoteModUnionTable" :
274 "UpdateAndMarkImageModUnionTable";
Ian Rogers5fe9af72013-11-14 00:17:20 -0800275 TimingLogger::ScopedSplit split(name, &timings_);
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700276 accounting::ModUnionTable* mod_union_table = heap_->FindModUnionTableFromSpace(space);
277 CHECK(mod_union_table != nullptr);
278 mod_union_table->UpdateAndMarkReferences(MarkRootCallback, this);
279 }
280 }
281}
282
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700283void MarkSweep::MarkThreadRoots(Thread* self) {
284 MarkRootsCheckpoint(self);
285}
286
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800287void MarkSweep::MarkReachableObjects() {
288 // Mark everything allocated since the last as GC live so that we can sweep concurrently,
289 // knowing that new allocations won't be marked as live.
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700290 timings_.StartSplit("MarkStackAsLive");
Ian Rogers1d54e732013-05-02 21:10:01 -0700291 accounting::ObjectStack* live_stack = heap_->GetLiveStack();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700292 heap_->MarkAllocStackAsLive(live_stack);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800293 live_stack->Reset();
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700294 timings_.EndSplit();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800295 // Recursively mark all the non-image bits set in the mark bitmap.
296 RecursiveMark();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800297}
298
299void MarkSweep::ReclaimPhase() {
Ian Rogers5fe9af72013-11-14 00:17:20 -0800300 TimingLogger::ScopedSplit split("ReclaimPhase", &timings_);
Mathieu Chartier720ef762013-08-17 14:46:54 -0700301 Thread* self = Thread::Current();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800302
303 if (!IsConcurrent()) {
304 ProcessReferences(self);
Mathieu Chartierc11d9b82013-09-19 10:01:59 -0700305 }
306
307 {
308 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
309 SweepSystemWeaks();
310 }
311
312 if (IsConcurrent()) {
313 Runtime::Current()->AllowNewSystemWeaks();
314
Ian Rogers5fe9af72013-11-14 00:17:20 -0800315 TimingLogger::ScopedSplit split("UnMarkAllocStack", &timings_);
Mathieu Chartier9642c962013-08-05 17:40:36 -0700316 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700317 accounting::ObjectStack* allocation_stack = GetHeap()->allocation_stack_.get();
Mathieu Chartier9642c962013-08-05 17:40:36 -0700318 // The allocation stack contains things allocated since the start of the GC. These may have been
319 // marked during this GC meaning they won't be eligible for reclaiming in the next sticky GC.
320 // Remove these objects from the mark bitmaps so that they will be eligible for sticky
321 // collection.
322 // There is a race here which is safely handled. Another thread such as the hprof could
323 // have flushed the alloc stack after we resumed the threads. This is safe however, since
324 // reseting the allocation stack zeros it out with madvise. This means that we will either
325 // read NULLs or attempt to unmark a newly allocated object which will not be marked in the
326 // first place.
327 mirror::Object** end = allocation_stack->End();
328 for (mirror::Object** it = allocation_stack->Begin(); it != end; ++it) {
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700329 const Object* obj = *it;
Mathieu Chartier9642c962013-08-05 17:40:36 -0700330 if (obj != NULL) {
331 UnMarkObjectNonNull(obj);
332 }
333 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800334 }
335
336 // Before freeing anything, lets verify the heap.
337 if (kIsDebugBuild) {
338 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
339 VerifyImageRoots();
340 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800341
342 {
343 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
344
345 // Reclaim unmarked objects.
Ian Rogers1d54e732013-05-02 21:10:01 -0700346 Sweep(false);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800347
348 // Swap the live and mark bitmaps for each space which we modified space. This is an
349 // optimization that enables us to not clear live bits inside of the sweep. Only swaps unbound
350 // bitmaps.
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700351 timings_.StartSplit("SwapBitmaps");
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800352 SwapBitmaps();
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700353 timings_.EndSplit();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800354
355 // Unbind the live and mark bitmaps.
356 UnBindBitmaps();
357 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800358}
359
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800360void MarkSweep::SetImmuneRange(Object* begin, Object* end) {
361 immune_begin_ = begin;
362 immune_end_ = end;
Carl Shapiro58551df2011-07-24 03:09:51 -0700363}
364
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700365void MarkSweep::FindDefaultMarkBitmap() {
Ian Rogers5fe9af72013-11-14 00:17:20 -0800366 TimingLogger::ScopedSplit split("FindDefaultMarkBitmap", &timings_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700367 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700368 accounting::SpaceBitmap* bitmap = space->GetMarkBitmap();
369 if (bitmap != nullptr &&
370 space->GetGcRetentionPolicy() == space::kGcRetentionPolicyAlwaysCollect) {
371 current_mark_bitmap_ = bitmap;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700372 CHECK(current_mark_bitmap_ != NULL);
373 return;
374 }
375 }
376 GetHeap()->DumpSpaces();
377 LOG(FATAL) << "Could not find a default mark bitmap";
378}
379
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800380void MarkSweep::ExpandMarkStack() {
Mathieu Chartierba311b42013-08-27 13:02:30 -0700381 ResizeMarkStack(mark_stack_->Capacity() * 2);
382}
383
384void MarkSweep::ResizeMarkStack(size_t new_size) {
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800385 // Rare case, no need to have Thread::Current be a parameter.
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800386 if (UNLIKELY(mark_stack_->Size() < mark_stack_->Capacity())) {
387 // Someone else acquired the lock and expanded the mark stack before us.
388 return;
389 }
Mathieu Chartier02e25112013-08-14 16:14:24 -0700390 std::vector<Object*> temp(mark_stack_->Begin(), mark_stack_->End());
Mathieu Chartierba311b42013-08-27 13:02:30 -0700391 CHECK_LE(mark_stack_->Size(), new_size);
392 mark_stack_->Resize(new_size);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700393 for (const auto& obj : temp) {
394 mark_stack_->PushBack(obj);
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800395 }
396}
397
Mathieu Chartier9642c962013-08-05 17:40:36 -0700398inline void MarkSweep::MarkObjectNonNullParallel(const Object* obj) {
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800399 DCHECK(obj != NULL);
400 if (MarkObjectParallel(obj)) {
Mathieu Chartierba311b42013-08-27 13:02:30 -0700401 MutexLock mu(Thread::Current(), mark_stack_lock_);
402 if (UNLIKELY(mark_stack_->Size() >= mark_stack_->Capacity())) {
Mathieu Chartier184e3222013-08-03 14:02:57 -0700403 ExpandMarkStack();
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800404 }
Mathieu Chartierba311b42013-08-27 13:02:30 -0700405 // The object must be pushed on to the mark stack.
406 mark_stack_->PushBack(const_cast<Object*>(obj));
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800407 }
408}
409
Mathieu Chartier39e32612013-11-12 16:28:05 -0800410mirror::Object* MarkSweep::RecursiveMarkObjectCallback(mirror::Object* obj, void* arg) {
411 MarkSweep* mark_sweep = reinterpret_cast<MarkSweep*>(arg);
412 mark_sweep->MarkObject(obj);
413 mark_sweep->ProcessMarkStack(true);
414 return obj;
415}
416
Mathieu Chartier9642c962013-08-05 17:40:36 -0700417inline void MarkSweep::UnMarkObjectNonNull(const Object* obj) {
418 DCHECK(!IsImmune(obj));
419 // Try to take advantage of locality of references within a space, failing this find the space
420 // the hard way.
421 accounting::SpaceBitmap* object_bitmap = current_mark_bitmap_;
422 if (UNLIKELY(!object_bitmap->HasAddress(obj))) {
423 accounting::SpaceBitmap* new_bitmap = heap_->GetMarkBitmap()->GetContinuousSpaceBitmap(obj);
424 if (LIKELY(new_bitmap != NULL)) {
425 object_bitmap = new_bitmap;
426 } else {
427 MarkLargeObject(obj, false);
428 return;
429 }
430 }
431
432 DCHECK(object_bitmap->HasAddress(obj));
433 object_bitmap->Clear(obj);
434}
435
436inline void MarkSweep::MarkObjectNonNull(const Object* obj) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700437 DCHECK(obj != NULL);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700438
Mathieu Chartier9642c962013-08-05 17:40:36 -0700439 if (IsImmune(obj)) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700440 DCHECK(IsMarked(obj));
Carl Shapiro69759ea2011-07-21 18:13:35 -0700441 return;
442 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700443
444 // Try to take advantage of locality of references within a space, failing this find the space
445 // the hard way.
Ian Rogers1d54e732013-05-02 21:10:01 -0700446 accounting::SpaceBitmap* object_bitmap = current_mark_bitmap_;
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700447 if (UNLIKELY(!object_bitmap->HasAddress(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700448 accounting::SpaceBitmap* new_bitmap = heap_->GetMarkBitmap()->GetContinuousSpaceBitmap(obj);
449 if (LIKELY(new_bitmap != NULL)) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700450 object_bitmap = new_bitmap;
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700451 } else {
Mathieu Chartier9642c962013-08-05 17:40:36 -0700452 MarkLargeObject(obj, true);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700453 return;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700454 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700455 }
456
Carl Shapiro69759ea2011-07-21 18:13:35 -0700457 // This object was not previously marked.
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700458 if (!object_bitmap->Test(obj)) {
459 object_bitmap->Set(obj);
Mathieu Chartier184e3222013-08-03 14:02:57 -0700460 if (UNLIKELY(mark_stack_->Size() >= mark_stack_->Capacity())) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700461 // Lock is not needed but is here anyways to please annotalysis.
462 MutexLock mu(Thread::Current(), mark_stack_lock_);
Mathieu Chartier184e3222013-08-03 14:02:57 -0700463 ExpandMarkStack();
Carl Shapiro69759ea2011-07-21 18:13:35 -0700464 }
Mathieu Chartier184e3222013-08-03 14:02:57 -0700465 // The object must be pushed on to the mark stack.
466 mark_stack_->PushBack(const_cast<Object*>(obj));
Carl Shapiro69759ea2011-07-21 18:13:35 -0700467 }
468}
469
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700470// Rare case, probably not worth inlining since it will increase instruction cache miss rate.
Mathieu Chartier9642c962013-08-05 17:40:36 -0700471bool MarkSweep::MarkLargeObject(const Object* obj, bool set) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700472 // TODO: support >1 discontinuous space.
473 space::LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
474 accounting::SpaceSetMap* large_objects = large_object_space->GetMarkObjects();
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700475 if (kProfileLargeObjects) {
476 ++large_object_test_;
477 }
478 if (UNLIKELY(!large_objects->Test(obj))) {
Mathieu Chartier4fcb8d32013-07-15 12:43:36 -0700479 if (!large_object_space->Contains(obj)) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700480 LOG(ERROR) << "Tried to mark " << obj << " not contained by any spaces";
481 LOG(ERROR) << "Attempting see if it's a bad root";
482 VerifyRoots();
483 LOG(FATAL) << "Can't mark bad root";
484 }
485 if (kProfileLargeObjects) {
486 ++large_object_mark_;
487 }
Mathieu Chartier9642c962013-08-05 17:40:36 -0700488 if (set) {
489 large_objects->Set(obj);
490 } else {
491 large_objects->Clear(obj);
492 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700493 return true;
494 }
495 return false;
496}
497
498inline bool MarkSweep::MarkObjectParallel(const Object* obj) {
499 DCHECK(obj != NULL);
500
Mathieu Chartier9642c962013-08-05 17:40:36 -0700501 if (IsImmune(obj)) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700502 DCHECK(IsMarked(obj));
503 return false;
504 }
505
506 // Try to take advantage of locality of references within a space, failing this find the space
507 // the hard way.
Ian Rogers1d54e732013-05-02 21:10:01 -0700508 accounting::SpaceBitmap* object_bitmap = current_mark_bitmap_;
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700509 if (UNLIKELY(!object_bitmap->HasAddress(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700510 accounting::SpaceBitmap* new_bitmap = heap_->GetMarkBitmap()->GetContinuousSpaceBitmap(obj);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700511 if (new_bitmap != NULL) {
512 object_bitmap = new_bitmap;
513 } else {
514 // TODO: Remove the Thread::Current here?
515 // TODO: Convert this to some kind of atomic marking?
516 MutexLock mu(Thread::Current(), large_object_lock_);
Mathieu Chartier9642c962013-08-05 17:40:36 -0700517 return MarkLargeObject(obj, true);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700518 }
519 }
520
521 // Return true if the object was not previously marked.
522 return !object_bitmap->AtomicTestAndSet(obj);
523}
524
Carl Shapiro69759ea2011-07-21 18:13:35 -0700525// Used to mark objects when recursing. Recursion is done by moving
526// the finger across the bitmaps in address order and marking child
527// objects. Any newly-marked objects whose addresses are lower than
528// the finger won't be visited by the bitmap scan, so those objects
529// need to be added to the mark stack.
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700530inline void MarkSweep::MarkObject(const Object* obj) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700531 if (obj != NULL) {
Mathieu Chartier9642c962013-08-05 17:40:36 -0700532 MarkObjectNonNull(obj);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700533 }
534}
535
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800536void MarkSweep::MarkRoot(const Object* obj) {
537 if (obj != NULL) {
Mathieu Chartier9642c962013-08-05 17:40:36 -0700538 MarkObjectNonNull(obj);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800539 }
540}
541
Mathieu Chartier423d2a32013-09-12 17:33:56 -0700542Object* MarkSweep::MarkRootParallelCallback(Object* root, void* arg) {
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800543 DCHECK(root != NULL);
544 DCHECK(arg != NULL);
Mathieu Chartierba311b42013-08-27 13:02:30 -0700545 reinterpret_cast<MarkSweep*>(arg)->MarkObjectNonNullParallel(root);
Mathieu Chartier423d2a32013-09-12 17:33:56 -0700546 return root;
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800547}
548
Mathieu Chartier423d2a32013-09-12 17:33:56 -0700549Object* MarkSweep::MarkRootCallback(Object* root, void* arg) {
550 DCHECK(root != nullptr);
551 DCHECK(arg != nullptr);
552 reinterpret_cast<MarkSweep*>(arg)->MarkObjectNonNull(root);
553 return root;
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700554}
555
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700556void MarkSweep::VerifyRootCallback(const Object* root, void* arg, size_t vreg,
Ian Rogers40e3bac2012-11-20 00:09:14 -0800557 const StackVisitor* visitor) {
558 reinterpret_cast<MarkSweep*>(arg)->VerifyRoot(root, vreg, visitor);
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700559}
560
Ian Rogers40e3bac2012-11-20 00:09:14 -0800561void MarkSweep::VerifyRoot(const Object* root, size_t vreg, const StackVisitor* visitor) {
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700562 // See if the root is on any space bitmap.
Ian Rogers1d54e732013-05-02 21:10:01 -0700563 if (GetHeap()->GetLiveBitmap()->GetContinuousSpaceBitmap(root) == NULL) {
564 space::LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
Mathieu Chartier4202b742012-10-17 17:51:25 -0700565 if (!large_object_space->Contains(root)) {
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700566 LOG(ERROR) << "Found invalid root: " << root;
Ian Rogers40e3bac2012-11-20 00:09:14 -0800567 if (visitor != NULL) {
568 LOG(ERROR) << visitor->DescribeLocation() << " in VReg: " << vreg;
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700569 }
570 }
571 }
572}
573
574void MarkSweep::VerifyRoots() {
575 Runtime::Current()->GetThreadList()->VerifyRoots(VerifyRootCallback, this);
576}
577
Carl Shapiro69759ea2011-07-21 18:13:35 -0700578// Marks all objects in the root set.
579void MarkSweep::MarkRoots() {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700580 timings_.StartSplit("MarkRoots");
Mathieu Chartier423d2a32013-09-12 17:33:56 -0700581 Runtime::Current()->VisitNonConcurrentRoots(MarkRootCallback, this);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700582 timings_.EndSplit();
Mathieu Chartier9ebae1f2012-10-15 17:38:16 -0700583}
584
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700585void MarkSweep::MarkNonThreadRoots() {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700586 timings_.StartSplit("MarkNonThreadRoots");
Mathieu Chartier423d2a32013-09-12 17:33:56 -0700587 Runtime::Current()->VisitNonThreadRoots(MarkRootCallback, this);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700588 timings_.EndSplit();
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700589}
590
Mathieu Chartier9ebae1f2012-10-15 17:38:16 -0700591void MarkSweep::MarkConcurrentRoots() {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700592 timings_.StartSplit("MarkConcurrentRoots");
Ian Rogers1d54e732013-05-02 21:10:01 -0700593 // Visit all runtime roots and clear dirty flags.
Mathieu Chartier423d2a32013-09-12 17:33:56 -0700594 Runtime::Current()->VisitConcurrentRoots(MarkRootCallback, this, false, true);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700595 timings_.EndSplit();
Carl Shapiro69759ea2011-07-21 18:13:35 -0700596}
597
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700598void MarkSweep::CheckObject(const Object* obj) {
599 DCHECK(obj != NULL);
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700600 VisitObjectReferences(const_cast<Object*>(obj), [this](const Object* obj, const Object* ref,
601 MemberOffset offset, bool is_static) NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700602 Locks::heap_bitmap_lock_->AssertSharedHeld(Thread::Current());
603 CheckReference(obj, ref, offset, is_static);
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700604 }, true);
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700605}
606
607void MarkSweep::VerifyImageRootVisitor(Object* root, void* arg) {
608 DCHECK(root != NULL);
609 DCHECK(arg != NULL);
610 MarkSweep* mark_sweep = reinterpret_cast<MarkSweep*>(arg);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700611 DCHECK(mark_sweep->heap_->GetMarkBitmap()->Test(root));
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700612 mark_sweep->CheckObject(root);
613}
614
Ian Rogers1d54e732013-05-02 21:10:01 -0700615void MarkSweep::BindLiveToMarkBitmap(space::ContinuousSpace* space) {
616 CHECK(space->IsDlMallocSpace());
617 space::DlMallocSpace* alloc_space = space->AsDlMallocSpace();
618 accounting::SpaceBitmap* live_bitmap = space->GetLiveBitmap();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700619 accounting::SpaceBitmap* mark_bitmap = alloc_space->BindLiveToMarkBitmap();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700620 GetHeap()->GetMarkBitmap()->ReplaceBitmap(mark_bitmap, live_bitmap);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700621}
622
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700623class ScanObjectVisitor {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700624 public:
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700625 explicit ScanObjectVisitor(MarkSweep* const mark_sweep) ALWAYS_INLINE
626 : mark_sweep_(mark_sweep) {}
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700627
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800628 // TODO: Fixme when anotatalysis works with visitors.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700629 void operator()(Object* obj) const ALWAYS_INLINE NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700630 if (kCheckLocks) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800631 Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
632 Locks::heap_bitmap_lock_->AssertExclusiveHeld(Thread::Current());
633 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700634 mark_sweep_->ScanObject(obj);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700635 }
636
637 private:
638 MarkSweep* const mark_sweep_;
639};
640
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700641template <bool kUseFinger = false>
642class MarkStackTask : public Task {
643 public:
644 MarkStackTask(ThreadPool* thread_pool, MarkSweep* mark_sweep, size_t mark_stack_size,
645 const Object** mark_stack)
646 : mark_sweep_(mark_sweep),
647 thread_pool_(thread_pool),
648 mark_stack_pos_(mark_stack_size) {
649 // We may have to copy part of an existing mark stack when another mark stack overflows.
650 if (mark_stack_size != 0) {
651 DCHECK(mark_stack != NULL);
652 // TODO: Check performance?
653 std::copy(mark_stack, mark_stack + mark_stack_size, mark_stack_);
Ian Rogers1d54e732013-05-02 21:10:01 -0700654 }
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700655 if (kCountTasks) {
656 ++mark_sweep_->work_chunks_created_;
657 }
658 }
659
660 static const size_t kMaxSize = 1 * KB;
661
662 protected:
663 class ScanObjectParallelVisitor {
664 public:
665 explicit ScanObjectParallelVisitor(MarkStackTask<kUseFinger>* chunk_task) ALWAYS_INLINE
666 : chunk_task_(chunk_task) {}
667
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700668 void operator()(Object* obj) const {
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700669 MarkSweep* mark_sweep = chunk_task_->mark_sweep_;
670 mark_sweep->ScanObjectVisit(obj,
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700671 [mark_sweep, this](Object* /* obj */, Object* ref, const MemberOffset& /* offset */,
672 bool /* is_static */) ALWAYS_INLINE {
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700673 if (ref != nullptr && mark_sweep->MarkObjectParallel(ref)) {
674 if (kUseFinger) {
675 android_memory_barrier();
676 if (reinterpret_cast<uintptr_t>(ref) >=
677 static_cast<uintptr_t>(mark_sweep->atomic_finger_)) {
678 return;
679 }
680 }
681 chunk_task_->MarkStackPush(ref);
682 }
683 });
684 }
685
686 private:
687 MarkStackTask<kUseFinger>* const chunk_task_;
688 };
689
690 virtual ~MarkStackTask() {
691 // Make sure that we have cleared our mark stack.
692 DCHECK_EQ(mark_stack_pos_, 0U);
693 if (kCountTasks) {
694 ++mark_sweep_->work_chunks_deleted_;
695 }
696 }
697
698 MarkSweep* const mark_sweep_;
699 ThreadPool* const thread_pool_;
700 // Thread local mark stack for this task.
701 const Object* mark_stack_[kMaxSize];
702 // Mark stack position.
703 size_t mark_stack_pos_;
704
705 void MarkStackPush(const Object* obj) ALWAYS_INLINE {
706 if (UNLIKELY(mark_stack_pos_ == kMaxSize)) {
707 // Mark stack overflow, give 1/2 the stack to the thread pool as a new work task.
708 mark_stack_pos_ /= 2;
709 auto* task = new MarkStackTask(thread_pool_, mark_sweep_, kMaxSize - mark_stack_pos_,
710 mark_stack_ + mark_stack_pos_);
711 thread_pool_->AddTask(Thread::Current(), task);
712 }
713 DCHECK(obj != nullptr);
714 DCHECK(mark_stack_pos_ < kMaxSize);
715 mark_stack_[mark_stack_pos_++] = obj;
716 }
717
718 virtual void Finalize() {
719 delete this;
720 }
721
722 // Scans all of the objects
723 virtual void Run(Thread* self) {
724 ScanObjectParallelVisitor visitor(this);
725 // TODO: Tune this.
726 static const size_t kFifoSize = 4;
727 BoundedFifoPowerOfTwo<const Object*, kFifoSize> prefetch_fifo;
728 for (;;) {
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700729 const Object* obj = nullptr;
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700730 if (kUseMarkStackPrefetch) {
731 while (mark_stack_pos_ != 0 && prefetch_fifo.size() < kFifoSize) {
732 const Object* obj = mark_stack_[--mark_stack_pos_];
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700733 DCHECK(obj != nullptr);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700734 __builtin_prefetch(obj);
735 prefetch_fifo.push_back(obj);
736 }
737 if (UNLIKELY(prefetch_fifo.empty())) {
738 break;
739 }
740 obj = prefetch_fifo.front();
741 prefetch_fifo.pop_front();
742 } else {
743 if (UNLIKELY(mark_stack_pos_ == 0)) {
744 break;
745 }
746 obj = mark_stack_[--mark_stack_pos_];
747 }
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700748 DCHECK(obj != nullptr);
749 visitor(const_cast<mirror::Object*>(obj));
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700750 }
751 }
752};
753
754class CardScanTask : public MarkStackTask<false> {
755 public:
756 CardScanTask(ThreadPool* thread_pool, MarkSweep* mark_sweep, accounting::SpaceBitmap* bitmap,
757 byte* begin, byte* end, byte minimum_age, size_t mark_stack_size,
758 const Object** mark_stack_obj)
759 : MarkStackTask<false>(thread_pool, mark_sweep, mark_stack_size, mark_stack_obj),
760 bitmap_(bitmap),
761 begin_(begin),
762 end_(end),
763 minimum_age_(minimum_age) {
764 }
765
766 protected:
767 accounting::SpaceBitmap* const bitmap_;
768 byte* const begin_;
769 byte* const end_;
770 const byte minimum_age_;
771
772 virtual void Finalize() {
773 delete this;
774 }
775
776 virtual void Run(Thread* self) NO_THREAD_SAFETY_ANALYSIS {
777 ScanObjectParallelVisitor visitor(this);
778 accounting::CardTable* card_table = mark_sweep_->GetHeap()->GetCardTable();
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700779 size_t cards_scanned = card_table->Scan(bitmap_, begin_, end_, visitor, minimum_age_);
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700780 VLOG(heap) << "Parallel scanning cards " << reinterpret_cast<void*>(begin_) << " - "
781 << reinterpret_cast<void*>(end_) << " = " << cards_scanned;
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700782 // Finish by emptying our local mark stack.
783 MarkStackTask::Run(self);
784 }
785};
786
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700787size_t MarkSweep::GetThreadCount(bool paused) const {
788 if (heap_->GetThreadPool() == nullptr || !heap_->CareAboutPauseTimes()) {
789 return 0;
790 }
791 if (paused) {
792 return heap_->GetParallelGCThreadCount() + 1;
793 } else {
794 return heap_->GetConcGCThreadCount() + 1;
795 }
796}
797
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700798void MarkSweep::ScanGrayObjects(bool paused, byte minimum_age) {
799 accounting::CardTable* card_table = GetHeap()->GetCardTable();
800 ThreadPool* thread_pool = GetHeap()->GetThreadPool();
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700801 size_t thread_count = GetThreadCount(paused);
802 // The parallel version with only one thread is faster for card scanning, TODO: fix.
803 if (kParallelCardScan && thread_count > 0) {
Mathieu Chartier720ef762013-08-17 14:46:54 -0700804 Thread* self = Thread::Current();
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700805 // Can't have a different split for each space since multiple spaces can have their cards being
806 // scanned at the same time.
807 timings_.StartSplit(paused ? "(Paused)ScanGrayObjects" : "ScanGrayObjects");
808 // Try to take some of the mark stack since we can pass this off to the worker tasks.
809 const Object** mark_stack_begin = const_cast<const Object**>(mark_stack_->Begin());
810 const Object** mark_stack_end = const_cast<const Object**>(mark_stack_->End());
Mathieu Chartier720ef762013-08-17 14:46:54 -0700811 const size_t mark_stack_size = mark_stack_end - mark_stack_begin;
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700812 // Estimated number of work tasks we will create.
813 const size_t mark_stack_tasks = GetHeap()->GetContinuousSpaces().size() * thread_count;
814 DCHECK_NE(mark_stack_tasks, 0U);
815 const size_t mark_stack_delta = std::min(CardScanTask::kMaxSize / 2,
816 mark_stack_size / mark_stack_tasks + 1);
817 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700818 if (space->GetMarkBitmap() == nullptr) {
819 continue;
820 }
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700821 byte* card_begin = space->Begin();
822 byte* card_end = space->End();
Hiroshi Yamauchi0941b042013-11-05 11:34:03 -0800823 // Align up the end address. For example, the image space's end
824 // may not be card-size-aligned.
825 card_end = AlignUp(card_end, accounting::CardTable::kCardSize);
826 DCHECK(IsAligned<accounting::CardTable::kCardSize>(card_begin));
827 DCHECK(IsAligned<accounting::CardTable::kCardSize>(card_end));
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700828 // Calculate how many bytes of heap we will scan,
829 const size_t address_range = card_end - card_begin;
830 // Calculate how much address range each task gets.
831 const size_t card_delta = RoundUp(address_range / thread_count + 1,
832 accounting::CardTable::kCardSize);
833 // Create the worker tasks for this space.
834 while (card_begin != card_end) {
835 // Add a range of cards.
836 size_t addr_remaining = card_end - card_begin;
837 size_t card_increment = std::min(card_delta, addr_remaining);
838 // Take from the back of the mark stack.
839 size_t mark_stack_remaining = mark_stack_end - mark_stack_begin;
840 size_t mark_stack_increment = std::min(mark_stack_delta, mark_stack_remaining);
841 mark_stack_end -= mark_stack_increment;
842 mark_stack_->PopBackCount(static_cast<int32_t>(mark_stack_increment));
843 DCHECK_EQ(mark_stack_end, mark_stack_->End());
844 // Add the new task to the thread pool.
845 auto* task = new CardScanTask(thread_pool, this, space->GetMarkBitmap(), card_begin,
846 card_begin + card_increment, minimum_age,
847 mark_stack_increment, mark_stack_end);
848 thread_pool->AddTask(self, task);
849 card_begin += card_increment;
850 }
851 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700852
Hiroshi Yamauchi0941b042013-11-05 11:34:03 -0800853 // Note: the card scan below may dirty new cards (and scan them)
854 // as a side effect when a Reference object is encountered and
855 // queued during the marking. See b/11465268.
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700856 thread_pool->SetMaxActiveWorkers(thread_count - 1);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700857 thread_pool->StartWorkers(self);
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700858 thread_pool->Wait(self, true, true);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700859 thread_pool->StopWorkers(self);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700860 timings_.EndSplit();
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700861 } else {
862 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700863 if (space->GetMarkBitmap() != nullptr) {
864 // Image spaces are handled properly since live == marked for them.
865 switch (space->GetGcRetentionPolicy()) {
866 case space::kGcRetentionPolicyNeverCollect:
867 timings_.StartSplit(paused ? "(Paused)ScanGrayImageSpaceObjects" :
868 "ScanGrayImageSpaceObjects");
869 break;
870 case space::kGcRetentionPolicyFullCollect:
871 timings_.StartSplit(paused ? "(Paused)ScanGrayZygoteSpaceObjects" :
872 "ScanGrayZygoteSpaceObjects");
873 break;
874 case space::kGcRetentionPolicyAlwaysCollect:
875 timings_.StartSplit(paused ? "(Paused)ScanGrayAllocSpaceObjects" :
876 "ScanGrayAllocSpaceObjects");
877 break;
878 }
879 ScanObjectVisitor visitor(this);
880 card_table->Scan(space->GetMarkBitmap(), space->Begin(), space->End(), visitor, minimum_age);
881 timings_.EndSplit();
882 }
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700883 }
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700884 }
885}
886
887void MarkSweep::VerifyImageRoots() {
888 // Verify roots ensures that all the references inside the image space point
889 // objects which are either in the image space or marked objects in the alloc
890 // space
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700891 timings_.StartSplit("VerifyImageRoots");
Mathieu Chartier02e25112013-08-14 16:14:24 -0700892 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
893 if (space->IsImageSpace()) {
894 space::ImageSpace* image_space = space->AsImageSpace();
895 uintptr_t begin = reinterpret_cast<uintptr_t>(image_space->Begin());
896 uintptr_t end = reinterpret_cast<uintptr_t>(image_space->End());
897 accounting::SpaceBitmap* live_bitmap = image_space->GetLiveBitmap();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700898 DCHECK(live_bitmap != NULL);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700899 live_bitmap->VisitMarkedRange(begin, end, [this](const Object* obj) {
900 if (kCheckLocks) {
901 Locks::heap_bitmap_lock_->AssertSharedHeld(Thread::Current());
902 }
903 DCHECK(obj != NULL);
904 CheckObject(obj);
905 });
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700906 }
907 }
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700908 timings_.EndSplit();
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700909}
910
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700911class RecursiveMarkTask : public MarkStackTask<false> {
912 public:
913 RecursiveMarkTask(ThreadPool* thread_pool, MarkSweep* mark_sweep,
914 accounting::SpaceBitmap* bitmap, uintptr_t begin, uintptr_t end)
915 : MarkStackTask<false>(thread_pool, mark_sweep, 0, NULL),
916 bitmap_(bitmap),
917 begin_(begin),
918 end_(end) {
919 }
920
921 protected:
922 accounting::SpaceBitmap* const bitmap_;
923 const uintptr_t begin_;
924 const uintptr_t end_;
925
926 virtual void Finalize() {
927 delete this;
928 }
929
930 // Scans all of the objects
931 virtual void Run(Thread* self) NO_THREAD_SAFETY_ANALYSIS {
932 ScanObjectParallelVisitor visitor(this);
933 bitmap_->VisitMarkedRange(begin_, end_, visitor);
934 // Finish by emptying our local mark stack.
935 MarkStackTask::Run(self);
936 }
937};
938
Carl Shapiro58551df2011-07-24 03:09:51 -0700939// Populates the mark stack based on the set of marked objects and
940// recursively marks until the mark stack is emptied.
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800941void MarkSweep::RecursiveMark() {
Ian Rogers5fe9af72013-11-14 00:17:20 -0800942 TimingLogger::ScopedSplit split("RecursiveMark", &timings_);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700943 // RecursiveMark will build the lists of known instances of the Reference classes.
944 // See DelayReferenceReferent for details.
945 CHECK(soft_reference_list_ == NULL);
946 CHECK(weak_reference_list_ == NULL);
947 CHECK(finalizer_reference_list_ == NULL);
948 CHECK(phantom_reference_list_ == NULL);
949 CHECK(cleared_reference_list_ == NULL);
950
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700951 if (kUseRecursiveMark) {
952 const bool partial = GetGcType() == kGcTypePartial;
953 ScanObjectVisitor scan_visitor(this);
954 auto* self = Thread::Current();
955 ThreadPool* thread_pool = heap_->GetThreadPool();
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700956 size_t thread_count = GetThreadCount(false);
957 const bool parallel = kParallelRecursiveMark && thread_count > 1;
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700958 mark_stack_->Reset();
Mathieu Chartier02e25112013-08-14 16:14:24 -0700959 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700960 if ((space->GetGcRetentionPolicy() == space::kGcRetentionPolicyAlwaysCollect) ||
961 (!partial && space->GetGcRetentionPolicy() == space::kGcRetentionPolicyFullCollect)) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800962 current_mark_bitmap_ = space->GetMarkBitmap();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700963 if (current_mark_bitmap_ == nullptr) {
964 continue;
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800965 }
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700966 if (parallel) {
967 // We will use the mark stack the future.
968 // CHECK(mark_stack_->IsEmpty());
969 // This function does not handle heap end increasing, so we must use the space end.
970 uintptr_t begin = reinterpret_cast<uintptr_t>(space->Begin());
971 uintptr_t end = reinterpret_cast<uintptr_t>(space->End());
972 atomic_finger_ = static_cast<int32_t>(0xFFFFFFFF);
973
974 // Create a few worker tasks.
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700975 const size_t n = thread_count * 2;
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700976 while (begin != end) {
977 uintptr_t start = begin;
978 uintptr_t delta = (end - begin) / n;
979 delta = RoundUp(delta, KB);
980 if (delta < 16 * KB) delta = end - begin;
981 begin += delta;
982 auto* task = new RecursiveMarkTask(thread_pool, this, current_mark_bitmap_, start,
983 begin);
984 thread_pool->AddTask(self, task);
985 }
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700986 thread_pool->SetMaxActiveWorkers(thread_count - 1);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700987 thread_pool->StartWorkers(self);
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700988 thread_pool->Wait(self, true, true);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700989 thread_pool->StopWorkers(self);
990 } else {
991 // This function does not handle heap end increasing, so we must use the space end.
992 uintptr_t begin = reinterpret_cast<uintptr_t>(space->Begin());
993 uintptr_t end = reinterpret_cast<uintptr_t>(space->End());
994 current_mark_bitmap_->VisitMarkedRange(begin, end, scan_visitor);
995 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700996 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700997 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700998 }
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700999 ProcessMarkStack(false);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001000}
1001
Mathieu Chartier39e32612013-11-12 16:28:05 -08001002mirror::Object* MarkSweep::IsMarkedCallback(Object* object, void* arg) {
Mathieu Chartier5712d5d2013-09-18 17:59:36 -07001003 if (reinterpret_cast<MarkSweep*>(arg)->IsMarked(object)) {
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001004 return object;
1005 }
1006 return nullptr;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001007}
1008
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001009void MarkSweep::RecursiveMarkDirtyObjects(bool paused, byte minimum_age) {
1010 ScanGrayObjects(paused, minimum_age);
1011 ProcessMarkStack(paused);
Mathieu Chartier262e5ff2012-06-01 17:35:38 -07001012}
1013
Carl Shapiro58551df2011-07-24 03:09:51 -07001014void MarkSweep::ReMarkRoots() {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001015 timings_.StartSplit("ReMarkRoots");
Mathieu Chartier423d2a32013-09-12 17:33:56 -07001016 Runtime::Current()->VisitRoots(MarkRootCallback, this, true, true);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001017 timings_.EndSplit();
Carl Shapiro69759ea2011-07-21 18:13:35 -07001018}
1019
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001020void MarkSweep::SweepSystemWeaks() {
1021 Runtime* runtime = Runtime::Current();
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001022 timings_.StartSplit("SweepSystemWeaks");
Mathieu Chartier39e32612013-11-12 16:28:05 -08001023 runtime->SweepSystemWeaks(IsMarkedCallback, this);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001024 timings_.EndSplit();
Carl Shapiro58551df2011-07-24 03:09:51 -07001025}
1026
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001027mirror::Object* MarkSweep::VerifySystemWeakIsLiveCallback(Object* obj, void* arg) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001028 reinterpret_cast<MarkSweep*>(arg)->VerifyIsLive(obj);
1029 // We don't actually want to sweep the object, so lets return "marked"
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001030 return obj;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001031}
1032
1033void MarkSweep::VerifyIsLive(const Object* obj) {
1034 Heap* heap = GetHeap();
1035 if (!heap->GetLiveBitmap()->Test(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001036 space::LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001037 if (!large_object_space->GetLiveObjects()->Test(obj)) {
1038 if (std::find(heap->allocation_stack_->Begin(), heap->allocation_stack_->End(), obj) ==
1039 heap->allocation_stack_->End()) {
1040 // Object not found!
1041 heap->DumpSpaces();
1042 LOG(FATAL) << "Found dead object " << obj;
1043 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001044 }
1045 }
1046}
1047
1048void MarkSweep::VerifySystemWeaks() {
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001049 // Verify system weaks, uses a special object visitor which returns the input object.
1050 Runtime::Current()->SweepSystemWeaks(VerifySystemWeakIsLiveCallback, this);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001051}
1052
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001053struct SweepCallbackContext {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001054 MarkSweep* mark_sweep;
Ian Rogers1d54e732013-05-02 21:10:01 -07001055 space::AllocSpace* space;
Ian Rogers50b35e22012-10-04 10:09:15 -07001056 Thread* self;
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001057};
1058
Mathieu Chartier0e4627e2012-10-23 16:13:36 -07001059class CheckpointMarkThreadRoots : public Closure {
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001060 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001061 explicit CheckpointMarkThreadRoots(MarkSweep* mark_sweep) : mark_sweep_(mark_sweep) {}
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001062
1063 virtual void Run(Thread* thread) NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier3f966702013-09-04 16:50:05 -07001064 ATRACE_BEGIN("Marking thread roots");
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001065 // Note: self is not necessarily equal to thread since thread may be suspended.
1066 Thread* self = Thread::Current();
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001067 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
1068 << thread->GetState() << " thread " << thread << " self " << self;
Mathieu Chartierac86a7c2012-11-12 15:03:16 -08001069 thread->VisitRoots(MarkSweep::MarkRootParallelCallback, mark_sweep_);
Mathieu Chartier3f966702013-09-04 16:50:05 -07001070 ATRACE_END();
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001071 mark_sweep_->GetBarrier().Pass(self);
1072 }
1073
1074 private:
1075 MarkSweep* mark_sweep_;
1076};
1077
Ian Rogers1d54e732013-05-02 21:10:01 -07001078void MarkSweep::MarkRootsCheckpoint(Thread* self) {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001079 CheckpointMarkThreadRoots check_point(this);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001080 timings_.StartSplit("MarkRootsCheckpoint");
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001081 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Ian Rogers1d54e732013-05-02 21:10:01 -07001082 // Request the check point is run on all threads returning a count of the threads that must
1083 // run through the barrier including self.
1084 size_t barrier_count = thread_list->RunCheckpoint(&check_point);
1085 // Release locks then wait for all mutator threads to pass the barrier.
1086 // TODO: optimize to not release locks when there are no threads to wait for.
1087 Locks::heap_bitmap_lock_->ExclusiveUnlock(self);
1088 Locks::mutator_lock_->SharedUnlock(self);
1089 ThreadState old_state = self->SetState(kWaitingForCheckPointsToRun);
1090 CHECK_EQ(old_state, kWaitingPerformingGc);
1091 gc_barrier_->Increment(self, barrier_count);
1092 self->SetState(kWaitingPerformingGc);
1093 Locks::mutator_lock_->SharedLock(self);
1094 Locks::heap_bitmap_lock_->ExclusiveLock(self);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001095 timings_.EndSplit();
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001096}
1097
Ian Rogers30fab402012-01-23 15:43:46 -08001098void MarkSweep::SweepCallback(size_t num_ptrs, Object** ptrs, void* arg) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001099 SweepCallbackContext* context = static_cast<SweepCallbackContext*>(arg);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001100 MarkSweep* mark_sweep = context->mark_sweep;
1101 Heap* heap = mark_sweep->GetHeap();
Ian Rogers1d54e732013-05-02 21:10:01 -07001102 space::AllocSpace* space = context->space;
Ian Rogers50b35e22012-10-04 10:09:15 -07001103 Thread* self = context->self;
1104 Locks::heap_bitmap_lock_->AssertExclusiveHeld(self);
Ian Rogers5d76c432011-10-31 21:42:49 -07001105 // Use a bulk free, that merges consecutive objects before freeing or free per object?
1106 // Documentation suggests better free performance with merging, but this may be at the expensive
1107 // of allocation.
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001108 size_t freed_objects = num_ptrs;
1109 // AllocSpace::FreeList clears the value in ptrs, so perform after clearing the live bit
1110 size_t freed_bytes = space->FreeList(self, num_ptrs, ptrs);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001111 heap->RecordFree(freed_objects, freed_bytes);
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -07001112 mark_sweep->freed_objects_.fetch_add(freed_objects);
1113 mark_sweep->freed_bytes_.fetch_add(freed_bytes);
Carl Shapiro58551df2011-07-24 03:09:51 -07001114}
1115
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001116void MarkSweep::ZygoteSweepCallback(size_t num_ptrs, Object** ptrs, void* arg) {
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001117 SweepCallbackContext* context = static_cast<SweepCallbackContext*>(arg);
Ian Rogers50b35e22012-10-04 10:09:15 -07001118 Locks::heap_bitmap_lock_->AssertExclusiveHeld(context->self);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001119 Heap* heap = context->mark_sweep->GetHeap();
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001120 // We don't free any actual memory to avoid dirtying the shared zygote pages.
1121 for (size_t i = 0; i < num_ptrs; ++i) {
1122 Object* obj = static_cast<Object*>(ptrs[i]);
1123 heap->GetLiveBitmap()->Clear(obj);
1124 heap->GetCardTable()->MarkCard(obj);
1125 }
1126}
1127
Ian Rogers1d54e732013-05-02 21:10:01 -07001128void MarkSweep::SweepArray(accounting::ObjectStack* allocations, bool swap_bitmaps) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001129 space::DlMallocSpace* space = heap_->GetNonMovingSpace();
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001130 timings_.StartSplit("SweepArray");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001131 // Newly allocated objects MUST be in the alloc space and those are the only objects which we are
1132 // going to free.
Ian Rogers1d54e732013-05-02 21:10:01 -07001133 accounting::SpaceBitmap* live_bitmap = space->GetLiveBitmap();
1134 accounting::SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
1135 space::LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
1136 accounting::SpaceSetMap* large_live_objects = large_object_space->GetLiveObjects();
1137 accounting::SpaceSetMap* large_mark_objects = large_object_space->GetMarkObjects();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001138 if (swap_bitmaps) {
1139 std::swap(live_bitmap, mark_bitmap);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001140 std::swap(large_live_objects, large_mark_objects);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001141 }
1142
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001143 size_t freed_bytes = 0;
1144 size_t freed_large_object_bytes = 0;
Hiroshi Yamauchib22a4512013-08-13 15:03:22 -07001145 size_t freed_objects = 0;
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001146 size_t freed_large_objects = 0;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001147 size_t count = allocations->Size();
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001148 Object** objects = const_cast<Object**>(allocations->Begin());
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001149 Object** out = objects;
Hiroshi Yamauchib22a4512013-08-13 15:03:22 -07001150 Object** objects_to_chunk_free = out;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001151
1152 // Empty the allocation stack.
Ian Rogers50b35e22012-10-04 10:09:15 -07001153 Thread* self = Thread::Current();
Brian Carlstrom02c8cc62013-07-18 15:54:44 -07001154 for (size_t i = 0; i < count; ++i) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001155 Object* obj = objects[i];
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001156 // There should only be objects in the AllocSpace/LargeObjectSpace in the allocation stack.
1157 if (LIKELY(mark_bitmap->HasAddress(obj))) {
1158 if (!mark_bitmap->Test(obj)) {
1159 // Don't bother un-marking since we clear the mark bitmap anyways.
1160 *(out++) = obj;
Hiroshi Yamauchib22a4512013-08-13 15:03:22 -07001161 // Free objects in chunks.
1162 DCHECK_GE(out, objects_to_chunk_free);
1163 DCHECK_LE(static_cast<size_t>(out - objects_to_chunk_free), kSweepArrayChunkFreeSize);
1164 if (static_cast<size_t>(out - objects_to_chunk_free) == kSweepArrayChunkFreeSize) {
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001165 timings_.StartSplit("FreeList");
Hiroshi Yamauchib22a4512013-08-13 15:03:22 -07001166 size_t chunk_freed_objects = out - objects_to_chunk_free;
1167 freed_objects += chunk_freed_objects;
1168 freed_bytes += space->FreeList(self, chunk_freed_objects, objects_to_chunk_free);
1169 objects_to_chunk_free = out;
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001170 timings_.EndSplit();
Hiroshi Yamauchib22a4512013-08-13 15:03:22 -07001171 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001172 }
1173 } else if (!large_mark_objects->Test(obj)) {
1174 ++freed_large_objects;
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001175 freed_large_object_bytes += large_object_space->Free(self, obj);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001176 }
1177 }
Hiroshi Yamauchib22a4512013-08-13 15:03:22 -07001178 // Free the remaining objects in chunks.
1179 DCHECK_GE(out, objects_to_chunk_free);
1180 DCHECK_LE(static_cast<size_t>(out - objects_to_chunk_free), kSweepArrayChunkFreeSize);
1181 if (out - objects_to_chunk_free > 0) {
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001182 timings_.StartSplit("FreeList");
Hiroshi Yamauchib22a4512013-08-13 15:03:22 -07001183 size_t chunk_freed_objects = out - objects_to_chunk_free;
1184 freed_objects += chunk_freed_objects;
1185 freed_bytes += space->FreeList(self, chunk_freed_objects, objects_to_chunk_free);
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001186 timings_.EndSplit();
Hiroshi Yamauchib22a4512013-08-13 15:03:22 -07001187 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001188 CHECK_EQ(count, allocations->Size());
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001189 timings_.EndSplit();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001190
Hiroshi Yamauchib22a4512013-08-13 15:03:22 -07001191 timings_.StartSplit("RecordFree");
Mathieu Chartier40e978b2012-09-07 11:38:36 -07001192 VLOG(heap) << "Freed " << freed_objects << "/" << count
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001193 << " objects with size " << PrettySize(freed_bytes);
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001194 heap_->RecordFree(freed_objects + freed_large_objects, freed_bytes + freed_large_object_bytes);
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -07001195 freed_objects_.fetch_add(freed_objects);
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001196 freed_large_objects_.fetch_add(freed_large_objects);
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -07001197 freed_bytes_.fetch_add(freed_bytes);
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001198 freed_large_object_bytes_.fetch_add(freed_large_object_bytes);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001199 timings_.EndSplit();
Ian Rogers1d54e732013-05-02 21:10:01 -07001200
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001201 timings_.StartSplit("ResetStack");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001202 allocations->Reset();
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001203 timings_.EndSplit();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001204}
1205
Ian Rogers1d54e732013-05-02 21:10:01 -07001206void MarkSweep::Sweep(bool swap_bitmaps) {
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001207 DCHECK(mark_stack_->IsEmpty());
Ian Rogers5fe9af72013-11-14 00:17:20 -08001208 TimingLogger::ScopedSplit("Sweep", &timings_);
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001209
Ian Rogers1d54e732013-05-02 21:10:01 -07001210 const bool partial = (GetGcType() == kGcTypePartial);
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001211 SweepCallbackContext scc;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001212 scc.mark_sweep = this;
Ian Rogers50b35e22012-10-04 10:09:15 -07001213 scc.self = Thread::Current();
Mathieu Chartier02e25112013-08-14 16:14:24 -07001214 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001215 if (!space->IsDlMallocSpace()) {
1216 continue;
1217 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001218 // We always sweep always collect spaces.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001219 bool sweep_space = space->GetGcRetentionPolicy() == space::kGcRetentionPolicyAlwaysCollect;
Ian Rogers1d54e732013-05-02 21:10:01 -07001220 if (!partial && !sweep_space) {
1221 // We sweep full collect spaces when the GC isn't a partial GC (ie its full).
1222 sweep_space = (space->GetGcRetentionPolicy() == space::kGcRetentionPolicyFullCollect);
1223 }
1224 if (sweep_space) {
Mathieu Chartier720ef762013-08-17 14:46:54 -07001225 uintptr_t begin = reinterpret_cast<uintptr_t>(space->Begin());
1226 uintptr_t end = reinterpret_cast<uintptr_t>(space->End());
Ian Rogers1d54e732013-05-02 21:10:01 -07001227 scc.space = space->AsDlMallocSpace();
1228 accounting::SpaceBitmap* live_bitmap = space->GetLiveBitmap();
1229 accounting::SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001230 if (swap_bitmaps) {
1231 std::swap(live_bitmap, mark_bitmap);
1232 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001233 if (!space->IsZygoteSpace()) {
Ian Rogers5fe9af72013-11-14 00:17:20 -08001234 TimingLogger::ScopedSplit split("SweepAllocSpace", &timings_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001235 // Bitmaps are pre-swapped for optimization which enables sweeping with the heap unlocked.
Ian Rogers1d54e732013-05-02 21:10:01 -07001236 accounting::SpaceBitmap::SweepWalk(*live_bitmap, *mark_bitmap, begin, end,
1237 &SweepCallback, reinterpret_cast<void*>(&scc));
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001238 } else {
Ian Rogers5fe9af72013-11-14 00:17:20 -08001239 TimingLogger::ScopedSplit split("SweepZygote", &timings_);
Ian Rogers1d54e732013-05-02 21:10:01 -07001240 // Zygote sweep takes care of dirtying cards and clearing live bits, does not free actual
1241 // memory.
1242 accounting::SpaceBitmap::SweepWalk(*live_bitmap, *mark_bitmap, begin, end,
1243 &ZygoteSweepCallback, reinterpret_cast<void*>(&scc));
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001244 }
Carl Shapiro58551df2011-07-24 03:09:51 -07001245 }
1246 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001247
1248 SweepLargeObjects(swap_bitmaps);
Carl Shapiro58551df2011-07-24 03:09:51 -07001249}
1250
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001251void MarkSweep::SweepLargeObjects(bool swap_bitmaps) {
Ian Rogers5fe9af72013-11-14 00:17:20 -08001252 TimingLogger::ScopedSplit("SweepLargeObjects", &timings_);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001253 // Sweep large objects
Ian Rogers1d54e732013-05-02 21:10:01 -07001254 space::LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
1255 accounting::SpaceSetMap* large_live_objects = large_object_space->GetLiveObjects();
1256 accounting::SpaceSetMap* large_mark_objects = large_object_space->GetMarkObjects();
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001257 if (swap_bitmaps) {
1258 std::swap(large_live_objects, large_mark_objects);
1259 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001260 // O(n*log(n)) but hopefully there are not too many large objects.
1261 size_t freed_objects = 0;
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001262 size_t freed_bytes = 0;
Ian Rogers50b35e22012-10-04 10:09:15 -07001263 Thread* self = Thread::Current();
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001264 for (const Object* obj : large_live_objects->GetObjects()) {
Mathieu Chartier02e25112013-08-14 16:14:24 -07001265 if (!large_mark_objects->Test(obj)) {
1266 freed_bytes += large_object_space->Free(self, const_cast<Object*>(obj));
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001267 ++freed_objects;
1268 }
1269 }
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001270 freed_large_objects_.fetch_add(freed_objects);
1271 freed_large_object_bytes_.fetch_add(freed_bytes);
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001272 GetHeap()->RecordFree(freed_objects, freed_bytes);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001273}
1274
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001275void MarkSweep::CheckReference(const Object* obj, const Object* ref, MemberOffset offset, bool is_static) {
Mathieu Chartier02e25112013-08-14 16:14:24 -07001276 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001277 if (space->IsDlMallocSpace() && space->Contains(ref)) {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001278 DCHECK(IsMarked(obj));
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001279
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001280 bool is_marked = IsMarked(ref);
1281 if (!is_marked) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001282 LOG(INFO) << *space;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001283 LOG(WARNING) << (is_static ? "Static ref'" : "Instance ref'") << PrettyTypeOf(ref)
1284 << "' (" << reinterpret_cast<const void*>(ref) << ") in '" << PrettyTypeOf(obj)
1285 << "' (" << reinterpret_cast<const void*>(obj) << ") at offset "
1286 << reinterpret_cast<void*>(offset.Int32Value()) << " wasn't marked";
Mathieu Chartier262e5ff2012-06-01 17:35:38 -07001287
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001288 const Class* klass = is_static ? obj->AsClass() : obj->GetClass();
1289 DCHECK(klass != NULL);
Brian Carlstromea46f952013-07-30 01:26:50 -07001290 const ObjectArray<ArtField>* fields = is_static ? klass->GetSFields() : klass->GetIFields();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001291 DCHECK(fields != NULL);
1292 bool found = false;
1293 for (int32_t i = 0; i < fields->GetLength(); ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001294 const ArtField* cur = fields->Get(i);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001295 if (cur->GetOffset().Int32Value() == offset.Int32Value()) {
1296 LOG(WARNING) << "Field referencing the alloc space was " << PrettyField(cur);
1297 found = true;
1298 break;
1299 }
1300 }
1301 if (!found) {
1302 LOG(WARNING) << "Could not find field in object alloc space with offset " << offset.Int32Value();
1303 }
Mathieu Chartier262e5ff2012-06-01 17:35:38 -07001304
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001305 bool obj_marked = heap_->GetCardTable()->IsDirty(obj);
1306 if (!obj_marked) {
1307 LOG(WARNING) << "Object '" << PrettyTypeOf(obj) << "' "
1308 << "(" << reinterpret_cast<const void*>(obj) << ") contains references to "
1309 << "the alloc space, but wasn't card marked";
Mathieu Chartier262e5ff2012-06-01 17:35:38 -07001310 }
1311 }
Ian Rogers5d76c432011-10-31 21:42:49 -07001312 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001313 break;
Ian Rogers5d76c432011-10-31 21:42:49 -07001314 }
1315}
1316
Carl Shapiro69759ea2011-07-21 18:13:35 -07001317// Process the "referent" field in a java.lang.ref.Reference. If the
1318// referent has not yet been marked, put it on the appropriate list in
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001319// the heap for later processing.
1320void MarkSweep::DelayReferenceReferent(mirror::Class* klass, Object* obj) {
1321 DCHECK(klass != nullptr);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001322 DCHECK(klass->IsReferenceClass());
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001323 DCHECK(obj != NULL);
Mathieu Chartier39e32612013-11-12 16:28:05 -08001324 heap_->DelayReferenceReferent(klass, obj, IsMarkedCallback, this);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001325}
1326
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001327class MarkObjectVisitor {
1328 public:
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001329 explicit MarkObjectVisitor(MarkSweep* const mark_sweep) ALWAYS_INLINE : mark_sweep_(mark_sweep) {}
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001330
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001331 // TODO: Fixme when anotatalysis works with visitors.
Brian Carlstromdf629502013-07-17 22:39:56 -07001332 void operator()(const Object* /* obj */, const Object* ref, const MemberOffset& /* offset */,
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001333 bool /* is_static */) const ALWAYS_INLINE
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001334 NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001335 if (kCheckLocks) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001336 Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
1337 Locks::heap_bitmap_lock_->AssertExclusiveHeld(Thread::Current());
1338 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001339 mark_sweep_->MarkObject(ref);
1340 }
1341
1342 private:
1343 MarkSweep* const mark_sweep_;
1344};
1345
Carl Shapiro69759ea2011-07-21 18:13:35 -07001346// Scans an object reference. Determines the type of the reference
1347// and dispatches to a specialized scanning routine.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001348void MarkSweep::ScanObject(Object* obj) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001349 MarkObjectVisitor visitor(this);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001350 ScanObjectVisit(obj, visitor);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001351}
1352
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001353void MarkSweep::ProcessMarkStackParallel(size_t thread_count) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001354 Thread* self = Thread::Current();
1355 ThreadPool* thread_pool = GetHeap()->GetThreadPool();
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001356 const size_t chunk_size = std::min(mark_stack_->Size() / thread_count + 1,
1357 static_cast<size_t>(MarkStackTask<false>::kMaxSize));
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001358 CHECK_GT(chunk_size, 0U);
1359 // Split the current mark stack up into work tasks.
1360 for (mirror::Object **it = mark_stack_->Begin(), **end = mark_stack_->End(); it < end; ) {
1361 const size_t delta = std::min(static_cast<size_t>(end - it), chunk_size);
1362 thread_pool->AddTask(self, new MarkStackTask<false>(thread_pool, this, delta,
1363 const_cast<const mirror::Object**>(it)));
1364 it += delta;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001365 }
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001366 thread_pool->SetMaxActiveWorkers(thread_count - 1);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001367 thread_pool->StartWorkers(self);
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001368 thread_pool->Wait(self, true, true);
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001369 thread_pool->StopWorkers(self);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001370 mark_stack_->Reset();
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001371 CHECK_EQ(work_chunks_created_, work_chunks_deleted_) << " some of the work chunks were leaked";
Carl Shapiro69759ea2011-07-21 18:13:35 -07001372}
1373
Ian Rogers5d76c432011-10-31 21:42:49 -07001374// Scan anything that's on the mark stack.
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001375void MarkSweep::ProcessMarkStack(bool paused) {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001376 timings_.StartSplit("ProcessMarkStack");
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001377 size_t thread_count = GetThreadCount(paused);
1378 if (kParallelProcessMarkStack && thread_count > 1 &&
1379 mark_stack_->Size() >= kMinimumParallelMarkStackSize) {
1380 ProcessMarkStackParallel(thread_count);
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001381 } else {
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001382 // TODO: Tune this.
1383 static const size_t kFifoSize = 4;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001384 BoundedFifoPowerOfTwo<Object*, kFifoSize> prefetch_fifo;
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001385 for (;;) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001386 Object* obj = NULL;
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001387 if (kUseMarkStackPrefetch) {
1388 while (!mark_stack_->IsEmpty() && prefetch_fifo.size() < kFifoSize) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001389 Object* obj = mark_stack_->PopBack();
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001390 DCHECK(obj != NULL);
1391 __builtin_prefetch(obj);
1392 prefetch_fifo.push_back(obj);
1393 }
1394 if (prefetch_fifo.empty()) {
1395 break;
1396 }
1397 obj = prefetch_fifo.front();
1398 prefetch_fifo.pop_front();
1399 } else {
1400 if (mark_stack_->IsEmpty()) {
1401 break;
1402 }
1403 obj = mark_stack_->PopBack();
1404 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001405 DCHECK(obj != NULL);
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001406 ScanObject(obj);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001407 }
1408 }
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001409 timings_.EndSplit();
Carl Shapiro69759ea2011-07-21 18:13:35 -07001410}
1411
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001412inline bool MarkSweep::IsMarked(const Object* object) const
1413 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
Mathieu Chartier9642c962013-08-05 17:40:36 -07001414 if (IsImmune(object)) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001415 return true;
1416 }
1417 DCHECK(current_mark_bitmap_ != NULL);
1418 if (current_mark_bitmap_->HasAddress(object)) {
1419 return current_mark_bitmap_->Test(object);
1420 }
1421 return heap_->GetMarkBitmap()->Test(object);
1422}
1423
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001424void MarkSweep::UnBindBitmaps() {
Ian Rogers5fe9af72013-11-14 00:17:20 -08001425 TimingLogger::ScopedSplit split("UnBindBitmaps", &timings_);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001426 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001427 if (space->IsDlMallocSpace()) {
1428 space::DlMallocSpace* alloc_space = space->AsDlMallocSpace();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001429 if (alloc_space->temp_bitmap_.get() != NULL) {
1430 // At this point, the temp_bitmap holds our old mark bitmap.
Ian Rogers1d54e732013-05-02 21:10:01 -07001431 accounting::SpaceBitmap* new_bitmap = alloc_space->temp_bitmap_.release();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001432 GetHeap()->GetMarkBitmap()->ReplaceBitmap(alloc_space->mark_bitmap_.get(), new_bitmap);
1433 CHECK_EQ(alloc_space->mark_bitmap_.release(), alloc_space->live_bitmap_.get());
1434 alloc_space->mark_bitmap_.reset(new_bitmap);
1435 DCHECK(alloc_space->temp_bitmap_.get() == NULL);
1436 }
1437 }
1438 }
1439}
1440
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001441void MarkSweep::FinishPhase() {
Ian Rogers5fe9af72013-11-14 00:17:20 -08001442 TimingLogger::ScopedSplit split("FinishPhase", &timings_);
Anwar Ghuloum46543222013-08-12 09:28:42 -07001443 // Can't enqueue references if we hold the mutator lock.
Ian Rogers1d54e732013-05-02 21:10:01 -07001444 Heap* heap = GetHeap();
Anwar Ghuloum46543222013-08-12 09:28:42 -07001445 timings_.NewSplit("PostGcVerification");
Ian Rogers1d54e732013-05-02 21:10:01 -07001446 heap->PostGcVerification(this);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001447
Anwar Ghuloum46543222013-08-12 09:28:42 -07001448 timings_.NewSplit("RequestHeapTrim");
Ian Rogers1d54e732013-05-02 21:10:01 -07001449 heap->RequestHeapTrim();
Mathieu Chartier65db8802012-11-20 12:36:46 -08001450
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001451 // Update the cumulative statistics
Ian Rogers1d54e732013-05-02 21:10:01 -07001452 total_time_ns_ += GetDurationNs();
1453 total_paused_time_ns_ += std::accumulate(GetPauseTimes().begin(), GetPauseTimes().end(), 0,
1454 std::plus<uint64_t>());
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001455 total_freed_objects_ += GetFreedObjects() + GetFreedLargeObjects();
1456 total_freed_bytes_ += GetFreedBytes() + GetFreedLargeObjectBytes();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001457
1458 // Ensure that the mark stack is empty.
1459 CHECK(mark_stack_->IsEmpty());
1460
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001461 if (kCountScannedTypes) {
1462 VLOG(gc) << "MarkSweep scanned classes=" << class_count_ << " arrays=" << array_count_
1463 << " other=" << other_count_;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001464 }
1465
1466 if (kCountTasks) {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001467 VLOG(gc) << "Total number of work chunks allocated: " << work_chunks_created_;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001468 }
1469
1470 if (kMeasureOverhead) {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001471 VLOG(gc) << "Overhead time " << PrettyDuration(overhead_time_);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001472 }
1473
1474 if (kProfileLargeObjects) {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001475 VLOG(gc) << "Large objects tested " << large_object_test_ << " marked " << large_object_mark_;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001476 }
1477
1478 if (kCountClassesMarked) {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001479 VLOG(gc) << "Classes marked " << classes_marked_;
1480 }
1481
1482 if (kCountJavaLangRefs) {
1483 VLOG(gc) << "References scanned " << reference_count_;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001484 }
1485
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001486 // Update the cumulative loggers.
1487 cumulative_timings_.Start();
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001488 cumulative_timings_.AddLogger(timings_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001489 cumulative_timings_.End();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001490
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001491 // Clear all of the spaces' mark bitmaps.
Mathieu Chartier02e25112013-08-14 16:14:24 -07001492 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001493 accounting::SpaceBitmap* bitmap = space->GetMarkBitmap();
1494 if (bitmap != nullptr &&
1495 space->GetGcRetentionPolicy() != space::kGcRetentionPolicyNeverCollect) {
1496 bitmap->Clear();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001497 }
1498 }
Mathieu Chartier5301cd22012-05-31 12:11:36 -07001499 mark_stack_->Reset();
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001500
1501 // Reset the marked large objects.
Ian Rogers1d54e732013-05-02 21:10:01 -07001502 space::LargeObjectSpace* large_objects = GetHeap()->GetLargeObjectsSpace();
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001503 large_objects->GetMarkObjects()->Clear();
Carl Shapiro69759ea2011-07-21 18:13:35 -07001504}
1505
Ian Rogers1d54e732013-05-02 21:10:01 -07001506} // namespace collector
1507} // namespace gc
Carl Shapiro69759ea2011-07-21 18:13:35 -07001508} // namespace art