blob: fa1e4e8906fa9188f2266c73a4ac6f25bcda1c69 [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);
Mathieu Chartier9e452d12013-09-18 16:35:15 -0700210 {
211 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
212 SweepSystemWeaks();
213 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800214
215 // Only need to do this if we have the card mark verification on, and only during concurrent GC.
216 if (GetHeap()->verify_missing_card_marks_) {
217 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
218 // This second sweep makes sure that we don't have any objects in the live stack which point to
219 // freed objects. These cause problems since their references may be previously freed objects.
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700220 SweepArray(GetHeap()->allocation_stack_.get(), false);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800221 }
222 return true;
223}
224
225bool MarkSweep::IsConcurrent() const {
226 return is_concurrent_;
227}
228
229void MarkSweep::MarkingPhase() {
Anwar Ghuloum46543222013-08-12 09:28:42 -0700230 base::TimingLogger::ScopedSplit split("MarkingPhase", &timings_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800231 Heap* heap = GetHeap();
232 Thread* self = Thread::Current();
233
234 BindBitmaps();
235 FindDefaultMarkBitmap();
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700236
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800237 // Process dirty cards and add dirty cards to mod union tables.
238 heap->ProcessCards(timings_);
239
240 // Need to do this before the checkpoint since we don't want any threads to add references to
241 // the live stack during the recursive mark.
Anwar Ghuloum46543222013-08-12 09:28:42 -0700242 timings_.NewSplit("SwapStacks");
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800243 heap->SwapStacks();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800244
245 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
246 if (Locks::mutator_lock_->IsExclusiveHeld(self)) {
247 // If we exclusively hold the mutator lock, all threads must be suspended.
248 MarkRoots();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800249 } else {
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700250 MarkThreadRoots(self);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800251 MarkNonThreadRoots();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800252 }
253 MarkConcurrentRoots();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800254
255 heap->UpdateAndMarkModUnion(this, timings_, GetGcType());
256 MarkReachableObjects();
257}
258
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700259void MarkSweep::MarkThreadRoots(Thread* self) {
260 MarkRootsCheckpoint(self);
261}
262
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800263void MarkSweep::MarkReachableObjects() {
264 // Mark everything allocated since the last as GC live so that we can sweep concurrently,
265 // knowing that new allocations won't be marked as live.
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700266 timings_.StartSplit("MarkStackAsLive");
Ian Rogers1d54e732013-05-02 21:10:01 -0700267 accounting::ObjectStack* live_stack = heap_->GetLiveStack();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800268 heap_->MarkAllocStack(heap_->alloc_space_->GetLiveBitmap(),
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700269 heap_->large_object_space_->GetLiveObjects(), live_stack);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800270 live_stack->Reset();
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700271 timings_.EndSplit();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800272 // Recursively mark all the non-image bits set in the mark bitmap.
273 RecursiveMark();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800274}
275
276void MarkSweep::ReclaimPhase() {
Anwar Ghuloum46543222013-08-12 09:28:42 -0700277 base::TimingLogger::ScopedSplit split("ReclaimPhase", &timings_);
Mathieu Chartier720ef762013-08-17 14:46:54 -0700278 Thread* self = Thread::Current();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800279
280 if (!IsConcurrent()) {
281 ProcessReferences(self);
Mathieu Chartier9e452d12013-09-18 16:35:15 -0700282 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
283 SweepSystemWeaks();
Mathieu Chartier9642c962013-08-05 17:40:36 -0700284 } else {
Anwar Ghulouma9a50922013-08-09 21:34:20 -0700285 base::TimingLogger::ScopedSplit split("UnMarkAllocStack", &timings_);
Mathieu Chartier9642c962013-08-05 17:40:36 -0700286 accounting::ObjectStack* allocation_stack = GetHeap()->allocation_stack_.get();
287 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
288 // The allocation stack contains things allocated since the start of the GC. These may have been
289 // marked during this GC meaning they won't be eligible for reclaiming in the next sticky GC.
290 // Remove these objects from the mark bitmaps so that they will be eligible for sticky
291 // collection.
292 // There is a race here which is safely handled. Another thread such as the hprof could
293 // have flushed the alloc stack after we resumed the threads. This is safe however, since
294 // reseting the allocation stack zeros it out with madvise. This means that we will either
295 // read NULLs or attempt to unmark a newly allocated object which will not be marked in the
296 // first place.
297 mirror::Object** end = allocation_stack->End();
298 for (mirror::Object** it = allocation_stack->Begin(); it != end; ++it) {
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700299 const Object* obj = *it;
Mathieu Chartier9642c962013-08-05 17:40:36 -0700300 if (obj != NULL) {
301 UnMarkObjectNonNull(obj);
302 }
303 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800304 }
305
306 // Before freeing anything, lets verify the heap.
307 if (kIsDebugBuild) {
308 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
309 VerifyImageRoots();
310 }
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700311 timings_.StartSplit("PreSweepingGcVerification");
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800312 heap_->PreSweepingGcVerification(this);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700313 timings_.EndSplit();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800314
315 {
316 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
317
318 // Reclaim unmarked objects.
Ian Rogers1d54e732013-05-02 21:10:01 -0700319 Sweep(false);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800320
321 // Swap the live and mark bitmaps for each space which we modified space. This is an
322 // optimization that enables us to not clear live bits inside of the sweep. Only swaps unbound
323 // bitmaps.
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700324 timings_.StartSplit("SwapBitmaps");
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800325 SwapBitmaps();
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700326 timings_.EndSplit();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800327
328 // Unbind the live and mark bitmaps.
329 UnBindBitmaps();
330 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800331}
332
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800333void MarkSweep::SetImmuneRange(Object* begin, Object* end) {
334 immune_begin_ = begin;
335 immune_end_ = end;
Carl Shapiro58551df2011-07-24 03:09:51 -0700336}
337
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700338void MarkSweep::FindDefaultMarkBitmap() {
Anwar Ghuloum46543222013-08-12 09:28:42 -0700339 base::TimingLogger::ScopedSplit split("FindDefaultMarkBitmap", &timings_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700340 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700341 if (space->GetGcRetentionPolicy() == space::kGcRetentionPolicyAlwaysCollect) {
Mathieu Chartier02e25112013-08-14 16:14:24 -0700342 current_mark_bitmap_ = space->GetMarkBitmap();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700343 CHECK(current_mark_bitmap_ != NULL);
344 return;
345 }
346 }
347 GetHeap()->DumpSpaces();
348 LOG(FATAL) << "Could not find a default mark bitmap";
349}
350
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800351void MarkSweep::ExpandMarkStack() {
Mathieu Chartierba311b42013-08-27 13:02:30 -0700352 ResizeMarkStack(mark_stack_->Capacity() * 2);
353}
354
355void MarkSweep::ResizeMarkStack(size_t new_size) {
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800356 // Rare case, no need to have Thread::Current be a parameter.
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800357 if (UNLIKELY(mark_stack_->Size() < mark_stack_->Capacity())) {
358 // Someone else acquired the lock and expanded the mark stack before us.
359 return;
360 }
Mathieu Chartier02e25112013-08-14 16:14:24 -0700361 std::vector<Object*> temp(mark_stack_->Begin(), mark_stack_->End());
Mathieu Chartierba311b42013-08-27 13:02:30 -0700362 CHECK_LE(mark_stack_->Size(), new_size);
363 mark_stack_->Resize(new_size);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700364 for (const auto& obj : temp) {
365 mark_stack_->PushBack(obj);
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800366 }
367}
368
Mathieu Chartier9642c962013-08-05 17:40:36 -0700369inline void MarkSweep::MarkObjectNonNullParallel(const Object* obj) {
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800370 DCHECK(obj != NULL);
371 if (MarkObjectParallel(obj)) {
Mathieu Chartierba311b42013-08-27 13:02:30 -0700372 MutexLock mu(Thread::Current(), mark_stack_lock_);
373 if (UNLIKELY(mark_stack_->Size() >= mark_stack_->Capacity())) {
Mathieu Chartier184e3222013-08-03 14:02:57 -0700374 ExpandMarkStack();
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800375 }
Mathieu Chartierba311b42013-08-27 13:02:30 -0700376 // The object must be pushed on to the mark stack.
377 mark_stack_->PushBack(const_cast<Object*>(obj));
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800378 }
379}
380
Mathieu Chartier9642c962013-08-05 17:40:36 -0700381inline void MarkSweep::UnMarkObjectNonNull(const Object* obj) {
382 DCHECK(!IsImmune(obj));
383 // Try to take advantage of locality of references within a space, failing this find the space
384 // the hard way.
385 accounting::SpaceBitmap* object_bitmap = current_mark_bitmap_;
386 if (UNLIKELY(!object_bitmap->HasAddress(obj))) {
387 accounting::SpaceBitmap* new_bitmap = heap_->GetMarkBitmap()->GetContinuousSpaceBitmap(obj);
388 if (LIKELY(new_bitmap != NULL)) {
389 object_bitmap = new_bitmap;
390 } else {
391 MarkLargeObject(obj, false);
392 return;
393 }
394 }
395
396 DCHECK(object_bitmap->HasAddress(obj));
397 object_bitmap->Clear(obj);
398}
399
400inline void MarkSweep::MarkObjectNonNull(const Object* obj) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700401 DCHECK(obj != NULL);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700402
Mathieu Chartier9642c962013-08-05 17:40:36 -0700403 if (IsImmune(obj)) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700404 DCHECK(IsMarked(obj));
Carl Shapiro69759ea2011-07-21 18:13:35 -0700405 return;
406 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700407
408 // Try to take advantage of locality of references within a space, failing this find the space
409 // the hard way.
Ian Rogers1d54e732013-05-02 21:10:01 -0700410 accounting::SpaceBitmap* object_bitmap = current_mark_bitmap_;
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700411 if (UNLIKELY(!object_bitmap->HasAddress(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700412 accounting::SpaceBitmap* new_bitmap = heap_->GetMarkBitmap()->GetContinuousSpaceBitmap(obj);
413 if (LIKELY(new_bitmap != NULL)) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700414 object_bitmap = new_bitmap;
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700415 } else {
Mathieu Chartier9642c962013-08-05 17:40:36 -0700416 MarkLargeObject(obj, true);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700417 return;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700418 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700419 }
420
Carl Shapiro69759ea2011-07-21 18:13:35 -0700421 // This object was not previously marked.
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700422 if (!object_bitmap->Test(obj)) {
423 object_bitmap->Set(obj);
Mathieu Chartierba311b42013-08-27 13:02:30 -0700424 // Lock is not needed but is here anyways to please annotalysis.
425 MutexLock mu(Thread::Current(), mark_stack_lock_);
Mathieu Chartier184e3222013-08-03 14:02:57 -0700426 if (UNLIKELY(mark_stack_->Size() >= mark_stack_->Capacity())) {
427 ExpandMarkStack();
Carl Shapiro69759ea2011-07-21 18:13:35 -0700428 }
Mathieu Chartier184e3222013-08-03 14:02:57 -0700429 // The object must be pushed on to the mark stack.
430 mark_stack_->PushBack(const_cast<Object*>(obj));
Carl Shapiro69759ea2011-07-21 18:13:35 -0700431 }
432}
433
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700434// Rare case, probably not worth inlining since it will increase instruction cache miss rate.
Mathieu Chartier9642c962013-08-05 17:40:36 -0700435bool MarkSweep::MarkLargeObject(const Object* obj, bool set) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700436 // TODO: support >1 discontinuous space.
437 space::LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
438 accounting::SpaceSetMap* large_objects = large_object_space->GetMarkObjects();
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700439 if (kProfileLargeObjects) {
440 ++large_object_test_;
441 }
442 if (UNLIKELY(!large_objects->Test(obj))) {
Mathieu Chartier4fcb8d32013-07-15 12:43:36 -0700443 if (!large_object_space->Contains(obj)) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700444 LOG(ERROR) << "Tried to mark " << obj << " not contained by any spaces";
445 LOG(ERROR) << "Attempting see if it's a bad root";
446 VerifyRoots();
447 LOG(FATAL) << "Can't mark bad root";
448 }
449 if (kProfileLargeObjects) {
450 ++large_object_mark_;
451 }
Mathieu Chartier9642c962013-08-05 17:40:36 -0700452 if (set) {
453 large_objects->Set(obj);
454 } else {
455 large_objects->Clear(obj);
456 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700457 return true;
458 }
459 return false;
460}
461
462inline bool MarkSweep::MarkObjectParallel(const Object* obj) {
463 DCHECK(obj != NULL);
464
Mathieu Chartier9642c962013-08-05 17:40:36 -0700465 if (IsImmune(obj)) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700466 DCHECK(IsMarked(obj));
467 return false;
468 }
469
470 // Try to take advantage of locality of references within a space, failing this find the space
471 // the hard way.
Ian Rogers1d54e732013-05-02 21:10:01 -0700472 accounting::SpaceBitmap* object_bitmap = current_mark_bitmap_;
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700473 if (UNLIKELY(!object_bitmap->HasAddress(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700474 accounting::SpaceBitmap* new_bitmap = heap_->GetMarkBitmap()->GetContinuousSpaceBitmap(obj);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700475 if (new_bitmap != NULL) {
476 object_bitmap = new_bitmap;
477 } else {
478 // TODO: Remove the Thread::Current here?
479 // TODO: Convert this to some kind of atomic marking?
480 MutexLock mu(Thread::Current(), large_object_lock_);
Mathieu Chartier9642c962013-08-05 17:40:36 -0700481 return MarkLargeObject(obj, true);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700482 }
483 }
484
485 // Return true if the object was not previously marked.
486 return !object_bitmap->AtomicTestAndSet(obj);
487}
488
Carl Shapiro69759ea2011-07-21 18:13:35 -0700489// Used to mark objects when recursing. Recursion is done by moving
490// the finger across the bitmaps in address order and marking child
491// objects. Any newly-marked objects whose addresses are lower than
492// the finger won't be visited by the bitmap scan, so those objects
493// need to be added to the mark stack.
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700494inline void MarkSweep::MarkObject(const Object* obj) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700495 if (obj != NULL) {
Mathieu Chartier9642c962013-08-05 17:40:36 -0700496 MarkObjectNonNull(obj);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700497 }
498}
499
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800500void MarkSweep::MarkRoot(const Object* obj) {
501 if (obj != NULL) {
Mathieu Chartier9642c962013-08-05 17:40:36 -0700502 MarkObjectNonNull(obj);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800503 }
504}
505
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800506void MarkSweep::MarkRootParallelCallback(const Object* root, void* arg) {
507 DCHECK(root != NULL);
508 DCHECK(arg != NULL);
Mathieu Chartierba311b42013-08-27 13:02:30 -0700509 reinterpret_cast<MarkSweep*>(arg)->MarkObjectNonNullParallel(root);
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800510}
511
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700512void MarkSweep::MarkObjectCallback(const Object* root, void* arg) {
Brian Carlstrom1f870082011-08-23 16:02:11 -0700513 DCHECK(root != NULL);
514 DCHECK(arg != NULL);
515 MarkSweep* mark_sweep = reinterpret_cast<MarkSweep*>(arg);
Mathieu Chartier9642c962013-08-05 17:40:36 -0700516 mark_sweep->MarkObjectNonNull(root);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700517}
518
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700519void MarkSweep::ReMarkObjectVisitor(const Object* root, void* arg) {
520 DCHECK(root != NULL);
521 DCHECK(arg != NULL);
522 MarkSweep* mark_sweep = reinterpret_cast<MarkSweep*>(arg);
Mathieu Chartier9642c962013-08-05 17:40:36 -0700523 mark_sweep->MarkObjectNonNull(root);
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700524}
525
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700526void MarkSweep::VerifyRootCallback(const Object* root, void* arg, size_t vreg,
Ian Rogers40e3bac2012-11-20 00:09:14 -0800527 const StackVisitor* visitor) {
528 reinterpret_cast<MarkSweep*>(arg)->VerifyRoot(root, vreg, visitor);
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700529}
530
Ian Rogers40e3bac2012-11-20 00:09:14 -0800531void MarkSweep::VerifyRoot(const Object* root, size_t vreg, const StackVisitor* visitor) {
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700532 // See if the root is on any space bitmap.
Ian Rogers1d54e732013-05-02 21:10:01 -0700533 if (GetHeap()->GetLiveBitmap()->GetContinuousSpaceBitmap(root) == NULL) {
534 space::LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
Mathieu Chartier4202b742012-10-17 17:51:25 -0700535 if (!large_object_space->Contains(root)) {
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700536 LOG(ERROR) << "Found invalid root: " << root;
Ian Rogers40e3bac2012-11-20 00:09:14 -0800537 if (visitor != NULL) {
538 LOG(ERROR) << visitor->DescribeLocation() << " in VReg: " << vreg;
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700539 }
540 }
541 }
542}
543
544void MarkSweep::VerifyRoots() {
545 Runtime::Current()->GetThreadList()->VerifyRoots(VerifyRootCallback, this);
546}
547
Carl Shapiro69759ea2011-07-21 18:13:35 -0700548// Marks all objects in the root set.
549void MarkSweep::MarkRoots() {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700550 timings_.StartSplit("MarkRoots");
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700551 Runtime::Current()->VisitNonConcurrentRoots(MarkObjectCallback, this);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700552 timings_.EndSplit();
Mathieu Chartier9ebae1f2012-10-15 17:38:16 -0700553}
554
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700555void MarkSweep::MarkNonThreadRoots() {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700556 timings_.StartSplit("MarkNonThreadRoots");
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700557 Runtime::Current()->VisitNonThreadRoots(MarkObjectCallback, this);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700558 timings_.EndSplit();
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700559}
560
Mathieu Chartier9ebae1f2012-10-15 17:38:16 -0700561void MarkSweep::MarkConcurrentRoots() {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700562 timings_.StartSplit("MarkConcurrentRoots");
Ian Rogers1d54e732013-05-02 21:10:01 -0700563 // Visit all runtime roots and clear dirty flags.
564 Runtime::Current()->VisitConcurrentRoots(MarkObjectCallback, this, false, true);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700565 timings_.EndSplit();
Carl Shapiro69759ea2011-07-21 18:13:35 -0700566}
567
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700568void MarkSweep::CheckObject(const Object* obj) {
569 DCHECK(obj != NULL);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700570 VisitObjectReferences(obj, [this](const Object* obj, const Object* ref, MemberOffset offset,
571 bool is_static) NO_THREAD_SAFETY_ANALYSIS {
572 Locks::heap_bitmap_lock_->AssertSharedHeld(Thread::Current());
573 CheckReference(obj, ref, offset, is_static);
574 });
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700575}
576
577void MarkSweep::VerifyImageRootVisitor(Object* root, void* arg) {
578 DCHECK(root != NULL);
579 DCHECK(arg != NULL);
580 MarkSweep* mark_sweep = reinterpret_cast<MarkSweep*>(arg);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700581 DCHECK(mark_sweep->heap_->GetMarkBitmap()->Test(root));
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700582 mark_sweep->CheckObject(root);
583}
584
Ian Rogers1d54e732013-05-02 21:10:01 -0700585void MarkSweep::BindLiveToMarkBitmap(space::ContinuousSpace* space) {
586 CHECK(space->IsDlMallocSpace());
587 space::DlMallocSpace* alloc_space = space->AsDlMallocSpace();
588 accounting::SpaceBitmap* live_bitmap = space->GetLiveBitmap();
589 accounting::SpaceBitmap* mark_bitmap = alloc_space->mark_bitmap_.release();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700590 GetHeap()->GetMarkBitmap()->ReplaceBitmap(mark_bitmap, live_bitmap);
591 alloc_space->temp_bitmap_.reset(mark_bitmap);
592 alloc_space->mark_bitmap_.reset(live_bitmap);
593}
594
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700595class ScanObjectVisitor {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700596 public:
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700597 explicit ScanObjectVisitor(MarkSweep* const mark_sweep) ALWAYS_INLINE
598 : mark_sweep_(mark_sweep) {}
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700599
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800600 // TODO: Fixme when anotatalysis works with visitors.
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700601 void operator()(const Object* obj) const ALWAYS_INLINE NO_THREAD_SAFETY_ANALYSIS {
602 if (kCheckLocks) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800603 Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
604 Locks::heap_bitmap_lock_->AssertExclusiveHeld(Thread::Current());
605 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700606 mark_sweep_->ScanObject(obj);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700607 }
608
609 private:
610 MarkSweep* const mark_sweep_;
611};
612
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700613template <bool kUseFinger = false>
614class MarkStackTask : public Task {
615 public:
616 MarkStackTask(ThreadPool* thread_pool, MarkSweep* mark_sweep, size_t mark_stack_size,
617 const Object** mark_stack)
618 : mark_sweep_(mark_sweep),
619 thread_pool_(thread_pool),
620 mark_stack_pos_(mark_stack_size) {
621 // We may have to copy part of an existing mark stack when another mark stack overflows.
622 if (mark_stack_size != 0) {
623 DCHECK(mark_stack != NULL);
624 // TODO: Check performance?
625 std::copy(mark_stack, mark_stack + mark_stack_size, mark_stack_);
Ian Rogers1d54e732013-05-02 21:10:01 -0700626 }
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700627 if (kCountTasks) {
628 ++mark_sweep_->work_chunks_created_;
629 }
630 }
631
632 static const size_t kMaxSize = 1 * KB;
633
634 protected:
635 class ScanObjectParallelVisitor {
636 public:
637 explicit ScanObjectParallelVisitor(MarkStackTask<kUseFinger>* chunk_task) ALWAYS_INLINE
638 : chunk_task_(chunk_task) {}
639
640 void operator()(const Object* obj) const {
641 MarkSweep* mark_sweep = chunk_task_->mark_sweep_;
642 mark_sweep->ScanObjectVisit(obj,
643 [mark_sweep, this](const Object* /* obj */, const Object* ref,
644 const MemberOffset& /* offset */, bool /* is_static */) ALWAYS_INLINE {
645 if (ref != nullptr && mark_sweep->MarkObjectParallel(ref)) {
646 if (kUseFinger) {
647 android_memory_barrier();
648 if (reinterpret_cast<uintptr_t>(ref) >=
649 static_cast<uintptr_t>(mark_sweep->atomic_finger_)) {
650 return;
651 }
652 }
653 chunk_task_->MarkStackPush(ref);
654 }
655 });
656 }
657
658 private:
659 MarkStackTask<kUseFinger>* const chunk_task_;
660 };
661
662 virtual ~MarkStackTask() {
663 // Make sure that we have cleared our mark stack.
664 DCHECK_EQ(mark_stack_pos_, 0U);
665 if (kCountTasks) {
666 ++mark_sweep_->work_chunks_deleted_;
667 }
668 }
669
670 MarkSweep* const mark_sweep_;
671 ThreadPool* const thread_pool_;
672 // Thread local mark stack for this task.
673 const Object* mark_stack_[kMaxSize];
674 // Mark stack position.
675 size_t mark_stack_pos_;
676
677 void MarkStackPush(const Object* obj) ALWAYS_INLINE {
678 if (UNLIKELY(mark_stack_pos_ == kMaxSize)) {
679 // Mark stack overflow, give 1/2 the stack to the thread pool as a new work task.
680 mark_stack_pos_ /= 2;
681 auto* task = new MarkStackTask(thread_pool_, mark_sweep_, kMaxSize - mark_stack_pos_,
682 mark_stack_ + mark_stack_pos_);
683 thread_pool_->AddTask(Thread::Current(), task);
684 }
685 DCHECK(obj != nullptr);
686 DCHECK(mark_stack_pos_ < kMaxSize);
687 mark_stack_[mark_stack_pos_++] = obj;
688 }
689
690 virtual void Finalize() {
691 delete this;
692 }
693
694 // Scans all of the objects
695 virtual void Run(Thread* self) {
696 ScanObjectParallelVisitor visitor(this);
697 // TODO: Tune this.
698 static const size_t kFifoSize = 4;
699 BoundedFifoPowerOfTwo<const Object*, kFifoSize> prefetch_fifo;
700 for (;;) {
701 const Object* obj = NULL;
702 if (kUseMarkStackPrefetch) {
703 while (mark_stack_pos_ != 0 && prefetch_fifo.size() < kFifoSize) {
704 const Object* obj = mark_stack_[--mark_stack_pos_];
705 DCHECK(obj != NULL);
706 __builtin_prefetch(obj);
707 prefetch_fifo.push_back(obj);
708 }
709 if (UNLIKELY(prefetch_fifo.empty())) {
710 break;
711 }
712 obj = prefetch_fifo.front();
713 prefetch_fifo.pop_front();
714 } else {
715 if (UNLIKELY(mark_stack_pos_ == 0)) {
716 break;
717 }
718 obj = mark_stack_[--mark_stack_pos_];
719 }
720 DCHECK(obj != NULL);
721 visitor(obj);
722 }
723 }
724};
725
726class CardScanTask : public MarkStackTask<false> {
727 public:
728 CardScanTask(ThreadPool* thread_pool, MarkSweep* mark_sweep, accounting::SpaceBitmap* bitmap,
729 byte* begin, byte* end, byte minimum_age, size_t mark_stack_size,
730 const Object** mark_stack_obj)
731 : MarkStackTask<false>(thread_pool, mark_sweep, mark_stack_size, mark_stack_obj),
732 bitmap_(bitmap),
733 begin_(begin),
734 end_(end),
735 minimum_age_(minimum_age) {
736 }
737
738 protected:
739 accounting::SpaceBitmap* const bitmap_;
740 byte* const begin_;
741 byte* const end_;
742 const byte minimum_age_;
743
744 virtual void Finalize() {
745 delete this;
746 }
747
748 virtual void Run(Thread* self) NO_THREAD_SAFETY_ANALYSIS {
749 ScanObjectParallelVisitor visitor(this);
750 accounting::CardTable* card_table = mark_sweep_->GetHeap()->GetCardTable();
751 card_table->Scan(bitmap_, begin_, end_, visitor, minimum_age_);
752 // Finish by emptying our local mark stack.
753 MarkStackTask::Run(self);
754 }
755};
756
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700757size_t MarkSweep::GetThreadCount(bool paused) const {
758 if (heap_->GetThreadPool() == nullptr || !heap_->CareAboutPauseTimes()) {
759 return 0;
760 }
761 if (paused) {
762 return heap_->GetParallelGCThreadCount() + 1;
763 } else {
764 return heap_->GetConcGCThreadCount() + 1;
765 }
766}
767
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700768void MarkSweep::ScanGrayObjects(bool paused, byte minimum_age) {
769 accounting::CardTable* card_table = GetHeap()->GetCardTable();
770 ThreadPool* thread_pool = GetHeap()->GetThreadPool();
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700771 size_t thread_count = GetThreadCount(paused);
772 // The parallel version with only one thread is faster for card scanning, TODO: fix.
773 if (kParallelCardScan && thread_count > 0) {
Mathieu Chartier720ef762013-08-17 14:46:54 -0700774 Thread* self = Thread::Current();
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700775 // Can't have a different split for each space since multiple spaces can have their cards being
776 // scanned at the same time.
777 timings_.StartSplit(paused ? "(Paused)ScanGrayObjects" : "ScanGrayObjects");
778 // Try to take some of the mark stack since we can pass this off to the worker tasks.
779 const Object** mark_stack_begin = const_cast<const Object**>(mark_stack_->Begin());
780 const Object** mark_stack_end = const_cast<const Object**>(mark_stack_->End());
Mathieu Chartier720ef762013-08-17 14:46:54 -0700781 const size_t mark_stack_size = mark_stack_end - mark_stack_begin;
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700782 // Estimated number of work tasks we will create.
783 const size_t mark_stack_tasks = GetHeap()->GetContinuousSpaces().size() * thread_count;
784 DCHECK_NE(mark_stack_tasks, 0U);
785 const size_t mark_stack_delta = std::min(CardScanTask::kMaxSize / 2,
786 mark_stack_size / mark_stack_tasks + 1);
787 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
788 byte* card_begin = space->Begin();
789 byte* card_end = space->End();
790 // Calculate how many bytes of heap we will scan,
791 const size_t address_range = card_end - card_begin;
792 // Calculate how much address range each task gets.
793 const size_t card_delta = RoundUp(address_range / thread_count + 1,
794 accounting::CardTable::kCardSize);
795 // Create the worker tasks for this space.
796 while (card_begin != card_end) {
797 // Add a range of cards.
798 size_t addr_remaining = card_end - card_begin;
799 size_t card_increment = std::min(card_delta, addr_remaining);
800 // Take from the back of the mark stack.
801 size_t mark_stack_remaining = mark_stack_end - mark_stack_begin;
802 size_t mark_stack_increment = std::min(mark_stack_delta, mark_stack_remaining);
803 mark_stack_end -= mark_stack_increment;
804 mark_stack_->PopBackCount(static_cast<int32_t>(mark_stack_increment));
805 DCHECK_EQ(mark_stack_end, mark_stack_->End());
806 // Add the new task to the thread pool.
807 auto* task = new CardScanTask(thread_pool, this, space->GetMarkBitmap(), card_begin,
808 card_begin + card_increment, minimum_age,
809 mark_stack_increment, mark_stack_end);
810 thread_pool->AddTask(self, task);
811 card_begin += card_increment;
812 }
813 }
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700814 thread_pool->SetMaxActiveWorkers(thread_count - 1);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700815 thread_pool->StartWorkers(self);
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700816 thread_pool->Wait(self, true, true);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700817 thread_pool->StopWorkers(self);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700818 timings_.EndSplit();
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700819 } else {
820 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
821 // Image spaces are handled properly since live == marked for them.
822 switch (space->GetGcRetentionPolicy()) {
823 case space::kGcRetentionPolicyNeverCollect:
824 timings_.StartSplit(paused ? "(Paused)ScanGrayImageSpaceObjects" :
825 "ScanGrayImageSpaceObjects");
826 break;
827 case space::kGcRetentionPolicyFullCollect:
828 timings_.StartSplit(paused ? "(Paused)ScanGrayZygoteSpaceObjects" :
829 "ScanGrayZygoteSpaceObjects");
830 break;
831 case space::kGcRetentionPolicyAlwaysCollect:
832 timings_.StartSplit(paused ? "(Paused)ScanGrayAllocSpaceObjects" :
833 "ScanGrayAllocSpaceObjects");
834 break;
835 }
836 ScanObjectVisitor visitor(this);
837 card_table->Scan(space->GetMarkBitmap(), space->Begin(), space->End(), visitor, minimum_age);
838 timings_.EndSplit();
839 }
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700840 }
841}
842
843void MarkSweep::VerifyImageRoots() {
844 // Verify roots ensures that all the references inside the image space point
845 // objects which are either in the image space or marked objects in the alloc
846 // space
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700847 timings_.StartSplit("VerifyImageRoots");
Mathieu Chartier02e25112013-08-14 16:14:24 -0700848 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
849 if (space->IsImageSpace()) {
850 space::ImageSpace* image_space = space->AsImageSpace();
851 uintptr_t begin = reinterpret_cast<uintptr_t>(image_space->Begin());
852 uintptr_t end = reinterpret_cast<uintptr_t>(image_space->End());
853 accounting::SpaceBitmap* live_bitmap = image_space->GetLiveBitmap();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700854 DCHECK(live_bitmap != NULL);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700855 live_bitmap->VisitMarkedRange(begin, end, [this](const Object* obj) {
856 if (kCheckLocks) {
857 Locks::heap_bitmap_lock_->AssertSharedHeld(Thread::Current());
858 }
859 DCHECK(obj != NULL);
860 CheckObject(obj);
861 });
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700862 }
863 }
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700864 timings_.EndSplit();
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700865}
866
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700867class RecursiveMarkTask : public MarkStackTask<false> {
868 public:
869 RecursiveMarkTask(ThreadPool* thread_pool, MarkSweep* mark_sweep,
870 accounting::SpaceBitmap* bitmap, uintptr_t begin, uintptr_t end)
871 : MarkStackTask<false>(thread_pool, mark_sweep, 0, NULL),
872 bitmap_(bitmap),
873 begin_(begin),
874 end_(end) {
875 }
876
877 protected:
878 accounting::SpaceBitmap* const bitmap_;
879 const uintptr_t begin_;
880 const uintptr_t end_;
881
882 virtual void Finalize() {
883 delete this;
884 }
885
886 // Scans all of the objects
887 virtual void Run(Thread* self) NO_THREAD_SAFETY_ANALYSIS {
888 ScanObjectParallelVisitor visitor(this);
889 bitmap_->VisitMarkedRange(begin_, end_, visitor);
890 // Finish by emptying our local mark stack.
891 MarkStackTask::Run(self);
892 }
893};
894
Carl Shapiro58551df2011-07-24 03:09:51 -0700895// Populates the mark stack based on the set of marked objects and
896// recursively marks until the mark stack is emptied.
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800897void MarkSweep::RecursiveMark() {
Anwar Ghuloum46543222013-08-12 09:28:42 -0700898 base::TimingLogger::ScopedSplit split("RecursiveMark", &timings_);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700899 // RecursiveMark will build the lists of known instances of the Reference classes.
900 // See DelayReferenceReferent for details.
901 CHECK(soft_reference_list_ == NULL);
902 CHECK(weak_reference_list_ == NULL);
903 CHECK(finalizer_reference_list_ == NULL);
904 CHECK(phantom_reference_list_ == NULL);
905 CHECK(cleared_reference_list_ == NULL);
906
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700907 if (kUseRecursiveMark) {
908 const bool partial = GetGcType() == kGcTypePartial;
909 ScanObjectVisitor scan_visitor(this);
910 auto* self = Thread::Current();
911 ThreadPool* thread_pool = heap_->GetThreadPool();
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700912 size_t thread_count = GetThreadCount(false);
913 const bool parallel = kParallelRecursiveMark && thread_count > 1;
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700914 mark_stack_->Reset();
Mathieu Chartier02e25112013-08-14 16:14:24 -0700915 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700916 if ((space->GetGcRetentionPolicy() == space::kGcRetentionPolicyAlwaysCollect) ||
917 (!partial && space->GetGcRetentionPolicy() == space::kGcRetentionPolicyFullCollect)) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800918 current_mark_bitmap_ = space->GetMarkBitmap();
919 if (current_mark_bitmap_ == NULL) {
920 GetHeap()->DumpSpaces();
921 LOG(FATAL) << "invalid bitmap";
922 }
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700923 if (parallel) {
924 // We will use the mark stack the future.
925 // CHECK(mark_stack_->IsEmpty());
926 // This function does not handle heap end increasing, so we must use the space end.
927 uintptr_t begin = reinterpret_cast<uintptr_t>(space->Begin());
928 uintptr_t end = reinterpret_cast<uintptr_t>(space->End());
929 atomic_finger_ = static_cast<int32_t>(0xFFFFFFFF);
930
931 // Create a few worker tasks.
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700932 const size_t n = thread_count * 2;
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700933 while (begin != end) {
934 uintptr_t start = begin;
935 uintptr_t delta = (end - begin) / n;
936 delta = RoundUp(delta, KB);
937 if (delta < 16 * KB) delta = end - begin;
938 begin += delta;
939 auto* task = new RecursiveMarkTask(thread_pool, this, current_mark_bitmap_, start,
940 begin);
941 thread_pool->AddTask(self, task);
942 }
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700943 thread_pool->SetMaxActiveWorkers(thread_count - 1);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700944 thread_pool->StartWorkers(self);
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700945 thread_pool->Wait(self, true, true);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700946 thread_pool->StopWorkers(self);
947 } else {
948 // This function does not handle heap end increasing, so we must use the space end.
949 uintptr_t begin = reinterpret_cast<uintptr_t>(space->Begin());
950 uintptr_t end = reinterpret_cast<uintptr_t>(space->End());
951 current_mark_bitmap_->VisitMarkedRange(begin, end, scan_visitor);
952 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700953 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700954 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700955 }
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700956 ProcessMarkStack(false);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700957}
958
959bool MarkSweep::IsMarkedCallback(const Object* object, void* arg) {
Mathieu Chartier9e452d12013-09-18 16:35:15 -0700960 return reinterpret_cast<MarkSweep*>(arg)->IsMarked(object);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700961}
962
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700963void MarkSweep::RecursiveMarkDirtyObjects(bool paused, byte minimum_age) {
964 ScanGrayObjects(paused, minimum_age);
965 ProcessMarkStack(paused);
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700966}
967
Carl Shapiro58551df2011-07-24 03:09:51 -0700968void MarkSweep::ReMarkRoots() {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700969 timings_.StartSplit("ReMarkRoots");
Ian Rogers1d54e732013-05-02 21:10:01 -0700970 Runtime::Current()->VisitRoots(ReMarkObjectVisitor, this, true, true);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700971 timings_.EndSplit();
Carl Shapiro69759ea2011-07-21 18:13:35 -0700972}
973
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800974void MarkSweep::SweepJniWeakGlobals(IsMarkedTester is_marked, void* arg) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700975 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
Ian Rogersb8a0b942013-08-20 18:09:52 -0700976 WriterMutexLock mu(Thread::Current(), vm->weak_globals_lock);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700977 for (const Object** entry : vm->weak_globals) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700978 if (!is_marked(*entry, arg)) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700979 *entry = kClearedJniWeakGlobal;
980 }
981 }
982}
983
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700984struct ArrayMarkedCheck {
Ian Rogers1d54e732013-05-02 21:10:01 -0700985 accounting::ObjectStack* live_stack;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700986 MarkSweep* mark_sweep;
987};
988
989// Either marked or not live.
990bool MarkSweep::IsMarkedArrayCallback(const Object* object, void* arg) {
991 ArrayMarkedCheck* array_check = reinterpret_cast<ArrayMarkedCheck*>(arg);
992 if (array_check->mark_sweep->IsMarked(object)) {
993 return true;
994 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700995 accounting::ObjectStack* live_stack = array_check->live_stack;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700996 return std::find(live_stack->Begin(), live_stack->End(), object) == live_stack->End();
997}
998
Ian Rogers1d54e732013-05-02 21:10:01 -0700999void MarkSweep::SweepSystemWeaksArray(accounting::ObjectStack* allocations) {
Mathieu Chartier46a23632012-08-07 18:44:40 -07001000 Runtime* runtime = Runtime::Current();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001001 // The callbacks check
1002 // !is_marked where is_marked is the callback but we want
1003 // !IsMarked && IsLive
1004 // So compute !(!IsMarked && IsLive) which is equal to (IsMarked || !IsLive).
1005 // Or for swapped (IsLive || !IsMarked).
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001006
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001007 timings_.StartSplit("SweepSystemWeaksArray");
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001008 ArrayMarkedCheck visitor;
1009 visitor.live_stack = allocations;
1010 visitor.mark_sweep = this;
1011 runtime->GetInternTable()->SweepInternTableWeaks(IsMarkedArrayCallback, &visitor);
1012 runtime->GetMonitorList()->SweepMonitorList(IsMarkedArrayCallback, &visitor);
1013 SweepJniWeakGlobals(IsMarkedArrayCallback, &visitor);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001014 timings_.EndSplit();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001015}
1016
1017void MarkSweep::SweepSystemWeaks() {
1018 Runtime* runtime = Runtime::Current();
1019 // The callbacks check
1020 // !is_marked where is_marked is the callback but we want
1021 // !IsMarked && IsLive
1022 // So compute !(!IsMarked && IsLive) which is equal to (IsMarked || !IsLive).
1023 // Or for swapped (IsLive || !IsMarked).
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001024 timings_.StartSplit("SweepSystemWeaks");
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001025 runtime->GetInternTable()->SweepInternTableWeaks(IsMarkedCallback, this);
1026 runtime->GetMonitorList()->SweepMonitorList(IsMarkedCallback, this);
1027 SweepJniWeakGlobals(IsMarkedCallback, this);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001028 timings_.EndSplit();
Carl Shapiro58551df2011-07-24 03:09:51 -07001029}
1030
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001031bool MarkSweep::VerifyIsLiveCallback(const Object* obj, void* arg) {
1032 reinterpret_cast<MarkSweep*>(arg)->VerifyIsLive(obj);
1033 // We don't actually want to sweep the object, so lets return "marked"
1034 return true;
1035}
1036
1037void MarkSweep::VerifyIsLive(const Object* obj) {
1038 Heap* heap = GetHeap();
1039 if (!heap->GetLiveBitmap()->Test(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001040 space::LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001041 if (!large_object_space->GetLiveObjects()->Test(obj)) {
1042 if (std::find(heap->allocation_stack_->Begin(), heap->allocation_stack_->End(), obj) ==
1043 heap->allocation_stack_->End()) {
1044 // Object not found!
1045 heap->DumpSpaces();
1046 LOG(FATAL) << "Found dead object " << obj;
1047 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001048 }
1049 }
1050}
1051
1052void MarkSweep::VerifySystemWeaks() {
1053 Runtime* runtime = Runtime::Current();
1054 // Verify system weaks, uses a special IsMarked callback which always returns true.
1055 runtime->GetInternTable()->SweepInternTableWeaks(VerifyIsLiveCallback, this);
1056 runtime->GetMonitorList()->SweepMonitorList(VerifyIsLiveCallback, this);
1057
1058 JavaVMExt* vm = runtime->GetJavaVM();
Ian Rogersb8a0b942013-08-20 18:09:52 -07001059 ReaderMutexLock mu(Thread::Current(), vm->weak_globals_lock);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001060 for (const Object** entry : vm->weak_globals) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001061 VerifyIsLive(*entry);
1062 }
1063}
1064
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001065struct SweepCallbackContext {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001066 MarkSweep* mark_sweep;
Ian Rogers1d54e732013-05-02 21:10:01 -07001067 space::AllocSpace* space;
Ian Rogers50b35e22012-10-04 10:09:15 -07001068 Thread* self;
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001069};
1070
Mathieu Chartier0e4627e2012-10-23 16:13:36 -07001071class CheckpointMarkThreadRoots : public Closure {
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001072 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001073 explicit CheckpointMarkThreadRoots(MarkSweep* mark_sweep) : mark_sweep_(mark_sweep) {}
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001074
1075 virtual void Run(Thread* thread) NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier3f966702013-09-04 16:50:05 -07001076 ATRACE_BEGIN("Marking thread roots");
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001077 // Note: self is not necessarily equal to thread since thread may be suspended.
1078 Thread* self = Thread::Current();
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001079 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
1080 << thread->GetState() << " thread " << thread << " self " << self;
Mathieu Chartierac86a7c2012-11-12 15:03:16 -08001081 thread->VisitRoots(MarkSweep::MarkRootParallelCallback, mark_sweep_);
Mathieu Chartier3f966702013-09-04 16:50:05 -07001082 ATRACE_END();
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001083 mark_sweep_->GetBarrier().Pass(self);
1084 }
1085
1086 private:
1087 MarkSweep* mark_sweep_;
1088};
1089
Ian Rogers1d54e732013-05-02 21:10:01 -07001090void MarkSweep::MarkRootsCheckpoint(Thread* self) {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001091 CheckpointMarkThreadRoots check_point(this);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001092 timings_.StartSplit("MarkRootsCheckpoint");
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001093 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Ian Rogers1d54e732013-05-02 21:10:01 -07001094 // Request the check point is run on all threads returning a count of the threads that must
1095 // run through the barrier including self.
1096 size_t barrier_count = thread_list->RunCheckpoint(&check_point);
1097 // Release locks then wait for all mutator threads to pass the barrier.
1098 // TODO: optimize to not release locks when there are no threads to wait for.
1099 Locks::heap_bitmap_lock_->ExclusiveUnlock(self);
1100 Locks::mutator_lock_->SharedUnlock(self);
1101 ThreadState old_state = self->SetState(kWaitingForCheckPointsToRun);
1102 CHECK_EQ(old_state, kWaitingPerformingGc);
1103 gc_barrier_->Increment(self, barrier_count);
1104 self->SetState(kWaitingPerformingGc);
1105 Locks::mutator_lock_->SharedLock(self);
1106 Locks::heap_bitmap_lock_->ExclusiveLock(self);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001107 timings_.EndSplit();
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001108}
1109
Ian Rogers30fab402012-01-23 15:43:46 -08001110void MarkSweep::SweepCallback(size_t num_ptrs, Object** ptrs, void* arg) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001111 SweepCallbackContext* context = static_cast<SweepCallbackContext*>(arg);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001112 MarkSweep* mark_sweep = context->mark_sweep;
1113 Heap* heap = mark_sweep->GetHeap();
Ian Rogers1d54e732013-05-02 21:10:01 -07001114 space::AllocSpace* space = context->space;
Ian Rogers50b35e22012-10-04 10:09:15 -07001115 Thread* self = context->self;
1116 Locks::heap_bitmap_lock_->AssertExclusiveHeld(self);
Ian Rogers5d76c432011-10-31 21:42:49 -07001117 // Use a bulk free, that merges consecutive objects before freeing or free per object?
1118 // Documentation suggests better free performance with merging, but this may be at the expensive
1119 // of allocation.
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001120 size_t freed_objects = num_ptrs;
1121 // AllocSpace::FreeList clears the value in ptrs, so perform after clearing the live bit
1122 size_t freed_bytes = space->FreeList(self, num_ptrs, ptrs);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001123 heap->RecordFree(freed_objects, freed_bytes);
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -07001124 mark_sweep->freed_objects_.fetch_add(freed_objects);
1125 mark_sweep->freed_bytes_.fetch_add(freed_bytes);
Carl Shapiro58551df2011-07-24 03:09:51 -07001126}
1127
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001128void MarkSweep::ZygoteSweepCallback(size_t num_ptrs, Object** ptrs, void* arg) {
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001129 SweepCallbackContext* context = static_cast<SweepCallbackContext*>(arg);
Ian Rogers50b35e22012-10-04 10:09:15 -07001130 Locks::heap_bitmap_lock_->AssertExclusiveHeld(context->self);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001131 Heap* heap = context->mark_sweep->GetHeap();
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001132 // We don't free any actual memory to avoid dirtying the shared zygote pages.
1133 for (size_t i = 0; i < num_ptrs; ++i) {
1134 Object* obj = static_cast<Object*>(ptrs[i]);
1135 heap->GetLiveBitmap()->Clear(obj);
1136 heap->GetCardTable()->MarkCard(obj);
1137 }
1138}
1139
Ian Rogers1d54e732013-05-02 21:10:01 -07001140void MarkSweep::SweepArray(accounting::ObjectStack* allocations, bool swap_bitmaps) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001141 space::DlMallocSpace* space = heap_->GetAllocSpace();
Elliott Hughes2da50362011-10-10 16:57:08 -07001142
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001143 timings_.StartSplit("SweepArray");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001144 // Newly allocated objects MUST be in the alloc space and those are the only objects which we are
1145 // going to free.
Ian Rogers1d54e732013-05-02 21:10:01 -07001146 accounting::SpaceBitmap* live_bitmap = space->GetLiveBitmap();
1147 accounting::SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
1148 space::LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
1149 accounting::SpaceSetMap* large_live_objects = large_object_space->GetLiveObjects();
1150 accounting::SpaceSetMap* large_mark_objects = large_object_space->GetMarkObjects();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001151 if (swap_bitmaps) {
1152 std::swap(live_bitmap, mark_bitmap);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001153 std::swap(large_live_objects, large_mark_objects);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001154 }
1155
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001156 size_t freed_bytes = 0;
1157 size_t freed_large_object_bytes = 0;
Hiroshi Yamauchib22a4512013-08-13 15:03:22 -07001158 size_t freed_objects = 0;
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001159 size_t freed_large_objects = 0;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001160 size_t count = allocations->Size();
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001161 Object** objects = const_cast<Object**>(allocations->Begin());
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001162 Object** out = objects;
Hiroshi Yamauchib22a4512013-08-13 15:03:22 -07001163 Object** objects_to_chunk_free = out;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001164
1165 // Empty the allocation stack.
Ian Rogers50b35e22012-10-04 10:09:15 -07001166 Thread* self = Thread::Current();
Brian Carlstrom02c8cc62013-07-18 15:54:44 -07001167 for (size_t i = 0; i < count; ++i) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001168 Object* obj = objects[i];
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001169 // There should only be objects in the AllocSpace/LargeObjectSpace in the allocation stack.
1170 if (LIKELY(mark_bitmap->HasAddress(obj))) {
1171 if (!mark_bitmap->Test(obj)) {
1172 // Don't bother un-marking since we clear the mark bitmap anyways.
1173 *(out++) = obj;
Hiroshi Yamauchib22a4512013-08-13 15:03:22 -07001174 // Free objects in chunks.
1175 DCHECK_GE(out, objects_to_chunk_free);
1176 DCHECK_LE(static_cast<size_t>(out - objects_to_chunk_free), kSweepArrayChunkFreeSize);
1177 if (static_cast<size_t>(out - objects_to_chunk_free) == kSweepArrayChunkFreeSize) {
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001178 timings_.StartSplit("FreeList");
Hiroshi Yamauchib22a4512013-08-13 15:03:22 -07001179 size_t chunk_freed_objects = out - objects_to_chunk_free;
1180 freed_objects += chunk_freed_objects;
1181 freed_bytes += space->FreeList(self, chunk_freed_objects, objects_to_chunk_free);
1182 objects_to_chunk_free = out;
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001183 timings_.EndSplit();
Hiroshi Yamauchib22a4512013-08-13 15:03:22 -07001184 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001185 }
1186 } else if (!large_mark_objects->Test(obj)) {
1187 ++freed_large_objects;
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001188 freed_large_object_bytes += large_object_space->Free(self, obj);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001189 }
1190 }
Hiroshi Yamauchib22a4512013-08-13 15:03:22 -07001191 // Free the remaining objects in chunks.
1192 DCHECK_GE(out, objects_to_chunk_free);
1193 DCHECK_LE(static_cast<size_t>(out - objects_to_chunk_free), kSweepArrayChunkFreeSize);
1194 if (out - objects_to_chunk_free > 0) {
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001195 timings_.StartSplit("FreeList");
Hiroshi Yamauchib22a4512013-08-13 15:03:22 -07001196 size_t chunk_freed_objects = out - objects_to_chunk_free;
1197 freed_objects += chunk_freed_objects;
1198 freed_bytes += space->FreeList(self, chunk_freed_objects, objects_to_chunk_free);
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001199 timings_.EndSplit();
Hiroshi Yamauchib22a4512013-08-13 15:03:22 -07001200 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001201 CHECK_EQ(count, allocations->Size());
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001202 timings_.EndSplit();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001203
Hiroshi Yamauchib22a4512013-08-13 15:03:22 -07001204 timings_.StartSplit("RecordFree");
Mathieu Chartier40e978b2012-09-07 11:38:36 -07001205 VLOG(heap) << "Freed " << freed_objects << "/" << count
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001206 << " objects with size " << PrettySize(freed_bytes);
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001207 heap_->RecordFree(freed_objects + freed_large_objects, freed_bytes + freed_large_object_bytes);
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -07001208 freed_objects_.fetch_add(freed_objects);
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001209 freed_large_objects_.fetch_add(freed_large_objects);
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -07001210 freed_bytes_.fetch_add(freed_bytes);
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001211 freed_large_object_bytes_.fetch_add(freed_large_object_bytes);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001212 timings_.EndSplit();
Ian Rogers1d54e732013-05-02 21:10:01 -07001213
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001214 timings_.StartSplit("ResetStack");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001215 allocations->Reset();
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001216 timings_.EndSplit();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001217}
1218
Ian Rogers1d54e732013-05-02 21:10:01 -07001219void MarkSweep::Sweep(bool swap_bitmaps) {
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001220 DCHECK(mark_stack_->IsEmpty());
Anwar Ghuloum46543222013-08-12 09:28:42 -07001221 base::TimingLogger::ScopedSplit("Sweep", &timings_);
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001222
Ian Rogers1d54e732013-05-02 21:10:01 -07001223 const bool partial = (GetGcType() == kGcTypePartial);
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001224 SweepCallbackContext scc;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001225 scc.mark_sweep = this;
Ian Rogers50b35e22012-10-04 10:09:15 -07001226 scc.self = Thread::Current();
Mathieu Chartier02e25112013-08-14 16:14:24 -07001227 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001228 // We always sweep always collect spaces.
1229 bool sweep_space = (space->GetGcRetentionPolicy() == space::kGcRetentionPolicyAlwaysCollect);
1230 if (!partial && !sweep_space) {
1231 // We sweep full collect spaces when the GC isn't a partial GC (ie its full).
1232 sweep_space = (space->GetGcRetentionPolicy() == space::kGcRetentionPolicyFullCollect);
1233 }
1234 if (sweep_space) {
Mathieu Chartier720ef762013-08-17 14:46:54 -07001235 uintptr_t begin = reinterpret_cast<uintptr_t>(space->Begin());
1236 uintptr_t end = reinterpret_cast<uintptr_t>(space->End());
Ian Rogers1d54e732013-05-02 21:10:01 -07001237 scc.space = space->AsDlMallocSpace();
1238 accounting::SpaceBitmap* live_bitmap = space->GetLiveBitmap();
1239 accounting::SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001240 if (swap_bitmaps) {
1241 std::swap(live_bitmap, mark_bitmap);
1242 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001243 if (!space->IsZygoteSpace()) {
Anwar Ghuloum46543222013-08-12 09:28:42 -07001244 base::TimingLogger::ScopedSplit split("SweepAllocSpace", &timings_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001245 // Bitmaps are pre-swapped for optimization which enables sweeping with the heap unlocked.
Ian Rogers1d54e732013-05-02 21:10:01 -07001246 accounting::SpaceBitmap::SweepWalk(*live_bitmap, *mark_bitmap, begin, end,
1247 &SweepCallback, reinterpret_cast<void*>(&scc));
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001248 } else {
Anwar Ghuloum46543222013-08-12 09:28:42 -07001249 base::TimingLogger::ScopedSplit split("SweepZygote", &timings_);
Ian Rogers1d54e732013-05-02 21:10:01 -07001250 // Zygote sweep takes care of dirtying cards and clearing live bits, does not free actual
1251 // memory.
1252 accounting::SpaceBitmap::SweepWalk(*live_bitmap, *mark_bitmap, begin, end,
1253 &ZygoteSweepCallback, reinterpret_cast<void*>(&scc));
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001254 }
Carl Shapiro58551df2011-07-24 03:09:51 -07001255 }
1256 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001257
1258 SweepLargeObjects(swap_bitmaps);
Carl Shapiro58551df2011-07-24 03:09:51 -07001259}
1260
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001261void MarkSweep::SweepLargeObjects(bool swap_bitmaps) {
Anwar Ghuloum46543222013-08-12 09:28:42 -07001262 base::TimingLogger::ScopedSplit("SweepLargeObjects", &timings_);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001263 // Sweep large objects
Ian Rogers1d54e732013-05-02 21:10:01 -07001264 space::LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
1265 accounting::SpaceSetMap* large_live_objects = large_object_space->GetLiveObjects();
1266 accounting::SpaceSetMap* large_mark_objects = large_object_space->GetMarkObjects();
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001267 if (swap_bitmaps) {
1268 std::swap(large_live_objects, large_mark_objects);
1269 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001270 // O(n*log(n)) but hopefully there are not too many large objects.
1271 size_t freed_objects = 0;
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001272 size_t freed_bytes = 0;
Ian Rogers50b35e22012-10-04 10:09:15 -07001273 Thread* self = Thread::Current();
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001274 for (const Object* obj : large_live_objects->GetObjects()) {
Mathieu Chartier02e25112013-08-14 16:14:24 -07001275 if (!large_mark_objects->Test(obj)) {
1276 freed_bytes += large_object_space->Free(self, const_cast<Object*>(obj));
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001277 ++freed_objects;
1278 }
1279 }
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001280 freed_large_objects_.fetch_add(freed_objects);
1281 freed_large_object_bytes_.fetch_add(freed_bytes);
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001282 GetHeap()->RecordFree(freed_objects, freed_bytes);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001283}
1284
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001285void MarkSweep::CheckReference(const Object* obj, const Object* ref, MemberOffset offset, bool is_static) {
Mathieu Chartier02e25112013-08-14 16:14:24 -07001286 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001287 if (space->IsDlMallocSpace() && space->Contains(ref)) {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001288 DCHECK(IsMarked(obj));
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001289
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001290 bool is_marked = IsMarked(ref);
1291 if (!is_marked) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001292 LOG(INFO) << *space;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001293 LOG(WARNING) << (is_static ? "Static ref'" : "Instance ref'") << PrettyTypeOf(ref)
1294 << "' (" << reinterpret_cast<const void*>(ref) << ") in '" << PrettyTypeOf(obj)
1295 << "' (" << reinterpret_cast<const void*>(obj) << ") at offset "
1296 << reinterpret_cast<void*>(offset.Int32Value()) << " wasn't marked";
Mathieu Chartier262e5ff2012-06-01 17:35:38 -07001297
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001298 const Class* klass = is_static ? obj->AsClass() : obj->GetClass();
1299 DCHECK(klass != NULL);
Brian Carlstromea46f952013-07-30 01:26:50 -07001300 const ObjectArray<ArtField>* fields = is_static ? klass->GetSFields() : klass->GetIFields();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001301 DCHECK(fields != NULL);
1302 bool found = false;
1303 for (int32_t i = 0; i < fields->GetLength(); ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001304 const ArtField* cur = fields->Get(i);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001305 if (cur->GetOffset().Int32Value() == offset.Int32Value()) {
1306 LOG(WARNING) << "Field referencing the alloc space was " << PrettyField(cur);
1307 found = true;
1308 break;
1309 }
1310 }
1311 if (!found) {
1312 LOG(WARNING) << "Could not find field in object alloc space with offset " << offset.Int32Value();
1313 }
Mathieu Chartier262e5ff2012-06-01 17:35:38 -07001314
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001315 bool obj_marked = heap_->GetCardTable()->IsDirty(obj);
1316 if (!obj_marked) {
1317 LOG(WARNING) << "Object '" << PrettyTypeOf(obj) << "' "
1318 << "(" << reinterpret_cast<const void*>(obj) << ") contains references to "
1319 << "the alloc space, but wasn't card marked";
Mathieu Chartier262e5ff2012-06-01 17:35:38 -07001320 }
1321 }
Ian Rogers5d76c432011-10-31 21:42:49 -07001322 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001323 break;
Ian Rogers5d76c432011-10-31 21:42:49 -07001324 }
1325}
1326
Carl Shapiro69759ea2011-07-21 18:13:35 -07001327// Process the "referent" field in a java.lang.ref.Reference. If the
1328// referent has not yet been marked, put it on the appropriate list in
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001329// the heap for later processing.
1330void MarkSweep::DelayReferenceReferent(mirror::Class* klass, Object* obj) {
1331 DCHECK(klass != nullptr);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001332 DCHECK(klass->IsReferenceClass());
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001333 DCHECK(obj != NULL);
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001334 Object* referent = heap_->GetReferenceReferent(obj);
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001335 if (referent != NULL && !IsMarked(referent)) {
1336 if (kCountJavaLangRefs) {
1337 ++reference_count_;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001338 }
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001339 Thread* self = Thread::Current();
1340 // TODO: Remove these locks, and use atomic stacks for storing references?
Mathieu Chartierb4ea4de2013-09-18 09:58:29 -07001341 // We need to check that the references haven't already been enqueued since we can end up
1342 // scanning the same reference multiple times due to dirty cards.
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001343 if (klass->IsSoftReferenceClass()) {
1344 MutexLock mu(self, *heap_->GetSoftRefQueueLock());
Mathieu Chartierb4ea4de2013-09-18 09:58:29 -07001345 if (!heap_->IsEnqueued(obj)) {
1346 heap_->EnqueuePendingReference(obj, &soft_reference_list_);
1347 }
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001348 } else if (klass->IsWeakReferenceClass()) {
1349 MutexLock mu(self, *heap_->GetWeakRefQueueLock());
Mathieu Chartierb4ea4de2013-09-18 09:58:29 -07001350 if (!heap_->IsEnqueued(obj)) {
1351 heap_->EnqueuePendingReference(obj, &weak_reference_list_);
1352 }
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001353 } else if (klass->IsFinalizerReferenceClass()) {
1354 MutexLock mu(self, *heap_->GetFinalizerRefQueueLock());
Mathieu Chartierb4ea4de2013-09-18 09:58:29 -07001355 if (!heap_->IsEnqueued(obj)) {
1356 heap_->EnqueuePendingReference(obj, &finalizer_reference_list_);
1357 }
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001358 } else if (klass->IsPhantomReferenceClass()) {
1359 MutexLock mu(self, *heap_->GetPhantomRefQueueLock());
Mathieu Chartierb4ea4de2013-09-18 09:58:29 -07001360 if (!heap_->IsEnqueued(obj)) {
1361 heap_->EnqueuePendingReference(obj, &phantom_reference_list_);
1362 }
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001363 } else {
1364 LOG(FATAL) << "Invalid reference type " << PrettyClass(klass)
1365 << " " << std::hex << klass->GetAccessFlags();
1366 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001367 }
1368}
1369
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001370void MarkSweep::ScanRoot(const Object* obj) {
1371 ScanObject(obj);
1372}
1373
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001374class MarkObjectVisitor {
1375 public:
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001376 explicit MarkObjectVisitor(MarkSweep* const mark_sweep) ALWAYS_INLINE : mark_sweep_(mark_sweep) {}
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001377
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001378 // TODO: Fixme when anotatalysis works with visitors.
Brian Carlstromdf629502013-07-17 22:39:56 -07001379 void operator()(const Object* /* obj */, const Object* ref, const MemberOffset& /* offset */,
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001380 bool /* is_static */) const ALWAYS_INLINE
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001381 NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001382 if (kCheckLocks) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001383 Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
1384 Locks::heap_bitmap_lock_->AssertExclusiveHeld(Thread::Current());
1385 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001386 mark_sweep_->MarkObject(ref);
1387 }
1388
1389 private:
1390 MarkSweep* const mark_sweep_;
1391};
1392
Carl Shapiro69759ea2011-07-21 18:13:35 -07001393// Scans an object reference. Determines the type of the reference
1394// and dispatches to a specialized scanning routine.
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001395void MarkSweep::ScanObject(const Object* obj) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001396 MarkObjectVisitor visitor(this);
1397 ScanObjectVisit(obj, visitor);
1398}
1399
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001400void MarkSweep::ProcessMarkStackParallel(size_t thread_count) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001401 Thread* self = Thread::Current();
1402 ThreadPool* thread_pool = GetHeap()->GetThreadPool();
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001403 const size_t chunk_size = std::min(mark_stack_->Size() / thread_count + 1,
1404 static_cast<size_t>(MarkStackTask<false>::kMaxSize));
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001405 CHECK_GT(chunk_size, 0U);
1406 // Split the current mark stack up into work tasks.
1407 for (mirror::Object **it = mark_stack_->Begin(), **end = mark_stack_->End(); it < end; ) {
1408 const size_t delta = std::min(static_cast<size_t>(end - it), chunk_size);
1409 thread_pool->AddTask(self, new MarkStackTask<false>(thread_pool, this, delta,
1410 const_cast<const mirror::Object**>(it)));
1411 it += delta;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001412 }
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001413 thread_pool->SetMaxActiveWorkers(thread_count - 1);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001414 thread_pool->StartWorkers(self);
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001415 thread_pool->Wait(self, true, true);
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001416 thread_pool->StopWorkers(self);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001417 mark_stack_->Reset();
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001418 CHECK_EQ(work_chunks_created_, work_chunks_deleted_) << " some of the work chunks were leaked";
Carl Shapiro69759ea2011-07-21 18:13:35 -07001419}
1420
Ian Rogers5d76c432011-10-31 21:42:49 -07001421// Scan anything that's on the mark stack.
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001422void MarkSweep::ProcessMarkStack(bool paused) {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001423 timings_.StartSplit("ProcessMarkStack");
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001424 size_t thread_count = GetThreadCount(paused);
1425 if (kParallelProcessMarkStack && thread_count > 1 &&
1426 mark_stack_->Size() >= kMinimumParallelMarkStackSize) {
1427 ProcessMarkStackParallel(thread_count);
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001428 } else {
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001429 // TODO: Tune this.
1430 static const size_t kFifoSize = 4;
1431 BoundedFifoPowerOfTwo<const Object*, kFifoSize> prefetch_fifo;
1432 for (;;) {
1433 const Object* obj = NULL;
1434 if (kUseMarkStackPrefetch) {
1435 while (!mark_stack_->IsEmpty() && prefetch_fifo.size() < kFifoSize) {
1436 const Object* obj = mark_stack_->PopBack();
1437 DCHECK(obj != NULL);
1438 __builtin_prefetch(obj);
1439 prefetch_fifo.push_back(obj);
1440 }
1441 if (prefetch_fifo.empty()) {
1442 break;
1443 }
1444 obj = prefetch_fifo.front();
1445 prefetch_fifo.pop_front();
1446 } else {
1447 if (mark_stack_->IsEmpty()) {
1448 break;
1449 }
1450 obj = mark_stack_->PopBack();
1451 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001452 DCHECK(obj != NULL);
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001453 ScanObject(obj);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001454 }
1455 }
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001456 timings_.EndSplit();
Carl Shapiro69759ea2011-07-21 18:13:35 -07001457}
1458
Carl Shapiro69759ea2011-07-21 18:13:35 -07001459// Walks the reference list marking any references subject to the
1460// reference clearing policy. References with a black referent are
1461// removed from the list. References with white referents biased
1462// toward saving are blackened and also removed from the list.
1463void MarkSweep::PreserveSomeSoftReferences(Object** list) {
1464 DCHECK(list != NULL);
1465 Object* clear = NULL;
1466 size_t counter = 0;
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001467
1468 DCHECK(mark_stack_->IsEmpty());
1469
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001470 timings_.StartSplit("PreserveSomeSoftReferences");
Carl Shapiro69759ea2011-07-21 18:13:35 -07001471 while (*list != NULL) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001472 Object* ref = heap_->DequeuePendingReference(list);
1473 Object* referent = heap_->GetReferenceReferent(ref);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001474 if (referent == NULL) {
1475 // Referent was cleared by the user during marking.
1476 continue;
1477 }
1478 bool is_marked = IsMarked(referent);
1479 if (!is_marked && ((++counter) & 1)) {
1480 // Referent is white and biased toward saving, mark it.
1481 MarkObject(referent);
1482 is_marked = true;
1483 }
1484 if (!is_marked) {
1485 // Referent is white, queue it for clearing.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001486 heap_->EnqueuePendingReference(ref, &clear);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001487 }
1488 }
1489 *list = clear;
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001490 timings_.EndSplit();
1491
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001492 // Restart the mark with the newly black references added to the root set.
1493 ProcessMarkStack(true);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001494}
1495
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001496inline bool MarkSweep::IsMarked(const Object* object) const
1497 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
Mathieu Chartier9642c962013-08-05 17:40:36 -07001498 if (IsImmune(object)) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001499 return true;
1500 }
1501 DCHECK(current_mark_bitmap_ != NULL);
1502 if (current_mark_bitmap_->HasAddress(object)) {
1503 return current_mark_bitmap_->Test(object);
1504 }
1505 return heap_->GetMarkBitmap()->Test(object);
1506}
1507
Carl Shapiro69759ea2011-07-21 18:13:35 -07001508// Unlink the reference list clearing references objects with white
1509// referents. Cleared references registered to a reference queue are
1510// scheduled for appending by the heap worker thread.
1511void MarkSweep::ClearWhiteReferences(Object** list) {
1512 DCHECK(list != NULL);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001513 while (*list != NULL) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001514 Object* ref = heap_->DequeuePendingReference(list);
1515 Object* referent = heap_->GetReferenceReferent(ref);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001516 if (referent != NULL && !IsMarked(referent)) {
1517 // Referent is white, clear it.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001518 heap_->ClearReferenceReferent(ref);
1519 if (heap_->IsEnqueuable(ref)) {
1520 heap_->EnqueueReference(ref, &cleared_reference_list_);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001521 }
1522 }
1523 }
1524 DCHECK(*list == NULL);
1525}
1526
1527// Enqueues finalizer references with white referents. White
1528// referents are blackened, moved to the zombie field, and the
1529// referent field is cleared.
1530void MarkSweep::EnqueueFinalizerReferences(Object** list) {
1531 DCHECK(list != NULL);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001532 timings_.StartSplit("EnqueueFinalizerReferences");
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001533 MemberOffset zombie_offset = heap_->GetFinalizerReferenceZombieOffset();
Carl Shapiro69759ea2011-07-21 18:13:35 -07001534 bool has_enqueued = false;
1535 while (*list != NULL) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001536 Object* ref = heap_->DequeuePendingReference(list);
1537 Object* referent = heap_->GetReferenceReferent(ref);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001538 if (referent != NULL && !IsMarked(referent)) {
1539 MarkObject(referent);
1540 // If the referent is non-null the reference must queuable.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001541 DCHECK(heap_->IsEnqueuable(ref));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001542 ref->SetFieldObject(zombie_offset, referent, false);
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001543 heap_->ClearReferenceReferent(ref);
1544 heap_->EnqueueReference(ref, &cleared_reference_list_);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001545 has_enqueued = true;
1546 }
1547 }
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001548 timings_.EndSplit();
Carl Shapiro69759ea2011-07-21 18:13:35 -07001549 if (has_enqueued) {
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001550 ProcessMarkStack(true);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001551 }
1552 DCHECK(*list == NULL);
1553}
1554
Carl Shapiro58551df2011-07-24 03:09:51 -07001555// Process reference class instances and schedule finalizations.
Carl Shapiro69759ea2011-07-21 18:13:35 -07001556void MarkSweep::ProcessReferences(Object** soft_references, bool clear_soft,
1557 Object** weak_references,
1558 Object** finalizer_references,
1559 Object** phantom_references) {
1560 DCHECK(soft_references != NULL);
1561 DCHECK(weak_references != NULL);
1562 DCHECK(finalizer_references != NULL);
1563 DCHECK(phantom_references != NULL);
1564
1565 // Unless we are in the zygote or required to clear soft references
1566 // with white references, preserve some white referents.
Ian Rogers2945e242012-06-03 14:45:16 -07001567 if (!clear_soft && !Runtime::Current()->IsZygote()) {
Carl Shapiro69759ea2011-07-21 18:13:35 -07001568 PreserveSomeSoftReferences(soft_references);
1569 }
1570
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001571 timings_.StartSplit("ProcessReferences");
Carl Shapiro69759ea2011-07-21 18:13:35 -07001572 // Clear all remaining soft and weak references with white
1573 // referents.
1574 ClearWhiteReferences(soft_references);
1575 ClearWhiteReferences(weak_references);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001576 timings_.EndSplit();
Carl Shapiro69759ea2011-07-21 18:13:35 -07001577
1578 // Preserve all white objects with finalize methods and schedule
1579 // them for finalization.
1580 EnqueueFinalizerReferences(finalizer_references);
1581
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001582 timings_.StartSplit("ProcessReferences");
Carl Shapiro69759ea2011-07-21 18:13:35 -07001583 // Clear all f-reachable soft and weak references with white
1584 // referents.
1585 ClearWhiteReferences(soft_references);
1586 ClearWhiteReferences(weak_references);
1587
1588 // Clear all phantom references with white referents.
1589 ClearWhiteReferences(phantom_references);
1590
1591 // At this point all reference lists should be empty.
1592 DCHECK(*soft_references == NULL);
1593 DCHECK(*weak_references == NULL);
1594 DCHECK(*finalizer_references == NULL);
1595 DCHECK(*phantom_references == NULL);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001596 timings_.EndSplit();
Carl Shapiro69759ea2011-07-21 18:13:35 -07001597}
1598
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001599void MarkSweep::UnBindBitmaps() {
Anwar Ghuloum46543222013-08-12 09:28:42 -07001600 base::TimingLogger::ScopedSplit split("UnBindBitmaps", &timings_);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001601 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001602 if (space->IsDlMallocSpace()) {
1603 space::DlMallocSpace* alloc_space = space->AsDlMallocSpace();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001604 if (alloc_space->temp_bitmap_.get() != NULL) {
1605 // At this point, the temp_bitmap holds our old mark bitmap.
Ian Rogers1d54e732013-05-02 21:10:01 -07001606 accounting::SpaceBitmap* new_bitmap = alloc_space->temp_bitmap_.release();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001607 GetHeap()->GetMarkBitmap()->ReplaceBitmap(alloc_space->mark_bitmap_.get(), new_bitmap);
1608 CHECK_EQ(alloc_space->mark_bitmap_.release(), alloc_space->live_bitmap_.get());
1609 alloc_space->mark_bitmap_.reset(new_bitmap);
1610 DCHECK(alloc_space->temp_bitmap_.get() == NULL);
1611 }
1612 }
1613 }
1614}
1615
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001616void MarkSweep::FinishPhase() {
Anwar Ghuloum46543222013-08-12 09:28:42 -07001617 base::TimingLogger::ScopedSplit split("FinishPhase", &timings_);
1618 // Can't enqueue references if we hold the mutator lock.
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001619 Object* cleared_references = GetClearedReferences();
Ian Rogers1d54e732013-05-02 21:10:01 -07001620 Heap* heap = GetHeap();
Anwar Ghuloum46543222013-08-12 09:28:42 -07001621 timings_.NewSplit("EnqueueClearedReferences");
Ian Rogers1d54e732013-05-02 21:10:01 -07001622 heap->EnqueueClearedReferences(&cleared_references);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001623
Anwar Ghuloum46543222013-08-12 09:28:42 -07001624 timings_.NewSplit("PostGcVerification");
Ian Rogers1d54e732013-05-02 21:10:01 -07001625 heap->PostGcVerification(this);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001626
Anwar Ghuloum46543222013-08-12 09:28:42 -07001627 timings_.NewSplit("GrowForUtilization");
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001628 heap->GrowForUtilization(GetGcType(), GetDurationNs());
Mathieu Chartier65db8802012-11-20 12:36:46 -08001629
Anwar Ghuloum46543222013-08-12 09:28:42 -07001630 timings_.NewSplit("RequestHeapTrim");
Ian Rogers1d54e732013-05-02 21:10:01 -07001631 heap->RequestHeapTrim();
Mathieu Chartier65db8802012-11-20 12:36:46 -08001632
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001633 // Update the cumulative statistics
Ian Rogers1d54e732013-05-02 21:10:01 -07001634 total_time_ns_ += GetDurationNs();
1635 total_paused_time_ns_ += std::accumulate(GetPauseTimes().begin(), GetPauseTimes().end(), 0,
1636 std::plus<uint64_t>());
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001637 total_freed_objects_ += GetFreedObjects() + GetFreedLargeObjects();
1638 total_freed_bytes_ += GetFreedBytes() + GetFreedLargeObjectBytes();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001639
1640 // Ensure that the mark stack is empty.
1641 CHECK(mark_stack_->IsEmpty());
1642
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001643 if (kCountScannedTypes) {
1644 VLOG(gc) << "MarkSweep scanned classes=" << class_count_ << " arrays=" << array_count_
1645 << " other=" << other_count_;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001646 }
1647
1648 if (kCountTasks) {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001649 VLOG(gc) << "Total number of work chunks allocated: " << work_chunks_created_;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001650 }
1651
1652 if (kMeasureOverhead) {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001653 VLOG(gc) << "Overhead time " << PrettyDuration(overhead_time_);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001654 }
1655
1656 if (kProfileLargeObjects) {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001657 VLOG(gc) << "Large objects tested " << large_object_test_ << " marked " << large_object_mark_;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001658 }
1659
1660 if (kCountClassesMarked) {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001661 VLOG(gc) << "Classes marked " << classes_marked_;
1662 }
1663
1664 if (kCountJavaLangRefs) {
1665 VLOG(gc) << "References scanned " << reference_count_;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001666 }
1667
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001668 // Update the cumulative loggers.
1669 cumulative_timings_.Start();
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001670 cumulative_timings_.AddLogger(timings_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001671 cumulative_timings_.End();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001672
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001673 // Clear all of the spaces' mark bitmaps.
Mathieu Chartier02e25112013-08-14 16:14:24 -07001674 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001675 if (space->GetGcRetentionPolicy() != space::kGcRetentionPolicyNeverCollect) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001676 space->GetMarkBitmap()->Clear();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001677 }
1678 }
Mathieu Chartier5301cd22012-05-31 12:11:36 -07001679 mark_stack_->Reset();
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001680
1681 // Reset the marked large objects.
Ian Rogers1d54e732013-05-02 21:10:01 -07001682 space::LargeObjectSpace* large_objects = GetHeap()->GetLargeObjectsSpace();
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001683 large_objects->GetMarkObjects()->Clear();
Carl Shapiro69759ea2011-07-21 18:13:35 -07001684}
1685
Ian Rogers1d54e732013-05-02 21:10:01 -07001686} // namespace collector
1687} // namespace gc
Carl Shapiro69759ea2011-07-21 18:13:35 -07001688} // namespace art