blob: 1625ba684dce1e9b5fb3d5df22001cc4e1976216 [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"
31#include "gc/accounting/space_bitmap-inl.h"
32#include "gc/heap.h"
33#include "gc/space/image_space.h"
34#include "gc/space/large_object_space.h"
35#include "gc/space/space-inl.h"
Elliott Hughes410c0c82011-09-01 17:58:25 -070036#include "indirect_reference_table.h"
37#include "intern_table.h"
Ian Rogers81d425b2012-09-27 16:03:43 -070038#include "jni_internal.h"
Elliott Hughesc33a32b2011-10-11 18:18:07 -070039#include "monitor.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080040#include "mark_sweep-inl.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070041#include "mirror/art_field.h"
42#include "mirror/art_field-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080043#include "mirror/class-inl.h"
44#include "mirror/class_loader.h"
45#include "mirror/dex_cache.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080046#include "mirror/object-inl.h"
47#include "mirror/object_array.h"
48#include "mirror/object_array-inl.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070049#include "runtime.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070050#include "thread-inl.h"
Mathieu Chartier6f1c9492012-10-15 12:08:41 -070051#include "thread_list.h"
Ian Rogers08254272012-10-23 17:49:23 -070052#include "verifier/method_verifier.h"
Carl Shapiro69759ea2011-07-21 18:13:35 -070053
Brian Carlstromea46f952013-07-30 01:26:50 -070054using ::art::mirror::ArtField;
Brian Carlstrom3e3d5912013-07-18 00:19:45 -070055using ::art::mirror::Class;
Brian Carlstrom3e3d5912013-07-18 00:19:45 -070056using ::art::mirror::Object;
57using ::art::mirror::ObjectArray;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080058
Carl Shapiro69759ea2011-07-21 18:13:35 -070059namespace art {
Ian Rogers1d54e732013-05-02 21:10:01 -070060namespace gc {
61namespace collector {
Carl Shapiro69759ea2011-07-21 18:13:35 -070062
Mathieu Chartier02b6a782012-10-26 13:51:26 -070063// Performance options.
Mathieu Chartier94c32c52013-08-09 11:14:04 -070064constexpr bool kUseRecursiveMark = false;
65constexpr bool kUseMarkStackPrefetch = true;
66constexpr size_t kSweepArrayChunkFreeSize = 1024;
67
68// Parallelism options.
69constexpr bool kParallelCardScan = true;
70constexpr bool kParallelRecursiveMark = true;
71// Don't attempt to parallelize mark stack processing unless the mark stack is at least n
72// elements. This is temporary until we reduce the overhead caused by allocating tasks, etc.. Not
73// having this can add overhead in ProcessReferences since we may end up doing many calls of
74// ProcessMarkStack with very small mark stacks.
75constexpr size_t kMinimumParallelMarkStackSize = 128;
76constexpr bool kParallelProcessMarkStack = true;
Mathieu Chartier858f1c52012-10-17 17:45:55 -070077
Mathieu Chartier02b6a782012-10-26 13:51:26 -070078// Profiling and information flags.
Mathieu Chartier94c32c52013-08-09 11:14:04 -070079constexpr bool kCountClassesMarked = false;
80constexpr bool kProfileLargeObjects = false;
81constexpr bool kMeasureOverhead = false;
82constexpr bool kCountTasks = false;
83constexpr bool kCountJavaLangRefs = false;
84
85// Turn off kCheckLocks when profiling the GC since it slows the GC down by up to 40%.
86constexpr bool kCheckLocks = kDebugLocking;
Mathieu Chartier02b6a782012-10-26 13:51:26 -070087
Ian Rogers1d54e732013-05-02 21:10:01 -070088void MarkSweep::ImmuneSpace(space::ContinuousSpace* space) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -080089 // Bind live to mark bitmap if necessary.
90 if (space->GetLiveBitmap() != space->GetMarkBitmap()) {
91 BindLiveToMarkBitmap(space);
92 }
93
94 // Add the space to the immune region.
95 if (immune_begin_ == NULL) {
96 DCHECK(immune_end_ == NULL);
97 SetImmuneRange(reinterpret_cast<Object*>(space->Begin()),
98 reinterpret_cast<Object*>(space->End()));
99 } else {
Mathieu Chartier02e25112013-08-14 16:14:24 -0700100 const space::ContinuousSpace* prev_space = nullptr;
Ian Rogers1d54e732013-05-02 21:10:01 -0700101 // Find out if the previous space is immune.
Mathieu Chartier02e25112013-08-14 16:14:24 -0700102 for (space::ContinuousSpace* cur_space : GetHeap()->GetContinuousSpaces()) {
103 if (cur_space == space) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700104 break;
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800105 }
Mathieu Chartier02e25112013-08-14 16:14:24 -0700106 prev_space = cur_space;
Ian Rogers1d54e732013-05-02 21:10:01 -0700107 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700108 // If previous space was immune, then extend the immune region. Relies on continuous spaces
109 // being sorted by Heap::AddContinuousSpace.
110 if (prev_space != NULL &&
111 immune_begin_ <= reinterpret_cast<Object*>(prev_space->Begin()) &&
112 immune_end_ >= reinterpret_cast<Object*>(prev_space->End())) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800113 immune_begin_ = std::min(reinterpret_cast<Object*>(space->Begin()), immune_begin_);
114 immune_end_ = std::max(reinterpret_cast<Object*>(space->End()), immune_end_);
115 }
116 }
117}
118
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800119void MarkSweep::BindBitmaps() {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700120 timings_.StartSplit("BindBitmaps");
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800121 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800122 // Mark all of the spaces we never collect as immune.
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700123 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700124 if (space->GetGcRetentionPolicy() == space::kGcRetentionPolicyNeverCollect) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800125 ImmuneSpace(space);
126 }
127 }
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700128 timings_.EndSplit();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800129}
130
Ian Rogers1d54e732013-05-02 21:10:01 -0700131MarkSweep::MarkSweep(Heap* heap, bool is_concurrent, const std::string& name_prefix)
132 : GarbageCollector(heap,
133 name_prefix + (name_prefix.empty() ? "" : " ") +
134 (is_concurrent ? "concurrent mark sweep": "mark sweep")),
135 current_mark_bitmap_(NULL),
136 java_lang_Class_(NULL),
137 mark_stack_(NULL),
Ian Rogers1d54e732013-05-02 21:10:01 -0700138 immune_begin_(NULL),
139 immune_end_(NULL),
140 soft_reference_list_(NULL),
141 weak_reference_list_(NULL),
142 finalizer_reference_list_(NULL),
143 phantom_reference_list_(NULL),
144 cleared_reference_list_(NULL),
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800145 gc_barrier_(new Barrier(0)),
Ian Rogers62d6c772013-02-27 08:32:07 -0800146 large_object_lock_("mark sweep large object lock", kMarkSweepLargeObjectLock),
Mathieu Chartier958291c2013-08-27 18:14:55 -0700147 mark_stack_lock_("mark sweep mark stack lock", kMarkSweepMarkStackLock),
Ian Rogers1bd4b4c2013-04-18 17:47:42 -0700148 is_concurrent_(is_concurrent),
Ian Rogers1d54e732013-05-02 21:10:01 -0700149 clear_soft_references_(false) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800150}
151
152void MarkSweep::InitializePhase() {
Ian Rogers1d54e732013-05-02 21:10:01 -0700153 timings_.Reset();
Anwar Ghuloum46543222013-08-12 09:28:42 -0700154 base::TimingLogger::ScopedSplit split("InitializePhase", &timings_);
Mathieu Chartiere53225c2013-08-19 10:59:11 -0700155 mark_stack_ = heap_->mark_stack_.get();
156 DCHECK(mark_stack_ != nullptr);
157 SetImmuneRange(nullptr, nullptr);
158 soft_reference_list_ = nullptr;
159 weak_reference_list_ = nullptr;
160 finalizer_reference_list_ = nullptr;
161 phantom_reference_list_ = nullptr;
162 cleared_reference_list_ = nullptr;
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800163 freed_bytes_ = 0;
Mathieu Chartiere53225c2013-08-19 10:59:11 -0700164 freed_large_object_bytes_ = 0;
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800165 freed_objects_ = 0;
Mathieu Chartiere53225c2013-08-19 10:59:11 -0700166 freed_large_objects_ = 0;
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800167 class_count_ = 0;
168 array_count_ = 0;
169 other_count_ = 0;
170 large_object_test_ = 0;
171 large_object_mark_ = 0;
172 classes_marked_ = 0;
173 overhead_time_ = 0;
174 work_chunks_created_ = 0;
175 work_chunks_deleted_ = 0;
176 reference_count_ = 0;
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700177 java_lang_Class_ = Class::GetJavaLangClass();
Mathieu Chartiere53225c2013-08-19 10:59:11 -0700178 CHECK(java_lang_Class_ != nullptr);
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) {
Mathieu Chartier9e452d12013-09-18 16:35:15 -0700188 base::TimingLogger::ScopedSplit split("ProcessReferences", &timings_);
Mathieu Chartier8e56c7e2012-11-20 13:25:50 -0800189 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800190 ProcessReferences(&soft_reference_list_, clear_soft_references_, &weak_reference_list_,
191 &finalizer_reference_list_, &phantom_reference_list_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800192}
193
194bool MarkSweep::HandleDirtyObjectsPhase() {
Anwar Ghuloum46543222013-08-12 09:28:42 -0700195 base::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() {
Anwar Ghuloum46543222013-08-12 09:28:42 -0700241 base::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 Chartier2b82db42012-11-14 17:29:05 -0800266
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700267 heap_->UpdateAndMarkModUnion(this, timings_, GetGcType());
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800268 MarkReachableObjects();
269}
270
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700271void MarkSweep::MarkThreadRoots(Thread* self) {
272 MarkRootsCheckpoint(self);
273}
274
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800275void MarkSweep::MarkReachableObjects() {
276 // Mark everything allocated since the last as GC live so that we can sweep concurrently,
277 // knowing that new allocations won't be marked as live.
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700278 timings_.StartSplit("MarkStackAsLive");
Ian Rogers1d54e732013-05-02 21:10:01 -0700279 accounting::ObjectStack* live_stack = heap_->GetLiveStack();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800280 heap_->MarkAllocStack(heap_->alloc_space_->GetLiveBitmap(),
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700281 heap_->large_object_space_->GetLiveObjects(), 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() {
Anwar Ghuloum46543222013-08-12 09:28:42 -0700289 base::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
Anwar Ghulouma9a50922013-08-09 21:34:20 -0700304 base::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 Chartier9642c962013-08-05 17:40:36 -0700307 // The allocation stack contains things allocated since the start of the GC. These may have been
308 // marked during this GC meaning they won't be eligible for reclaiming in the next sticky GC.
309 // Remove these objects from the mark bitmaps so that they will be eligible for sticky
310 // collection.
311 // There is a race here which is safely handled. Another thread such as the hprof could
312 // have flushed the alloc stack after we resumed the threads. This is safe however, since
313 // reseting the allocation stack zeros it out with madvise. This means that we will either
314 // read NULLs or attempt to unmark a newly allocated object which will not be marked in the
315 // first place.
316 mirror::Object** end = allocation_stack->End();
317 for (mirror::Object** it = allocation_stack->Begin(); it != end; ++it) {
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700318 const Object* obj = *it;
Mathieu Chartier9642c962013-08-05 17:40:36 -0700319 if (obj != NULL) {
320 UnMarkObjectNonNull(obj);
321 }
322 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800323 }
324
325 // Before freeing anything, lets verify the heap.
326 if (kIsDebugBuild) {
327 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
328 VerifyImageRoots();
329 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800330
331 {
332 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
333
334 // Reclaim unmarked objects.
Ian Rogers1d54e732013-05-02 21:10:01 -0700335 Sweep(false);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800336
337 // Swap the live and mark bitmaps for each space which we modified space. This is an
338 // optimization that enables us to not clear live bits inside of the sweep. Only swaps unbound
339 // bitmaps.
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700340 timings_.StartSplit("SwapBitmaps");
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800341 SwapBitmaps();
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700342 timings_.EndSplit();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800343
344 // Unbind the live and mark bitmaps.
345 UnBindBitmaps();
346 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800347}
348
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800349void MarkSweep::SetImmuneRange(Object* begin, Object* end) {
350 immune_begin_ = begin;
351 immune_end_ = end;
Carl Shapiro58551df2011-07-24 03:09:51 -0700352}
353
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700354void MarkSweep::FindDefaultMarkBitmap() {
Anwar Ghuloum46543222013-08-12 09:28:42 -0700355 base::TimingLogger::ScopedSplit split("FindDefaultMarkBitmap", &timings_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700356 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700357 if (space->GetGcRetentionPolicy() == space::kGcRetentionPolicyAlwaysCollect) {
Mathieu Chartier02e25112013-08-14 16:14:24 -0700358 current_mark_bitmap_ = space->GetMarkBitmap();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700359 CHECK(current_mark_bitmap_ != NULL);
360 return;
361 }
362 }
363 GetHeap()->DumpSpaces();
364 LOG(FATAL) << "Could not find a default mark bitmap";
365}
366
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800367void MarkSweep::ExpandMarkStack() {
Mathieu Chartierba311b42013-08-27 13:02:30 -0700368 ResizeMarkStack(mark_stack_->Capacity() * 2);
369}
370
371void MarkSweep::ResizeMarkStack(size_t new_size) {
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800372 // Rare case, no need to have Thread::Current be a parameter.
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800373 if (UNLIKELY(mark_stack_->Size() < mark_stack_->Capacity())) {
374 // Someone else acquired the lock and expanded the mark stack before us.
375 return;
376 }
Mathieu Chartier02e25112013-08-14 16:14:24 -0700377 std::vector<Object*> temp(mark_stack_->Begin(), mark_stack_->End());
Mathieu Chartierba311b42013-08-27 13:02:30 -0700378 CHECK_LE(mark_stack_->Size(), new_size);
379 mark_stack_->Resize(new_size);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700380 for (const auto& obj : temp) {
381 mark_stack_->PushBack(obj);
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800382 }
383}
384
Mathieu Chartier9642c962013-08-05 17:40:36 -0700385inline void MarkSweep::MarkObjectNonNullParallel(const Object* obj) {
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800386 DCHECK(obj != NULL);
387 if (MarkObjectParallel(obj)) {
Mathieu Chartierba311b42013-08-27 13:02:30 -0700388 MutexLock mu(Thread::Current(), mark_stack_lock_);
389 if (UNLIKELY(mark_stack_->Size() >= mark_stack_->Capacity())) {
Mathieu Chartier184e3222013-08-03 14:02:57 -0700390 ExpandMarkStack();
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800391 }
Mathieu Chartierba311b42013-08-27 13:02:30 -0700392 // The object must be pushed on to the mark stack.
393 mark_stack_->PushBack(const_cast<Object*>(obj));
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800394 }
395}
396
Mathieu Chartier9642c962013-08-05 17:40:36 -0700397inline void MarkSweep::UnMarkObjectNonNull(const Object* obj) {
398 DCHECK(!IsImmune(obj));
399 // Try to take advantage of locality of references within a space, failing this find the space
400 // the hard way.
401 accounting::SpaceBitmap* object_bitmap = current_mark_bitmap_;
402 if (UNLIKELY(!object_bitmap->HasAddress(obj))) {
403 accounting::SpaceBitmap* new_bitmap = heap_->GetMarkBitmap()->GetContinuousSpaceBitmap(obj);
404 if (LIKELY(new_bitmap != NULL)) {
405 object_bitmap = new_bitmap;
406 } else {
407 MarkLargeObject(obj, false);
408 return;
409 }
410 }
411
412 DCHECK(object_bitmap->HasAddress(obj));
413 object_bitmap->Clear(obj);
414}
415
416inline void MarkSweep::MarkObjectNonNull(const Object* obj) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700417 DCHECK(obj != NULL);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700418
Mathieu Chartier9642c962013-08-05 17:40:36 -0700419 if (IsImmune(obj)) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700420 DCHECK(IsMarked(obj));
Carl Shapiro69759ea2011-07-21 18:13:35 -0700421 return;
422 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700423
424 // Try to take advantage of locality of references within a space, failing this find the space
425 // the hard way.
Ian Rogers1d54e732013-05-02 21:10:01 -0700426 accounting::SpaceBitmap* object_bitmap = current_mark_bitmap_;
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700427 if (UNLIKELY(!object_bitmap->HasAddress(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700428 accounting::SpaceBitmap* new_bitmap = heap_->GetMarkBitmap()->GetContinuousSpaceBitmap(obj);
429 if (LIKELY(new_bitmap != NULL)) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700430 object_bitmap = new_bitmap;
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700431 } else {
Mathieu Chartier9642c962013-08-05 17:40:36 -0700432 MarkLargeObject(obj, true);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700433 return;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700434 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700435 }
436
Carl Shapiro69759ea2011-07-21 18:13:35 -0700437 // This object was not previously marked.
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700438 if (!object_bitmap->Test(obj)) {
439 object_bitmap->Set(obj);
Mathieu Chartier184e3222013-08-03 14:02:57 -0700440 if (UNLIKELY(mark_stack_->Size() >= mark_stack_->Capacity())) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700441 // Lock is not needed but is here anyways to please annotalysis.
442 MutexLock mu(Thread::Current(), mark_stack_lock_);
Mathieu Chartier184e3222013-08-03 14:02:57 -0700443 ExpandMarkStack();
Carl Shapiro69759ea2011-07-21 18:13:35 -0700444 }
Mathieu Chartier184e3222013-08-03 14:02:57 -0700445 // The object must be pushed on to the mark stack.
446 mark_stack_->PushBack(const_cast<Object*>(obj));
Carl Shapiro69759ea2011-07-21 18:13:35 -0700447 }
448}
449
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700450// Rare case, probably not worth inlining since it will increase instruction cache miss rate.
Mathieu Chartier9642c962013-08-05 17:40:36 -0700451bool MarkSweep::MarkLargeObject(const Object* obj, bool set) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700452 // TODO: support >1 discontinuous space.
453 space::LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
454 accounting::SpaceSetMap* large_objects = large_object_space->GetMarkObjects();
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700455 if (kProfileLargeObjects) {
456 ++large_object_test_;
457 }
458 if (UNLIKELY(!large_objects->Test(obj))) {
Mathieu Chartier4fcb8d32013-07-15 12:43:36 -0700459 if (!large_object_space->Contains(obj)) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700460 LOG(ERROR) << "Tried to mark " << obj << " not contained by any spaces";
461 LOG(ERROR) << "Attempting see if it's a bad root";
462 VerifyRoots();
463 LOG(FATAL) << "Can't mark bad root";
464 }
465 if (kProfileLargeObjects) {
466 ++large_object_mark_;
467 }
Mathieu Chartier9642c962013-08-05 17:40:36 -0700468 if (set) {
469 large_objects->Set(obj);
470 } else {
471 large_objects->Clear(obj);
472 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700473 return true;
474 }
475 return false;
476}
477
478inline bool MarkSweep::MarkObjectParallel(const Object* obj) {
479 DCHECK(obj != NULL);
480
Mathieu Chartier9642c962013-08-05 17:40:36 -0700481 if (IsImmune(obj)) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700482 DCHECK(IsMarked(obj));
483 return false;
484 }
485
486 // Try to take advantage of locality of references within a space, failing this find the space
487 // the hard way.
Ian Rogers1d54e732013-05-02 21:10:01 -0700488 accounting::SpaceBitmap* object_bitmap = current_mark_bitmap_;
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700489 if (UNLIKELY(!object_bitmap->HasAddress(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700490 accounting::SpaceBitmap* new_bitmap = heap_->GetMarkBitmap()->GetContinuousSpaceBitmap(obj);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700491 if (new_bitmap != NULL) {
492 object_bitmap = new_bitmap;
493 } else {
494 // TODO: Remove the Thread::Current here?
495 // TODO: Convert this to some kind of atomic marking?
496 MutexLock mu(Thread::Current(), large_object_lock_);
Mathieu Chartier9642c962013-08-05 17:40:36 -0700497 return MarkLargeObject(obj, true);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700498 }
499 }
500
501 // Return true if the object was not previously marked.
502 return !object_bitmap->AtomicTestAndSet(obj);
503}
504
Carl Shapiro69759ea2011-07-21 18:13:35 -0700505// Used to mark objects when recursing. Recursion is done by moving
506// the finger across the bitmaps in address order and marking child
507// objects. Any newly-marked objects whose addresses are lower than
508// the finger won't be visited by the bitmap scan, so those objects
509// need to be added to the mark stack.
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700510inline void MarkSweep::MarkObject(const Object* obj) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700511 if (obj != NULL) {
Mathieu Chartier9642c962013-08-05 17:40:36 -0700512 MarkObjectNonNull(obj);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700513 }
514}
515
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800516void MarkSweep::MarkRoot(const Object* obj) {
517 if (obj != NULL) {
Mathieu Chartier9642c962013-08-05 17:40:36 -0700518 MarkObjectNonNull(obj);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800519 }
520}
521
Mathieu Chartier423d2a32013-09-12 17:33:56 -0700522Object* MarkSweep::MarkRootParallelCallback(Object* root, void* arg) {
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800523 DCHECK(root != NULL);
524 DCHECK(arg != NULL);
Mathieu Chartierba311b42013-08-27 13:02:30 -0700525 reinterpret_cast<MarkSweep*>(arg)->MarkObjectNonNullParallel(root);
Mathieu Chartier423d2a32013-09-12 17:33:56 -0700526 return root;
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800527}
528
Mathieu Chartier423d2a32013-09-12 17:33:56 -0700529Object* MarkSweep::MarkRootCallback(Object* root, void* arg) {
530 DCHECK(root != nullptr);
531 DCHECK(arg != nullptr);
532 reinterpret_cast<MarkSweep*>(arg)->MarkObjectNonNull(root);
533 return root;
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700534}
535
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700536void MarkSweep::VerifyRootCallback(const Object* root, void* arg, size_t vreg,
Ian Rogers40e3bac2012-11-20 00:09:14 -0800537 const StackVisitor* visitor) {
538 reinterpret_cast<MarkSweep*>(arg)->VerifyRoot(root, vreg, visitor);
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700539}
540
Ian Rogers40e3bac2012-11-20 00:09:14 -0800541void MarkSweep::VerifyRoot(const Object* root, size_t vreg, const StackVisitor* visitor) {
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700542 // See if the root is on any space bitmap.
Ian Rogers1d54e732013-05-02 21:10:01 -0700543 if (GetHeap()->GetLiveBitmap()->GetContinuousSpaceBitmap(root) == NULL) {
544 space::LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
Mathieu Chartier4202b742012-10-17 17:51:25 -0700545 if (!large_object_space->Contains(root)) {
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700546 LOG(ERROR) << "Found invalid root: " << root;
Ian Rogers40e3bac2012-11-20 00:09:14 -0800547 if (visitor != NULL) {
548 LOG(ERROR) << visitor->DescribeLocation() << " in VReg: " << vreg;
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700549 }
550 }
551 }
552}
553
554void MarkSweep::VerifyRoots() {
555 Runtime::Current()->GetThreadList()->VerifyRoots(VerifyRootCallback, this);
556}
557
Carl Shapiro69759ea2011-07-21 18:13:35 -0700558// Marks all objects in the root set.
559void MarkSweep::MarkRoots() {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700560 timings_.StartSplit("MarkRoots");
Mathieu Chartier423d2a32013-09-12 17:33:56 -0700561 Runtime::Current()->VisitNonConcurrentRoots(MarkRootCallback, this);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700562 timings_.EndSplit();
Mathieu Chartier9ebae1f2012-10-15 17:38:16 -0700563}
564
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700565void MarkSweep::MarkNonThreadRoots() {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700566 timings_.StartSplit("MarkNonThreadRoots");
Mathieu Chartier423d2a32013-09-12 17:33:56 -0700567 Runtime::Current()->VisitNonThreadRoots(MarkRootCallback, this);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700568 timings_.EndSplit();
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700569}
570
Mathieu Chartier9ebae1f2012-10-15 17:38:16 -0700571void MarkSweep::MarkConcurrentRoots() {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700572 timings_.StartSplit("MarkConcurrentRoots");
Ian Rogers1d54e732013-05-02 21:10:01 -0700573 // Visit all runtime roots and clear dirty flags.
Mathieu Chartier423d2a32013-09-12 17:33:56 -0700574 Runtime::Current()->VisitConcurrentRoots(MarkRootCallback, this, false, true);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700575 timings_.EndSplit();
Carl Shapiro69759ea2011-07-21 18:13:35 -0700576}
577
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700578void MarkSweep::CheckObject(const Object* obj) {
579 DCHECK(obj != NULL);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700580 VisitObjectReferences(obj, [this](const Object* obj, const Object* ref, MemberOffset offset,
581 bool is_static) NO_THREAD_SAFETY_ANALYSIS {
582 Locks::heap_bitmap_lock_->AssertSharedHeld(Thread::Current());
583 CheckReference(obj, ref, offset, is_static);
584 });
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700585}
586
587void MarkSweep::VerifyImageRootVisitor(Object* root, void* arg) {
588 DCHECK(root != NULL);
589 DCHECK(arg != NULL);
590 MarkSweep* mark_sweep = reinterpret_cast<MarkSweep*>(arg);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700591 DCHECK(mark_sweep->heap_->GetMarkBitmap()->Test(root));
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700592 mark_sweep->CheckObject(root);
593}
594
Ian Rogers1d54e732013-05-02 21:10:01 -0700595void MarkSweep::BindLiveToMarkBitmap(space::ContinuousSpace* space) {
596 CHECK(space->IsDlMallocSpace());
597 space::DlMallocSpace* alloc_space = space->AsDlMallocSpace();
598 accounting::SpaceBitmap* live_bitmap = space->GetLiveBitmap();
599 accounting::SpaceBitmap* mark_bitmap = alloc_space->mark_bitmap_.release();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700600 GetHeap()->GetMarkBitmap()->ReplaceBitmap(mark_bitmap, live_bitmap);
601 alloc_space->temp_bitmap_.reset(mark_bitmap);
602 alloc_space->mark_bitmap_.reset(live_bitmap);
603}
604
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700605class ScanObjectVisitor {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700606 public:
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700607 explicit ScanObjectVisitor(MarkSweep* const mark_sweep) ALWAYS_INLINE
608 : mark_sweep_(mark_sweep) {}
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700609
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800610 // TODO: Fixme when anotatalysis works with visitors.
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700611 void operator()(const Object* obj) const ALWAYS_INLINE NO_THREAD_SAFETY_ANALYSIS {
612 if (kCheckLocks) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800613 Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
614 Locks::heap_bitmap_lock_->AssertExclusiveHeld(Thread::Current());
615 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700616 mark_sweep_->ScanObject(obj);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700617 }
618
619 private:
620 MarkSweep* const mark_sweep_;
621};
622
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700623template <bool kUseFinger = false>
624class MarkStackTask : public Task {
625 public:
626 MarkStackTask(ThreadPool* thread_pool, MarkSweep* mark_sweep, size_t mark_stack_size,
627 const Object** mark_stack)
628 : mark_sweep_(mark_sweep),
629 thread_pool_(thread_pool),
630 mark_stack_pos_(mark_stack_size) {
631 // We may have to copy part of an existing mark stack when another mark stack overflows.
632 if (mark_stack_size != 0) {
633 DCHECK(mark_stack != NULL);
634 // TODO: Check performance?
635 std::copy(mark_stack, mark_stack + mark_stack_size, mark_stack_);
Ian Rogers1d54e732013-05-02 21:10:01 -0700636 }
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700637 if (kCountTasks) {
638 ++mark_sweep_->work_chunks_created_;
639 }
640 }
641
642 static const size_t kMaxSize = 1 * KB;
643
644 protected:
645 class ScanObjectParallelVisitor {
646 public:
647 explicit ScanObjectParallelVisitor(MarkStackTask<kUseFinger>* chunk_task) ALWAYS_INLINE
648 : chunk_task_(chunk_task) {}
649
650 void operator()(const Object* obj) const {
651 MarkSweep* mark_sweep = chunk_task_->mark_sweep_;
652 mark_sweep->ScanObjectVisit(obj,
653 [mark_sweep, this](const Object* /* obj */, const Object* ref,
654 const MemberOffset& /* offset */, bool /* is_static */) ALWAYS_INLINE {
655 if (ref != nullptr && mark_sweep->MarkObjectParallel(ref)) {
656 if (kUseFinger) {
657 android_memory_barrier();
658 if (reinterpret_cast<uintptr_t>(ref) >=
659 static_cast<uintptr_t>(mark_sweep->atomic_finger_)) {
660 return;
661 }
662 }
663 chunk_task_->MarkStackPush(ref);
664 }
665 });
666 }
667
668 private:
669 MarkStackTask<kUseFinger>* const chunk_task_;
670 };
671
672 virtual ~MarkStackTask() {
673 // Make sure that we have cleared our mark stack.
674 DCHECK_EQ(mark_stack_pos_, 0U);
675 if (kCountTasks) {
676 ++mark_sweep_->work_chunks_deleted_;
677 }
678 }
679
680 MarkSweep* const mark_sweep_;
681 ThreadPool* const thread_pool_;
682 // Thread local mark stack for this task.
683 const Object* mark_stack_[kMaxSize];
684 // Mark stack position.
685 size_t mark_stack_pos_;
686
687 void MarkStackPush(const Object* obj) ALWAYS_INLINE {
688 if (UNLIKELY(mark_stack_pos_ == kMaxSize)) {
689 // Mark stack overflow, give 1/2 the stack to the thread pool as a new work task.
690 mark_stack_pos_ /= 2;
691 auto* task = new MarkStackTask(thread_pool_, mark_sweep_, kMaxSize - mark_stack_pos_,
692 mark_stack_ + mark_stack_pos_);
693 thread_pool_->AddTask(Thread::Current(), task);
694 }
695 DCHECK(obj != nullptr);
696 DCHECK(mark_stack_pos_ < kMaxSize);
697 mark_stack_[mark_stack_pos_++] = obj;
698 }
699
700 virtual void Finalize() {
701 delete this;
702 }
703
704 // Scans all of the objects
705 virtual void Run(Thread* self) {
706 ScanObjectParallelVisitor visitor(this);
707 // TODO: Tune this.
708 static const size_t kFifoSize = 4;
709 BoundedFifoPowerOfTwo<const Object*, kFifoSize> prefetch_fifo;
710 for (;;) {
711 const Object* obj = NULL;
712 if (kUseMarkStackPrefetch) {
713 while (mark_stack_pos_ != 0 && prefetch_fifo.size() < kFifoSize) {
714 const Object* obj = mark_stack_[--mark_stack_pos_];
715 DCHECK(obj != NULL);
716 __builtin_prefetch(obj);
717 prefetch_fifo.push_back(obj);
718 }
719 if (UNLIKELY(prefetch_fifo.empty())) {
720 break;
721 }
722 obj = prefetch_fifo.front();
723 prefetch_fifo.pop_front();
724 } else {
725 if (UNLIKELY(mark_stack_pos_ == 0)) {
726 break;
727 }
728 obj = mark_stack_[--mark_stack_pos_];
729 }
730 DCHECK(obj != NULL);
731 visitor(obj);
732 }
733 }
734};
735
736class CardScanTask : public MarkStackTask<false> {
737 public:
738 CardScanTask(ThreadPool* thread_pool, MarkSweep* mark_sweep, accounting::SpaceBitmap* bitmap,
739 byte* begin, byte* end, byte minimum_age, size_t mark_stack_size,
740 const Object** mark_stack_obj)
741 : MarkStackTask<false>(thread_pool, mark_sweep, mark_stack_size, mark_stack_obj),
742 bitmap_(bitmap),
743 begin_(begin),
744 end_(end),
745 minimum_age_(minimum_age) {
746 }
747
748 protected:
749 accounting::SpaceBitmap* const bitmap_;
750 byte* const begin_;
751 byte* const end_;
752 const byte minimum_age_;
753
754 virtual void Finalize() {
755 delete this;
756 }
757
758 virtual void Run(Thread* self) NO_THREAD_SAFETY_ANALYSIS {
759 ScanObjectParallelVisitor visitor(this);
760 accounting::CardTable* card_table = mark_sweep_->GetHeap()->GetCardTable();
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700761 size_t cards_scanned = card_table->Scan(bitmap_, begin_, end_, visitor, minimum_age_);
762 mark_sweep_->cards_scanned_.fetch_add(cards_scanned);
763 VLOG(heap) << "Parallel scanning cards " << reinterpret_cast<void*>(begin_) << " - "
764 << reinterpret_cast<void*>(end_) << " = " << cards_scanned;
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700765 // Finish by emptying our local mark stack.
766 MarkStackTask::Run(self);
767 }
768};
769
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700770size_t MarkSweep::GetThreadCount(bool paused) const {
771 if (heap_->GetThreadPool() == nullptr || !heap_->CareAboutPauseTimes()) {
772 return 0;
773 }
774 if (paused) {
775 return heap_->GetParallelGCThreadCount() + 1;
776 } else {
777 return heap_->GetConcGCThreadCount() + 1;
778 }
779}
780
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700781void MarkSweep::ScanGrayObjects(bool paused, byte minimum_age) {
782 accounting::CardTable* card_table = GetHeap()->GetCardTable();
783 ThreadPool* thread_pool = GetHeap()->GetThreadPool();
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700784 size_t thread_count = GetThreadCount(paused);
785 // The parallel version with only one thread is faster for card scanning, TODO: fix.
786 if (kParallelCardScan && thread_count > 0) {
Mathieu Chartier720ef762013-08-17 14:46:54 -0700787 Thread* self = Thread::Current();
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700788 // Can't have a different split for each space since multiple spaces can have their cards being
789 // scanned at the same time.
790 timings_.StartSplit(paused ? "(Paused)ScanGrayObjects" : "ScanGrayObjects");
791 // Try to take some of the mark stack since we can pass this off to the worker tasks.
792 const Object** mark_stack_begin = const_cast<const Object**>(mark_stack_->Begin());
793 const Object** mark_stack_end = const_cast<const Object**>(mark_stack_->End());
Mathieu Chartier720ef762013-08-17 14:46:54 -0700794 const size_t mark_stack_size = mark_stack_end - mark_stack_begin;
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700795 // Estimated number of work tasks we will create.
796 const size_t mark_stack_tasks = GetHeap()->GetContinuousSpaces().size() * thread_count;
797 DCHECK_NE(mark_stack_tasks, 0U);
798 const size_t mark_stack_delta = std::min(CardScanTask::kMaxSize / 2,
799 mark_stack_size / mark_stack_tasks + 1);
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700800 size_t ref_card_count = 0;
801 cards_scanned_ = 0;
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700802 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
803 byte* card_begin = space->Begin();
804 byte* card_end = space->End();
805 // 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));
820 DCHECK_EQ(mark_stack_end, mark_stack_->End());
821 // 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 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700828
829 if (paused && kIsDebugBuild) {
830 // Make sure we don't miss scanning any cards.
831 size_t scanned_cards = card_table->Scan(space->GetMarkBitmap(), space->Begin(),
832 space->End(), VoidFunctor(), minimum_age);
833 VLOG(heap) << "Scanning space cards " << reinterpret_cast<void*>(space->Begin()) << " - "
834 << reinterpret_cast<void*>(space->End()) << " = " << scanned_cards;
835 ref_card_count += scanned_cards;
836 }
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700837 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700838
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700839 thread_pool->SetMaxActiveWorkers(thread_count - 1);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700840 thread_pool->StartWorkers(self);
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700841 thread_pool->Wait(self, true, true);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700842 thread_pool->StopWorkers(self);
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700843 if (paused) {
844 DCHECK_EQ(ref_card_count, static_cast<size_t>(cards_scanned_.load()));
845 }
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700846 timings_.EndSplit();
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700847 } else {
848 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
849 // Image spaces are handled properly since live == marked for them.
850 switch (space->GetGcRetentionPolicy()) {
851 case space::kGcRetentionPolicyNeverCollect:
852 timings_.StartSplit(paused ? "(Paused)ScanGrayImageSpaceObjects" :
853 "ScanGrayImageSpaceObjects");
854 break;
855 case space::kGcRetentionPolicyFullCollect:
856 timings_.StartSplit(paused ? "(Paused)ScanGrayZygoteSpaceObjects" :
857 "ScanGrayZygoteSpaceObjects");
858 break;
859 case space::kGcRetentionPolicyAlwaysCollect:
860 timings_.StartSplit(paused ? "(Paused)ScanGrayAllocSpaceObjects" :
861 "ScanGrayAllocSpaceObjects");
862 break;
863 }
864 ScanObjectVisitor visitor(this);
865 card_table->Scan(space->GetMarkBitmap(), space->Begin(), space->End(), visitor, minimum_age);
866 timings_.EndSplit();
867 }
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700868 }
869}
870
871void MarkSweep::VerifyImageRoots() {
872 // Verify roots ensures that all the references inside the image space point
873 // objects which are either in the image space or marked objects in the alloc
874 // space
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700875 timings_.StartSplit("VerifyImageRoots");
Mathieu Chartier02e25112013-08-14 16:14:24 -0700876 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
877 if (space->IsImageSpace()) {
878 space::ImageSpace* image_space = space->AsImageSpace();
879 uintptr_t begin = reinterpret_cast<uintptr_t>(image_space->Begin());
880 uintptr_t end = reinterpret_cast<uintptr_t>(image_space->End());
881 accounting::SpaceBitmap* live_bitmap = image_space->GetLiveBitmap();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700882 DCHECK(live_bitmap != NULL);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700883 live_bitmap->VisitMarkedRange(begin, end, [this](const Object* obj) {
884 if (kCheckLocks) {
885 Locks::heap_bitmap_lock_->AssertSharedHeld(Thread::Current());
886 }
887 DCHECK(obj != NULL);
888 CheckObject(obj);
889 });
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700890 }
891 }
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700892 timings_.EndSplit();
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700893}
894
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700895class RecursiveMarkTask : public MarkStackTask<false> {
896 public:
897 RecursiveMarkTask(ThreadPool* thread_pool, MarkSweep* mark_sweep,
898 accounting::SpaceBitmap* bitmap, uintptr_t begin, uintptr_t end)
899 : MarkStackTask<false>(thread_pool, mark_sweep, 0, NULL),
900 bitmap_(bitmap),
901 begin_(begin),
902 end_(end) {
903 }
904
905 protected:
906 accounting::SpaceBitmap* const bitmap_;
907 const uintptr_t begin_;
908 const uintptr_t end_;
909
910 virtual void Finalize() {
911 delete this;
912 }
913
914 // Scans all of the objects
915 virtual void Run(Thread* self) NO_THREAD_SAFETY_ANALYSIS {
916 ScanObjectParallelVisitor visitor(this);
917 bitmap_->VisitMarkedRange(begin_, end_, visitor);
918 // Finish by emptying our local mark stack.
919 MarkStackTask::Run(self);
920 }
921};
922
Carl Shapiro58551df2011-07-24 03:09:51 -0700923// Populates the mark stack based on the set of marked objects and
924// recursively marks until the mark stack is emptied.
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800925void MarkSweep::RecursiveMark() {
Anwar Ghuloum46543222013-08-12 09:28:42 -0700926 base::TimingLogger::ScopedSplit split("RecursiveMark", &timings_);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700927 // RecursiveMark will build the lists of known instances of the Reference classes.
928 // See DelayReferenceReferent for details.
929 CHECK(soft_reference_list_ == NULL);
930 CHECK(weak_reference_list_ == NULL);
931 CHECK(finalizer_reference_list_ == NULL);
932 CHECK(phantom_reference_list_ == NULL);
933 CHECK(cleared_reference_list_ == NULL);
934
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700935 if (kUseRecursiveMark) {
936 const bool partial = GetGcType() == kGcTypePartial;
937 ScanObjectVisitor scan_visitor(this);
938 auto* self = Thread::Current();
939 ThreadPool* thread_pool = heap_->GetThreadPool();
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700940 size_t thread_count = GetThreadCount(false);
941 const bool parallel = kParallelRecursiveMark && thread_count > 1;
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700942 mark_stack_->Reset();
Mathieu Chartier02e25112013-08-14 16:14:24 -0700943 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700944 if ((space->GetGcRetentionPolicy() == space::kGcRetentionPolicyAlwaysCollect) ||
945 (!partial && space->GetGcRetentionPolicy() == space::kGcRetentionPolicyFullCollect)) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800946 current_mark_bitmap_ = space->GetMarkBitmap();
947 if (current_mark_bitmap_ == NULL) {
948 GetHeap()->DumpSpaces();
949 LOG(FATAL) << "invalid bitmap";
950 }
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700951 if (parallel) {
952 // We will use the mark stack the future.
953 // CHECK(mark_stack_->IsEmpty());
954 // This function does not handle heap end increasing, so we must use the space end.
955 uintptr_t begin = reinterpret_cast<uintptr_t>(space->Begin());
956 uintptr_t end = reinterpret_cast<uintptr_t>(space->End());
957 atomic_finger_ = static_cast<int32_t>(0xFFFFFFFF);
958
959 // Create a few worker tasks.
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700960 const size_t n = thread_count * 2;
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700961 while (begin != end) {
962 uintptr_t start = begin;
963 uintptr_t delta = (end - begin) / n;
964 delta = RoundUp(delta, KB);
965 if (delta < 16 * KB) delta = end - begin;
966 begin += delta;
967 auto* task = new RecursiveMarkTask(thread_pool, this, current_mark_bitmap_, start,
968 begin);
969 thread_pool->AddTask(self, task);
970 }
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700971 thread_pool->SetMaxActiveWorkers(thread_count - 1);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700972 thread_pool->StartWorkers(self);
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700973 thread_pool->Wait(self, true, true);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700974 thread_pool->StopWorkers(self);
975 } else {
976 // This function does not handle heap end increasing, so we must use the space end.
977 uintptr_t begin = reinterpret_cast<uintptr_t>(space->Begin());
978 uintptr_t end = reinterpret_cast<uintptr_t>(space->End());
979 current_mark_bitmap_->VisitMarkedRange(begin, end, scan_visitor);
980 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700981 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700982 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700983 }
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700984 ProcessMarkStack(false);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700985}
986
Mathieu Chartier6aa3df92013-09-17 15:17:28 -0700987mirror::Object* MarkSweep::SystemWeakIsMarkedCallback(Object* object, void* arg) {
Mathieu Chartier5712d5d2013-09-18 17:59:36 -0700988 if (reinterpret_cast<MarkSweep*>(arg)->IsMarked(object)) {
Mathieu Chartier6aa3df92013-09-17 15:17:28 -0700989 return object;
990 }
991 return nullptr;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700992}
993
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700994void MarkSweep::RecursiveMarkDirtyObjects(bool paused, byte minimum_age) {
995 ScanGrayObjects(paused, minimum_age);
996 ProcessMarkStack(paused);
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700997}
998
Carl Shapiro58551df2011-07-24 03:09:51 -0700999void MarkSweep::ReMarkRoots() {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001000 timings_.StartSplit("ReMarkRoots");
Mathieu Chartier423d2a32013-09-12 17:33:56 -07001001 Runtime::Current()->VisitRoots(MarkRootCallback, this, true, true);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001002 timings_.EndSplit();
Carl Shapiro69759ea2011-07-21 18:13:35 -07001003}
1004
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001005void MarkSweep::SweepSystemWeaks() {
1006 Runtime* runtime = Runtime::Current();
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001007 timings_.StartSplit("SweepSystemWeaks");
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001008 runtime->SweepSystemWeaks(SystemWeakIsMarkedCallback, this);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001009 timings_.EndSplit();
Carl Shapiro58551df2011-07-24 03:09:51 -07001010}
1011
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001012mirror::Object* MarkSweep::VerifySystemWeakIsLiveCallback(Object* obj, void* arg) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001013 reinterpret_cast<MarkSweep*>(arg)->VerifyIsLive(obj);
1014 // We don't actually want to sweep the object, so lets return "marked"
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001015 return obj;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001016}
1017
1018void MarkSweep::VerifyIsLive(const Object* obj) {
1019 Heap* heap = GetHeap();
1020 if (!heap->GetLiveBitmap()->Test(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001021 space::LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001022 if (!large_object_space->GetLiveObjects()->Test(obj)) {
1023 if (std::find(heap->allocation_stack_->Begin(), heap->allocation_stack_->End(), obj) ==
1024 heap->allocation_stack_->End()) {
1025 // Object not found!
1026 heap->DumpSpaces();
1027 LOG(FATAL) << "Found dead object " << obj;
1028 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001029 }
1030 }
1031}
1032
1033void MarkSweep::VerifySystemWeaks() {
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001034 // Verify system weaks, uses a special object visitor which returns the input object.
1035 Runtime::Current()->SweepSystemWeaks(VerifySystemWeakIsLiveCallback, this);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001036}
1037
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001038struct SweepCallbackContext {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001039 MarkSweep* mark_sweep;
Ian Rogers1d54e732013-05-02 21:10:01 -07001040 space::AllocSpace* space;
Ian Rogers50b35e22012-10-04 10:09:15 -07001041 Thread* self;
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001042};
1043
Mathieu Chartier0e4627e2012-10-23 16:13:36 -07001044class CheckpointMarkThreadRoots : public Closure {
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001045 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001046 explicit CheckpointMarkThreadRoots(MarkSweep* mark_sweep) : mark_sweep_(mark_sweep) {}
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001047
1048 virtual void Run(Thread* thread) NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier3f966702013-09-04 16:50:05 -07001049 ATRACE_BEGIN("Marking thread roots");
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001050 // Note: self is not necessarily equal to thread since thread may be suspended.
1051 Thread* self = Thread::Current();
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001052 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
1053 << thread->GetState() << " thread " << thread << " self " << self;
Mathieu Chartierac86a7c2012-11-12 15:03:16 -08001054 thread->VisitRoots(MarkSweep::MarkRootParallelCallback, mark_sweep_);
Mathieu Chartier3f966702013-09-04 16:50:05 -07001055 ATRACE_END();
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001056 mark_sweep_->GetBarrier().Pass(self);
1057 }
1058
1059 private:
1060 MarkSweep* mark_sweep_;
1061};
1062
Ian Rogers1d54e732013-05-02 21:10:01 -07001063void MarkSweep::MarkRootsCheckpoint(Thread* self) {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001064 CheckpointMarkThreadRoots check_point(this);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001065 timings_.StartSplit("MarkRootsCheckpoint");
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001066 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Ian Rogers1d54e732013-05-02 21:10:01 -07001067 // Request the check point is run on all threads returning a count of the threads that must
1068 // run through the barrier including self.
1069 size_t barrier_count = thread_list->RunCheckpoint(&check_point);
1070 // Release locks then wait for all mutator threads to pass the barrier.
1071 // TODO: optimize to not release locks when there are no threads to wait for.
1072 Locks::heap_bitmap_lock_->ExclusiveUnlock(self);
1073 Locks::mutator_lock_->SharedUnlock(self);
1074 ThreadState old_state = self->SetState(kWaitingForCheckPointsToRun);
1075 CHECK_EQ(old_state, kWaitingPerformingGc);
1076 gc_barrier_->Increment(self, barrier_count);
1077 self->SetState(kWaitingPerformingGc);
1078 Locks::mutator_lock_->SharedLock(self);
1079 Locks::heap_bitmap_lock_->ExclusiveLock(self);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001080 timings_.EndSplit();
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001081}
1082
Ian Rogers30fab402012-01-23 15:43:46 -08001083void MarkSweep::SweepCallback(size_t num_ptrs, Object** ptrs, void* arg) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001084 SweepCallbackContext* context = static_cast<SweepCallbackContext*>(arg);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001085 MarkSweep* mark_sweep = context->mark_sweep;
1086 Heap* heap = mark_sweep->GetHeap();
Ian Rogers1d54e732013-05-02 21:10:01 -07001087 space::AllocSpace* space = context->space;
Ian Rogers50b35e22012-10-04 10:09:15 -07001088 Thread* self = context->self;
1089 Locks::heap_bitmap_lock_->AssertExclusiveHeld(self);
Ian Rogers5d76c432011-10-31 21:42:49 -07001090 // Use a bulk free, that merges consecutive objects before freeing or free per object?
1091 // Documentation suggests better free performance with merging, but this may be at the expensive
1092 // of allocation.
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001093 size_t freed_objects = num_ptrs;
1094 // AllocSpace::FreeList clears the value in ptrs, so perform after clearing the live bit
1095 size_t freed_bytes = space->FreeList(self, num_ptrs, ptrs);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001096 heap->RecordFree(freed_objects, freed_bytes);
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -07001097 mark_sweep->freed_objects_.fetch_add(freed_objects);
1098 mark_sweep->freed_bytes_.fetch_add(freed_bytes);
Carl Shapiro58551df2011-07-24 03:09:51 -07001099}
1100
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001101void MarkSweep::ZygoteSweepCallback(size_t num_ptrs, Object** ptrs, void* arg) {
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001102 SweepCallbackContext* context = static_cast<SweepCallbackContext*>(arg);
Ian Rogers50b35e22012-10-04 10:09:15 -07001103 Locks::heap_bitmap_lock_->AssertExclusiveHeld(context->self);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001104 Heap* heap = context->mark_sweep->GetHeap();
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001105 // We don't free any actual memory to avoid dirtying the shared zygote pages.
1106 for (size_t i = 0; i < num_ptrs; ++i) {
1107 Object* obj = static_cast<Object*>(ptrs[i]);
1108 heap->GetLiveBitmap()->Clear(obj);
1109 heap->GetCardTable()->MarkCard(obj);
1110 }
1111}
1112
Ian Rogers1d54e732013-05-02 21:10:01 -07001113void MarkSweep::SweepArray(accounting::ObjectStack* allocations, bool swap_bitmaps) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001114 space::DlMallocSpace* space = heap_->GetAllocSpace();
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001115 timings_.StartSplit("SweepArray");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001116 // Newly allocated objects MUST be in the alloc space and those are the only objects which we are
1117 // going to free.
Ian Rogers1d54e732013-05-02 21:10:01 -07001118 accounting::SpaceBitmap* live_bitmap = space->GetLiveBitmap();
1119 accounting::SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
1120 space::LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
1121 accounting::SpaceSetMap* large_live_objects = large_object_space->GetLiveObjects();
1122 accounting::SpaceSetMap* large_mark_objects = large_object_space->GetMarkObjects();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001123 if (swap_bitmaps) {
1124 std::swap(live_bitmap, mark_bitmap);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001125 std::swap(large_live_objects, large_mark_objects);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001126 }
1127
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001128 size_t freed_bytes = 0;
1129 size_t freed_large_object_bytes = 0;
Hiroshi Yamauchib22a4512013-08-13 15:03:22 -07001130 size_t freed_objects = 0;
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001131 size_t freed_large_objects = 0;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001132 size_t count = allocations->Size();
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001133 Object** objects = const_cast<Object**>(allocations->Begin());
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001134 Object** out = objects;
Hiroshi Yamauchib22a4512013-08-13 15:03:22 -07001135 Object** objects_to_chunk_free = out;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001136
1137 // Empty the allocation stack.
Ian Rogers50b35e22012-10-04 10:09:15 -07001138 Thread* self = Thread::Current();
Brian Carlstrom02c8cc62013-07-18 15:54:44 -07001139 for (size_t i = 0; i < count; ++i) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001140 Object* obj = objects[i];
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001141 // There should only be objects in the AllocSpace/LargeObjectSpace in the allocation stack.
1142 if (LIKELY(mark_bitmap->HasAddress(obj))) {
1143 if (!mark_bitmap->Test(obj)) {
1144 // Don't bother un-marking since we clear the mark bitmap anyways.
1145 *(out++) = obj;
Hiroshi Yamauchib22a4512013-08-13 15:03:22 -07001146 // Free objects in chunks.
1147 DCHECK_GE(out, objects_to_chunk_free);
1148 DCHECK_LE(static_cast<size_t>(out - objects_to_chunk_free), kSweepArrayChunkFreeSize);
1149 if (static_cast<size_t>(out - objects_to_chunk_free) == kSweepArrayChunkFreeSize) {
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001150 timings_.StartSplit("FreeList");
Hiroshi Yamauchib22a4512013-08-13 15:03:22 -07001151 size_t chunk_freed_objects = out - objects_to_chunk_free;
1152 freed_objects += chunk_freed_objects;
1153 freed_bytes += space->FreeList(self, chunk_freed_objects, objects_to_chunk_free);
1154 objects_to_chunk_free = out;
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001155 timings_.EndSplit();
Hiroshi Yamauchib22a4512013-08-13 15:03:22 -07001156 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001157 }
1158 } else if (!large_mark_objects->Test(obj)) {
1159 ++freed_large_objects;
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001160 freed_large_object_bytes += large_object_space->Free(self, obj);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001161 }
1162 }
Hiroshi Yamauchib22a4512013-08-13 15:03:22 -07001163 // Free the remaining objects in chunks.
1164 DCHECK_GE(out, objects_to_chunk_free);
1165 DCHECK_LE(static_cast<size_t>(out - objects_to_chunk_free), kSweepArrayChunkFreeSize);
1166 if (out - objects_to_chunk_free > 0) {
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001167 timings_.StartSplit("FreeList");
Hiroshi Yamauchib22a4512013-08-13 15:03:22 -07001168 size_t chunk_freed_objects = out - objects_to_chunk_free;
1169 freed_objects += chunk_freed_objects;
1170 freed_bytes += space->FreeList(self, chunk_freed_objects, objects_to_chunk_free);
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001171 timings_.EndSplit();
Hiroshi Yamauchib22a4512013-08-13 15:03:22 -07001172 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001173 CHECK_EQ(count, allocations->Size());
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001174 timings_.EndSplit();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001175
Hiroshi Yamauchib22a4512013-08-13 15:03:22 -07001176 timings_.StartSplit("RecordFree");
Mathieu Chartier40e978b2012-09-07 11:38:36 -07001177 VLOG(heap) << "Freed " << freed_objects << "/" << count
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001178 << " objects with size " << PrettySize(freed_bytes);
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001179 heap_->RecordFree(freed_objects + freed_large_objects, freed_bytes + freed_large_object_bytes);
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -07001180 freed_objects_.fetch_add(freed_objects);
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001181 freed_large_objects_.fetch_add(freed_large_objects);
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -07001182 freed_bytes_.fetch_add(freed_bytes);
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001183 freed_large_object_bytes_.fetch_add(freed_large_object_bytes);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001184 timings_.EndSplit();
Ian Rogers1d54e732013-05-02 21:10:01 -07001185
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001186 timings_.StartSplit("ResetStack");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001187 allocations->Reset();
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001188 timings_.EndSplit();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001189}
1190
Ian Rogers1d54e732013-05-02 21:10:01 -07001191void MarkSweep::Sweep(bool swap_bitmaps) {
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001192 DCHECK(mark_stack_->IsEmpty());
Anwar Ghuloum46543222013-08-12 09:28:42 -07001193 base::TimingLogger::ScopedSplit("Sweep", &timings_);
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001194
Ian Rogers1d54e732013-05-02 21:10:01 -07001195 const bool partial = (GetGcType() == kGcTypePartial);
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001196 SweepCallbackContext scc;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001197 scc.mark_sweep = this;
Ian Rogers50b35e22012-10-04 10:09:15 -07001198 scc.self = Thread::Current();
Mathieu Chartier02e25112013-08-14 16:14:24 -07001199 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001200 // We always sweep always collect spaces.
1201 bool sweep_space = (space->GetGcRetentionPolicy() == space::kGcRetentionPolicyAlwaysCollect);
1202 if (!partial && !sweep_space) {
1203 // We sweep full collect spaces when the GC isn't a partial GC (ie its full).
1204 sweep_space = (space->GetGcRetentionPolicy() == space::kGcRetentionPolicyFullCollect);
1205 }
1206 if (sweep_space) {
Mathieu Chartier720ef762013-08-17 14:46:54 -07001207 uintptr_t begin = reinterpret_cast<uintptr_t>(space->Begin());
1208 uintptr_t end = reinterpret_cast<uintptr_t>(space->End());
Ian Rogers1d54e732013-05-02 21:10:01 -07001209 scc.space = space->AsDlMallocSpace();
1210 accounting::SpaceBitmap* live_bitmap = space->GetLiveBitmap();
1211 accounting::SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001212 if (swap_bitmaps) {
1213 std::swap(live_bitmap, mark_bitmap);
1214 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001215 if (!space->IsZygoteSpace()) {
Anwar Ghuloum46543222013-08-12 09:28:42 -07001216 base::TimingLogger::ScopedSplit split("SweepAllocSpace", &timings_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001217 // Bitmaps are pre-swapped for optimization which enables sweeping with the heap unlocked.
Ian Rogers1d54e732013-05-02 21:10:01 -07001218 accounting::SpaceBitmap::SweepWalk(*live_bitmap, *mark_bitmap, begin, end,
1219 &SweepCallback, reinterpret_cast<void*>(&scc));
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001220 } else {
Anwar Ghuloum46543222013-08-12 09:28:42 -07001221 base::TimingLogger::ScopedSplit split("SweepZygote", &timings_);
Ian Rogers1d54e732013-05-02 21:10:01 -07001222 // Zygote sweep takes care of dirtying cards and clearing live bits, does not free actual
1223 // memory.
1224 accounting::SpaceBitmap::SweepWalk(*live_bitmap, *mark_bitmap, begin, end,
1225 &ZygoteSweepCallback, reinterpret_cast<void*>(&scc));
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001226 }
Carl Shapiro58551df2011-07-24 03:09:51 -07001227 }
1228 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001229
1230 SweepLargeObjects(swap_bitmaps);
Carl Shapiro58551df2011-07-24 03:09:51 -07001231}
1232
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001233void MarkSweep::SweepLargeObjects(bool swap_bitmaps) {
Anwar Ghuloum46543222013-08-12 09:28:42 -07001234 base::TimingLogger::ScopedSplit("SweepLargeObjects", &timings_);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001235 // Sweep large objects
Ian Rogers1d54e732013-05-02 21:10:01 -07001236 space::LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
1237 accounting::SpaceSetMap* large_live_objects = large_object_space->GetLiveObjects();
1238 accounting::SpaceSetMap* large_mark_objects = large_object_space->GetMarkObjects();
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001239 if (swap_bitmaps) {
1240 std::swap(large_live_objects, large_mark_objects);
1241 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001242 // O(n*log(n)) but hopefully there are not too many large objects.
1243 size_t freed_objects = 0;
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001244 size_t freed_bytes = 0;
Ian Rogers50b35e22012-10-04 10:09:15 -07001245 Thread* self = Thread::Current();
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001246 for (const Object* obj : large_live_objects->GetObjects()) {
Mathieu Chartier02e25112013-08-14 16:14:24 -07001247 if (!large_mark_objects->Test(obj)) {
1248 freed_bytes += large_object_space->Free(self, const_cast<Object*>(obj));
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001249 ++freed_objects;
1250 }
1251 }
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001252 freed_large_objects_.fetch_add(freed_objects);
1253 freed_large_object_bytes_.fetch_add(freed_bytes);
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001254 GetHeap()->RecordFree(freed_objects, freed_bytes);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001255}
1256
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001257void MarkSweep::CheckReference(const Object* obj, const Object* ref, MemberOffset offset, bool is_static) {
Mathieu Chartier02e25112013-08-14 16:14:24 -07001258 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001259 if (space->IsDlMallocSpace() && space->Contains(ref)) {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001260 DCHECK(IsMarked(obj));
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001261
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001262 bool is_marked = IsMarked(ref);
1263 if (!is_marked) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001264 LOG(INFO) << *space;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001265 LOG(WARNING) << (is_static ? "Static ref'" : "Instance ref'") << PrettyTypeOf(ref)
1266 << "' (" << reinterpret_cast<const void*>(ref) << ") in '" << PrettyTypeOf(obj)
1267 << "' (" << reinterpret_cast<const void*>(obj) << ") at offset "
1268 << reinterpret_cast<void*>(offset.Int32Value()) << " wasn't marked";
Mathieu Chartier262e5ff2012-06-01 17:35:38 -07001269
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001270 const Class* klass = is_static ? obj->AsClass() : obj->GetClass();
1271 DCHECK(klass != NULL);
Brian Carlstromea46f952013-07-30 01:26:50 -07001272 const ObjectArray<ArtField>* fields = is_static ? klass->GetSFields() : klass->GetIFields();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001273 DCHECK(fields != NULL);
1274 bool found = false;
1275 for (int32_t i = 0; i < fields->GetLength(); ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001276 const ArtField* cur = fields->Get(i);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001277 if (cur->GetOffset().Int32Value() == offset.Int32Value()) {
1278 LOG(WARNING) << "Field referencing the alloc space was " << PrettyField(cur);
1279 found = true;
1280 break;
1281 }
1282 }
1283 if (!found) {
1284 LOG(WARNING) << "Could not find field in object alloc space with offset " << offset.Int32Value();
1285 }
Mathieu Chartier262e5ff2012-06-01 17:35:38 -07001286
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001287 bool obj_marked = heap_->GetCardTable()->IsDirty(obj);
1288 if (!obj_marked) {
1289 LOG(WARNING) << "Object '" << PrettyTypeOf(obj) << "' "
1290 << "(" << reinterpret_cast<const void*>(obj) << ") contains references to "
1291 << "the alloc space, but wasn't card marked";
Mathieu Chartier262e5ff2012-06-01 17:35:38 -07001292 }
1293 }
Ian Rogers5d76c432011-10-31 21:42:49 -07001294 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001295 break;
Ian Rogers5d76c432011-10-31 21:42:49 -07001296 }
1297}
1298
Carl Shapiro69759ea2011-07-21 18:13:35 -07001299// Process the "referent" field in a java.lang.ref.Reference. If the
1300// referent has not yet been marked, put it on the appropriate list in
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001301// the heap for later processing.
1302void MarkSweep::DelayReferenceReferent(mirror::Class* klass, Object* obj) {
1303 DCHECK(klass != nullptr);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001304 DCHECK(klass->IsReferenceClass());
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001305 DCHECK(obj != NULL);
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001306 Object* referent = heap_->GetReferenceReferent(obj);
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001307 if (referent != NULL && !IsMarked(referent)) {
1308 if (kCountJavaLangRefs) {
1309 ++reference_count_;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001310 }
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001311 Thread* self = Thread::Current();
1312 // TODO: Remove these locks, and use atomic stacks for storing references?
Mathieu Chartierb4ea4de2013-09-18 09:58:29 -07001313 // We need to check that the references haven't already been enqueued since we can end up
1314 // scanning the same reference multiple times due to dirty cards.
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001315 if (klass->IsSoftReferenceClass()) {
1316 MutexLock mu(self, *heap_->GetSoftRefQueueLock());
Mathieu Chartierb4ea4de2013-09-18 09:58:29 -07001317 if (!heap_->IsEnqueued(obj)) {
1318 heap_->EnqueuePendingReference(obj, &soft_reference_list_);
1319 }
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001320 } else if (klass->IsWeakReferenceClass()) {
1321 MutexLock mu(self, *heap_->GetWeakRefQueueLock());
Mathieu Chartierb4ea4de2013-09-18 09:58:29 -07001322 if (!heap_->IsEnqueued(obj)) {
1323 heap_->EnqueuePendingReference(obj, &weak_reference_list_);
1324 }
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001325 } else if (klass->IsFinalizerReferenceClass()) {
1326 MutexLock mu(self, *heap_->GetFinalizerRefQueueLock());
Mathieu Chartierb4ea4de2013-09-18 09:58:29 -07001327 if (!heap_->IsEnqueued(obj)) {
1328 heap_->EnqueuePendingReference(obj, &finalizer_reference_list_);
1329 }
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001330 } else if (klass->IsPhantomReferenceClass()) {
1331 MutexLock mu(self, *heap_->GetPhantomRefQueueLock());
Mathieu Chartierb4ea4de2013-09-18 09:58:29 -07001332 if (!heap_->IsEnqueued(obj)) {
1333 heap_->EnqueuePendingReference(obj, &phantom_reference_list_);
1334 }
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001335 } else {
1336 LOG(FATAL) << "Invalid reference type " << PrettyClass(klass)
1337 << " " << std::hex << klass->GetAccessFlags();
1338 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001339 }
1340}
1341
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001342void MarkSweep::ScanRoot(const Object* obj) {
1343 ScanObject(obj);
1344}
1345
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001346class MarkObjectVisitor {
1347 public:
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001348 explicit MarkObjectVisitor(MarkSweep* const mark_sweep) ALWAYS_INLINE : mark_sweep_(mark_sweep) {}
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001349
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001350 // TODO: Fixme when anotatalysis works with visitors.
Brian Carlstromdf629502013-07-17 22:39:56 -07001351 void operator()(const Object* /* obj */, const Object* ref, const MemberOffset& /* offset */,
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001352 bool /* is_static */) const ALWAYS_INLINE
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001353 NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001354 if (kCheckLocks) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001355 Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
1356 Locks::heap_bitmap_lock_->AssertExclusiveHeld(Thread::Current());
1357 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001358 mark_sweep_->MarkObject(ref);
1359 }
1360
1361 private:
1362 MarkSweep* const mark_sweep_;
1363};
1364
Carl Shapiro69759ea2011-07-21 18:13:35 -07001365// Scans an object reference. Determines the type of the reference
1366// and dispatches to a specialized scanning routine.
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001367void MarkSweep::ScanObject(const Object* obj) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001368 MarkObjectVisitor visitor(this);
1369 ScanObjectVisit(obj, visitor);
1370}
1371
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001372void MarkSweep::ProcessMarkStackParallel(size_t thread_count) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001373 Thread* self = Thread::Current();
1374 ThreadPool* thread_pool = GetHeap()->GetThreadPool();
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001375 const size_t chunk_size = std::min(mark_stack_->Size() / thread_count + 1,
1376 static_cast<size_t>(MarkStackTask<false>::kMaxSize));
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001377 CHECK_GT(chunk_size, 0U);
1378 // Split the current mark stack up into work tasks.
1379 for (mirror::Object **it = mark_stack_->Begin(), **end = mark_stack_->End(); it < end; ) {
1380 const size_t delta = std::min(static_cast<size_t>(end - it), chunk_size);
1381 thread_pool->AddTask(self, new MarkStackTask<false>(thread_pool, this, delta,
1382 const_cast<const mirror::Object**>(it)));
1383 it += delta;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001384 }
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001385 thread_pool->SetMaxActiveWorkers(thread_count - 1);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001386 thread_pool->StartWorkers(self);
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001387 thread_pool->Wait(self, true, true);
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001388 thread_pool->StopWorkers(self);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001389 mark_stack_->Reset();
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001390 CHECK_EQ(work_chunks_created_, work_chunks_deleted_) << " some of the work chunks were leaked";
Carl Shapiro69759ea2011-07-21 18:13:35 -07001391}
1392
Ian Rogers5d76c432011-10-31 21:42:49 -07001393// Scan anything that's on the mark stack.
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001394void MarkSweep::ProcessMarkStack(bool paused) {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001395 timings_.StartSplit("ProcessMarkStack");
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001396 size_t thread_count = GetThreadCount(paused);
1397 if (kParallelProcessMarkStack && thread_count > 1 &&
1398 mark_stack_->Size() >= kMinimumParallelMarkStackSize) {
1399 ProcessMarkStackParallel(thread_count);
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001400 } else {
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001401 // TODO: Tune this.
1402 static const size_t kFifoSize = 4;
1403 BoundedFifoPowerOfTwo<const Object*, kFifoSize> prefetch_fifo;
1404 for (;;) {
1405 const Object* obj = NULL;
1406 if (kUseMarkStackPrefetch) {
1407 while (!mark_stack_->IsEmpty() && prefetch_fifo.size() < kFifoSize) {
1408 const Object* obj = mark_stack_->PopBack();
1409 DCHECK(obj != NULL);
1410 __builtin_prefetch(obj);
1411 prefetch_fifo.push_back(obj);
1412 }
1413 if (prefetch_fifo.empty()) {
1414 break;
1415 }
1416 obj = prefetch_fifo.front();
1417 prefetch_fifo.pop_front();
1418 } else {
1419 if (mark_stack_->IsEmpty()) {
1420 break;
1421 }
1422 obj = mark_stack_->PopBack();
1423 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001424 DCHECK(obj != NULL);
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001425 ScanObject(obj);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001426 }
1427 }
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001428 timings_.EndSplit();
Carl Shapiro69759ea2011-07-21 18:13:35 -07001429}
1430
Carl Shapiro69759ea2011-07-21 18:13:35 -07001431// Walks the reference list marking any references subject to the
1432// reference clearing policy. References with a black referent are
1433// removed from the list. References with white referents biased
1434// toward saving are blackened and also removed from the list.
1435void MarkSweep::PreserveSomeSoftReferences(Object** list) {
1436 DCHECK(list != NULL);
1437 Object* clear = NULL;
1438 size_t counter = 0;
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001439
1440 DCHECK(mark_stack_->IsEmpty());
1441
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001442 timings_.StartSplit("PreserveSomeSoftReferences");
Carl Shapiro69759ea2011-07-21 18:13:35 -07001443 while (*list != NULL) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001444 Object* ref = heap_->DequeuePendingReference(list);
1445 Object* referent = heap_->GetReferenceReferent(ref);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001446 if (referent == NULL) {
1447 // Referent was cleared by the user during marking.
1448 continue;
1449 }
1450 bool is_marked = IsMarked(referent);
1451 if (!is_marked && ((++counter) & 1)) {
1452 // Referent is white and biased toward saving, mark it.
1453 MarkObject(referent);
1454 is_marked = true;
1455 }
1456 if (!is_marked) {
1457 // Referent is white, queue it for clearing.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001458 heap_->EnqueuePendingReference(ref, &clear);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001459 }
1460 }
1461 *list = clear;
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001462 timings_.EndSplit();
1463
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001464 // Restart the mark with the newly black references added to the root set.
1465 ProcessMarkStack(true);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001466}
1467
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001468inline bool MarkSweep::IsMarked(const Object* object) const
1469 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
Mathieu Chartier9642c962013-08-05 17:40:36 -07001470 if (IsImmune(object)) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001471 return true;
1472 }
1473 DCHECK(current_mark_bitmap_ != NULL);
1474 if (current_mark_bitmap_->HasAddress(object)) {
1475 return current_mark_bitmap_->Test(object);
1476 }
1477 return heap_->GetMarkBitmap()->Test(object);
1478}
1479
Carl Shapiro69759ea2011-07-21 18:13:35 -07001480// Unlink the reference list clearing references objects with white
1481// referents. Cleared references registered to a reference queue are
1482// scheduled for appending by the heap worker thread.
1483void MarkSweep::ClearWhiteReferences(Object** list) {
1484 DCHECK(list != NULL);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001485 while (*list != NULL) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001486 Object* ref = heap_->DequeuePendingReference(list);
1487 Object* referent = heap_->GetReferenceReferent(ref);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001488 if (referent != NULL && !IsMarked(referent)) {
1489 // Referent is white, clear it.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001490 heap_->ClearReferenceReferent(ref);
1491 if (heap_->IsEnqueuable(ref)) {
1492 heap_->EnqueueReference(ref, &cleared_reference_list_);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001493 }
1494 }
1495 }
1496 DCHECK(*list == NULL);
1497}
1498
1499// Enqueues finalizer references with white referents. White
1500// referents are blackened, moved to the zombie field, and the
1501// referent field is cleared.
1502void MarkSweep::EnqueueFinalizerReferences(Object** list) {
1503 DCHECK(list != NULL);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001504 timings_.StartSplit("EnqueueFinalizerReferences");
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001505 MemberOffset zombie_offset = heap_->GetFinalizerReferenceZombieOffset();
Carl Shapiro69759ea2011-07-21 18:13:35 -07001506 bool has_enqueued = false;
1507 while (*list != NULL) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001508 Object* ref = heap_->DequeuePendingReference(list);
1509 Object* referent = heap_->GetReferenceReferent(ref);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001510 if (referent != NULL && !IsMarked(referent)) {
1511 MarkObject(referent);
1512 // If the referent is non-null the reference must queuable.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001513 DCHECK(heap_->IsEnqueuable(ref));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001514 ref->SetFieldObject(zombie_offset, referent, false);
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001515 heap_->ClearReferenceReferent(ref);
1516 heap_->EnqueueReference(ref, &cleared_reference_list_);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001517 has_enqueued = true;
1518 }
1519 }
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001520 timings_.EndSplit();
Carl Shapiro69759ea2011-07-21 18:13:35 -07001521 if (has_enqueued) {
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001522 ProcessMarkStack(true);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001523 }
1524 DCHECK(*list == NULL);
1525}
1526
Carl Shapiro58551df2011-07-24 03:09:51 -07001527// Process reference class instances and schedule finalizations.
Carl Shapiro69759ea2011-07-21 18:13:35 -07001528void MarkSweep::ProcessReferences(Object** soft_references, bool clear_soft,
1529 Object** weak_references,
1530 Object** finalizer_references,
1531 Object** phantom_references) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001532 CHECK(soft_references != NULL);
1533 CHECK(weak_references != NULL);
1534 CHECK(finalizer_references != NULL);
1535 CHECK(phantom_references != NULL);
1536 CHECK(mark_stack_->IsEmpty());
Carl Shapiro69759ea2011-07-21 18:13:35 -07001537
1538 // Unless we are in the zygote or required to clear soft references
1539 // with white references, preserve some white referents.
Ian Rogers2945e242012-06-03 14:45:16 -07001540 if (!clear_soft && !Runtime::Current()->IsZygote()) {
Carl Shapiro69759ea2011-07-21 18:13:35 -07001541 PreserveSomeSoftReferences(soft_references);
1542 }
1543
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001544 timings_.StartSplit("ProcessReferences");
Carl Shapiro69759ea2011-07-21 18:13:35 -07001545 // Clear all remaining soft and weak references with white
1546 // referents.
1547 ClearWhiteReferences(soft_references);
1548 ClearWhiteReferences(weak_references);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001549 timings_.EndSplit();
Carl Shapiro69759ea2011-07-21 18:13:35 -07001550
1551 // Preserve all white objects with finalize methods and schedule
1552 // them for finalization.
1553 EnqueueFinalizerReferences(finalizer_references);
1554
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001555 timings_.StartSplit("ProcessReferences");
Carl Shapiro69759ea2011-07-21 18:13:35 -07001556 // Clear all f-reachable soft and weak references with white
1557 // referents.
1558 ClearWhiteReferences(soft_references);
1559 ClearWhiteReferences(weak_references);
1560
1561 // Clear all phantom references with white referents.
1562 ClearWhiteReferences(phantom_references);
1563
1564 // At this point all reference lists should be empty.
1565 DCHECK(*soft_references == NULL);
1566 DCHECK(*weak_references == NULL);
1567 DCHECK(*finalizer_references == NULL);
1568 DCHECK(*phantom_references == NULL);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001569 timings_.EndSplit();
Carl Shapiro69759ea2011-07-21 18:13:35 -07001570}
1571
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001572void MarkSweep::UnBindBitmaps() {
Anwar Ghuloum46543222013-08-12 09:28:42 -07001573 base::TimingLogger::ScopedSplit split("UnBindBitmaps", &timings_);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001574 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001575 if (space->IsDlMallocSpace()) {
1576 space::DlMallocSpace* alloc_space = space->AsDlMallocSpace();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001577 if (alloc_space->temp_bitmap_.get() != NULL) {
1578 // At this point, the temp_bitmap holds our old mark bitmap.
Ian Rogers1d54e732013-05-02 21:10:01 -07001579 accounting::SpaceBitmap* new_bitmap = alloc_space->temp_bitmap_.release();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001580 GetHeap()->GetMarkBitmap()->ReplaceBitmap(alloc_space->mark_bitmap_.get(), new_bitmap);
1581 CHECK_EQ(alloc_space->mark_bitmap_.release(), alloc_space->live_bitmap_.get());
1582 alloc_space->mark_bitmap_.reset(new_bitmap);
1583 DCHECK(alloc_space->temp_bitmap_.get() == NULL);
1584 }
1585 }
1586 }
1587}
1588
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001589void MarkSweep::FinishPhase() {
Anwar Ghuloum46543222013-08-12 09:28:42 -07001590 base::TimingLogger::ScopedSplit split("FinishPhase", &timings_);
1591 // Can't enqueue references if we hold the mutator lock.
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001592 Object* cleared_references = GetClearedReferences();
Ian Rogers1d54e732013-05-02 21:10:01 -07001593 Heap* heap = GetHeap();
Anwar Ghuloum46543222013-08-12 09:28:42 -07001594 timings_.NewSplit("EnqueueClearedReferences");
Ian Rogers1d54e732013-05-02 21:10:01 -07001595 heap->EnqueueClearedReferences(&cleared_references);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001596
Anwar Ghuloum46543222013-08-12 09:28:42 -07001597 timings_.NewSplit("PostGcVerification");
Ian Rogers1d54e732013-05-02 21:10:01 -07001598 heap->PostGcVerification(this);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001599
Anwar Ghuloum46543222013-08-12 09:28:42 -07001600 timings_.NewSplit("GrowForUtilization");
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001601 heap->GrowForUtilization(GetGcType(), GetDurationNs());
Mathieu Chartier65db8802012-11-20 12:36:46 -08001602
Anwar Ghuloum46543222013-08-12 09:28:42 -07001603 timings_.NewSplit("RequestHeapTrim");
Ian Rogers1d54e732013-05-02 21:10:01 -07001604 heap->RequestHeapTrim();
Mathieu Chartier65db8802012-11-20 12:36:46 -08001605
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001606 // Update the cumulative statistics
Ian Rogers1d54e732013-05-02 21:10:01 -07001607 total_time_ns_ += GetDurationNs();
1608 total_paused_time_ns_ += std::accumulate(GetPauseTimes().begin(), GetPauseTimes().end(), 0,
1609 std::plus<uint64_t>());
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001610 total_freed_objects_ += GetFreedObjects() + GetFreedLargeObjects();
1611 total_freed_bytes_ += GetFreedBytes() + GetFreedLargeObjectBytes();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001612
1613 // Ensure that the mark stack is empty.
1614 CHECK(mark_stack_->IsEmpty());
1615
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001616 if (kCountScannedTypes) {
1617 VLOG(gc) << "MarkSweep scanned classes=" << class_count_ << " arrays=" << array_count_
1618 << " other=" << other_count_;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001619 }
1620
1621 if (kCountTasks) {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001622 VLOG(gc) << "Total number of work chunks allocated: " << work_chunks_created_;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001623 }
1624
1625 if (kMeasureOverhead) {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001626 VLOG(gc) << "Overhead time " << PrettyDuration(overhead_time_);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001627 }
1628
1629 if (kProfileLargeObjects) {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001630 VLOG(gc) << "Large objects tested " << large_object_test_ << " marked " << large_object_mark_;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001631 }
1632
1633 if (kCountClassesMarked) {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001634 VLOG(gc) << "Classes marked " << classes_marked_;
1635 }
1636
1637 if (kCountJavaLangRefs) {
1638 VLOG(gc) << "References scanned " << reference_count_;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001639 }
1640
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001641 // Update the cumulative loggers.
1642 cumulative_timings_.Start();
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001643 cumulative_timings_.AddLogger(timings_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001644 cumulative_timings_.End();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001645
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001646 // Clear all of the spaces' mark bitmaps.
Mathieu Chartier02e25112013-08-14 16:14:24 -07001647 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001648 if (space->GetGcRetentionPolicy() != space::kGcRetentionPolicyNeverCollect) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001649 space->GetMarkBitmap()->Clear();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001650 }
1651 }
Mathieu Chartier5301cd22012-05-31 12:11:36 -07001652 mark_stack_->Reset();
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001653
1654 // Reset the marked large objects.
Ian Rogers1d54e732013-05-02 21:10:01 -07001655 space::LargeObjectSpace* large_objects = GetHeap()->GetLargeObjectsSpace();
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001656 large_objects->GetMarkObjects()->Clear();
Carl Shapiro69759ea2011-07-21 18:13:35 -07001657}
1658
Ian Rogers1d54e732013-05-02 21:10:01 -07001659} // namespace collector
1660} // namespace gc
Carl Shapiro69759ea2011-07-21 18:13:35 -07001661} // namespace art