blob: f724cdbf18999b229cadc85e0dc2efea43aa1445 [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 Chartier8e56c7e2012-11-20 13:25:50 -0800188 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800189 ProcessReferences(&soft_reference_list_, clear_soft_references_, &weak_reference_list_,
190 &finalizer_reference_list_, &phantom_reference_list_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800191}
192
193bool MarkSweep::HandleDirtyObjectsPhase() {
Anwar Ghuloum46543222013-08-12 09:28:42 -0700194 base::TimingLogger::ScopedSplit split("HandleDirtyObjectsPhase", &timings_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800195 Thread* self = Thread::Current();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800196 Locks::mutator_lock_->AssertExclusiveHeld(self);
197
198 {
199 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
200
201 // Re-mark root set.
202 ReMarkRoots();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800203
204 // Scan dirty objects, this is only required if we are not doing concurrent GC.
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700205 RecursiveMarkDirtyObjects(true, accounting::CardTable::kCardDirty);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800206 }
207
208 ProcessReferences(self);
209
210 // Only need to do this if we have the card mark verification on, and only during concurrent GC.
211 if (GetHeap()->verify_missing_card_marks_) {
212 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
213 // This second sweep makes sure that we don't have any objects in the live stack which point to
214 // freed objects. These cause problems since their references may be previously freed objects.
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700215 SweepArray(GetHeap()->allocation_stack_.get(), false);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800216 }
217 return true;
218}
219
220bool MarkSweep::IsConcurrent() const {
221 return is_concurrent_;
222}
223
224void MarkSweep::MarkingPhase() {
Anwar Ghuloum46543222013-08-12 09:28:42 -0700225 base::TimingLogger::ScopedSplit split("MarkingPhase", &timings_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800226 Heap* heap = GetHeap();
227 Thread* self = Thread::Current();
228
229 BindBitmaps();
230 FindDefaultMarkBitmap();
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700231
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800232 // Process dirty cards and add dirty cards to mod union tables.
233 heap->ProcessCards(timings_);
234
235 // Need to do this before the checkpoint since we don't want any threads to add references to
236 // the live stack during the recursive mark.
Anwar Ghuloum46543222013-08-12 09:28:42 -0700237 timings_.NewSplit("SwapStacks");
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800238 heap->SwapStacks();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800239
240 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
241 if (Locks::mutator_lock_->IsExclusiveHeld(self)) {
242 // If we exclusively hold the mutator lock, all threads must be suspended.
243 MarkRoots();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800244 } else {
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700245 MarkThreadRoots(self);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800246 MarkNonThreadRoots();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800247 }
248 MarkConcurrentRoots();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800249
250 heap->UpdateAndMarkModUnion(this, timings_, GetGcType());
251 MarkReachableObjects();
252}
253
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700254void MarkSweep::MarkThreadRoots(Thread* self) {
255 MarkRootsCheckpoint(self);
256}
257
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800258void MarkSweep::MarkReachableObjects() {
259 // Mark everything allocated since the last as GC live so that we can sweep concurrently,
260 // knowing that new allocations won't be marked as live.
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700261 timings_.StartSplit("MarkStackAsLive");
Ian Rogers1d54e732013-05-02 21:10:01 -0700262 accounting::ObjectStack* live_stack = heap_->GetLiveStack();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800263 heap_->MarkAllocStack(heap_->alloc_space_->GetLiveBitmap(),
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700264 heap_->large_object_space_->GetLiveObjects(), live_stack);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800265 live_stack->Reset();
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700266 timings_.EndSplit();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800267 // Recursively mark all the non-image bits set in the mark bitmap.
268 RecursiveMark();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800269}
270
271void MarkSweep::ReclaimPhase() {
Anwar Ghuloum46543222013-08-12 09:28:42 -0700272 base::TimingLogger::ScopedSplit split("ReclaimPhase", &timings_);
Mathieu Chartier720ef762013-08-17 14:46:54 -0700273 Thread* self = Thread::Current();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800274
275 if (!IsConcurrent()) {
Anwar Ghulouma9a50922013-08-09 21:34:20 -0700276 base::TimingLogger::ScopedSplit split("ProcessReferences", &timings_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800277 ProcessReferences(self);
Mathieu Chartier9642c962013-08-05 17:40:36 -0700278 } else {
Anwar Ghulouma9a50922013-08-09 21:34:20 -0700279 base::TimingLogger::ScopedSplit split("UnMarkAllocStack", &timings_);
Mathieu Chartier9642c962013-08-05 17:40:36 -0700280 accounting::ObjectStack* allocation_stack = GetHeap()->allocation_stack_.get();
281 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
282 // The allocation stack contains things allocated since the start of the GC. These may have been
283 // marked during this GC meaning they won't be eligible for reclaiming in the next sticky GC.
284 // Remove these objects from the mark bitmaps so that they will be eligible for sticky
285 // collection.
286 // There is a race here which is safely handled. Another thread such as the hprof could
287 // have flushed the alloc stack after we resumed the threads. This is safe however, since
288 // reseting the allocation stack zeros it out with madvise. This means that we will either
289 // read NULLs or attempt to unmark a newly allocated object which will not be marked in the
290 // first place.
291 mirror::Object** end = allocation_stack->End();
292 for (mirror::Object** it = allocation_stack->Begin(); it != end; ++it) {
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700293 const Object* obj = *it;
Mathieu Chartier9642c962013-08-05 17:40:36 -0700294 if (obj != NULL) {
295 UnMarkObjectNonNull(obj);
296 }
297 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800298 }
299
300 // Before freeing anything, lets verify the heap.
301 if (kIsDebugBuild) {
302 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
303 VerifyImageRoots();
304 }
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700305 timings_.StartSplit("PreSweepingGcVerification");
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800306 heap_->PreSweepingGcVerification(this);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700307 timings_.EndSplit();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800308
309 {
310 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
311
312 // Reclaim unmarked objects.
Ian Rogers1d54e732013-05-02 21:10:01 -0700313 Sweep(false);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800314
315 // Swap the live and mark bitmaps for each space which we modified space. This is an
316 // optimization that enables us to not clear live bits inside of the sweep. Only swaps unbound
317 // bitmaps.
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700318 timings_.StartSplit("SwapBitmaps");
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800319 SwapBitmaps();
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700320 timings_.EndSplit();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800321
322 // Unbind the live and mark bitmaps.
323 UnBindBitmaps();
324 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800325}
326
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800327void MarkSweep::SetImmuneRange(Object* begin, Object* end) {
328 immune_begin_ = begin;
329 immune_end_ = end;
Carl Shapiro58551df2011-07-24 03:09:51 -0700330}
331
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700332void MarkSweep::FindDefaultMarkBitmap() {
Anwar Ghuloum46543222013-08-12 09:28:42 -0700333 base::TimingLogger::ScopedSplit split("FindDefaultMarkBitmap", &timings_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700334 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700335 if (space->GetGcRetentionPolicy() == space::kGcRetentionPolicyAlwaysCollect) {
Mathieu Chartier02e25112013-08-14 16:14:24 -0700336 current_mark_bitmap_ = space->GetMarkBitmap();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700337 CHECK(current_mark_bitmap_ != NULL);
338 return;
339 }
340 }
341 GetHeap()->DumpSpaces();
342 LOG(FATAL) << "Could not find a default mark bitmap";
343}
344
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800345void MarkSweep::ExpandMarkStack() {
Mathieu Chartierba311b42013-08-27 13:02:30 -0700346 ResizeMarkStack(mark_stack_->Capacity() * 2);
347}
348
349void MarkSweep::ResizeMarkStack(size_t new_size) {
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800350 // Rare case, no need to have Thread::Current be a parameter.
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800351 if (UNLIKELY(mark_stack_->Size() < mark_stack_->Capacity())) {
352 // Someone else acquired the lock and expanded the mark stack before us.
353 return;
354 }
Mathieu Chartier02e25112013-08-14 16:14:24 -0700355 std::vector<Object*> temp(mark_stack_->Begin(), mark_stack_->End());
Mathieu Chartierba311b42013-08-27 13:02:30 -0700356 CHECK_LE(mark_stack_->Size(), new_size);
357 mark_stack_->Resize(new_size);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700358 for (const auto& obj : temp) {
359 mark_stack_->PushBack(obj);
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800360 }
361}
362
Mathieu Chartier9642c962013-08-05 17:40:36 -0700363inline void MarkSweep::MarkObjectNonNullParallel(const Object* obj) {
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800364 DCHECK(obj != NULL);
365 if (MarkObjectParallel(obj)) {
Mathieu Chartierba311b42013-08-27 13:02:30 -0700366 MutexLock mu(Thread::Current(), mark_stack_lock_);
367 if (UNLIKELY(mark_stack_->Size() >= mark_stack_->Capacity())) {
Mathieu Chartier184e3222013-08-03 14:02:57 -0700368 ExpandMarkStack();
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800369 }
Mathieu Chartierba311b42013-08-27 13:02:30 -0700370 // The object must be pushed on to the mark stack.
371 mark_stack_->PushBack(const_cast<Object*>(obj));
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800372 }
373}
374
Mathieu Chartier9642c962013-08-05 17:40:36 -0700375inline void MarkSweep::UnMarkObjectNonNull(const Object* obj) {
376 DCHECK(!IsImmune(obj));
377 // Try to take advantage of locality of references within a space, failing this find the space
378 // the hard way.
379 accounting::SpaceBitmap* object_bitmap = current_mark_bitmap_;
380 if (UNLIKELY(!object_bitmap->HasAddress(obj))) {
381 accounting::SpaceBitmap* new_bitmap = heap_->GetMarkBitmap()->GetContinuousSpaceBitmap(obj);
382 if (LIKELY(new_bitmap != NULL)) {
383 object_bitmap = new_bitmap;
384 } else {
385 MarkLargeObject(obj, false);
386 return;
387 }
388 }
389
390 DCHECK(object_bitmap->HasAddress(obj));
391 object_bitmap->Clear(obj);
392}
393
394inline void MarkSweep::MarkObjectNonNull(const Object* obj) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700395 DCHECK(obj != NULL);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700396
Mathieu Chartier9642c962013-08-05 17:40:36 -0700397 if (IsImmune(obj)) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700398 DCHECK(IsMarked(obj));
Carl Shapiro69759ea2011-07-21 18:13:35 -0700399 return;
400 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700401
402 // Try to take advantage of locality of references within a space, failing this find the space
403 // the hard way.
Ian Rogers1d54e732013-05-02 21:10:01 -0700404 accounting::SpaceBitmap* object_bitmap = current_mark_bitmap_;
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700405 if (UNLIKELY(!object_bitmap->HasAddress(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700406 accounting::SpaceBitmap* new_bitmap = heap_->GetMarkBitmap()->GetContinuousSpaceBitmap(obj);
407 if (LIKELY(new_bitmap != NULL)) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700408 object_bitmap = new_bitmap;
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700409 } else {
Mathieu Chartier9642c962013-08-05 17:40:36 -0700410 MarkLargeObject(obj, true);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700411 return;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700412 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700413 }
414
Carl Shapiro69759ea2011-07-21 18:13:35 -0700415 // This object was not previously marked.
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700416 if (!object_bitmap->Test(obj)) {
417 object_bitmap->Set(obj);
Mathieu Chartierba311b42013-08-27 13:02:30 -0700418 // Lock is not needed but is here anyways to please annotalysis.
419 MutexLock mu(Thread::Current(), mark_stack_lock_);
Mathieu Chartier184e3222013-08-03 14:02:57 -0700420 if (UNLIKELY(mark_stack_->Size() >= mark_stack_->Capacity())) {
421 ExpandMarkStack();
Carl Shapiro69759ea2011-07-21 18:13:35 -0700422 }
Mathieu Chartier184e3222013-08-03 14:02:57 -0700423 // The object must be pushed on to the mark stack.
424 mark_stack_->PushBack(const_cast<Object*>(obj));
Carl Shapiro69759ea2011-07-21 18:13:35 -0700425 }
426}
427
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700428// Rare case, probably not worth inlining since it will increase instruction cache miss rate.
Mathieu Chartier9642c962013-08-05 17:40:36 -0700429bool MarkSweep::MarkLargeObject(const Object* obj, bool set) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700430 // TODO: support >1 discontinuous space.
431 space::LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
432 accounting::SpaceSetMap* large_objects = large_object_space->GetMarkObjects();
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700433 if (kProfileLargeObjects) {
434 ++large_object_test_;
435 }
436 if (UNLIKELY(!large_objects->Test(obj))) {
Mathieu Chartier4fcb8d32013-07-15 12:43:36 -0700437 if (!large_object_space->Contains(obj)) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700438 LOG(ERROR) << "Tried to mark " << obj << " not contained by any spaces";
439 LOG(ERROR) << "Attempting see if it's a bad root";
440 VerifyRoots();
441 LOG(FATAL) << "Can't mark bad root";
442 }
443 if (kProfileLargeObjects) {
444 ++large_object_mark_;
445 }
Mathieu Chartier9642c962013-08-05 17:40:36 -0700446 if (set) {
447 large_objects->Set(obj);
448 } else {
449 large_objects->Clear(obj);
450 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700451 return true;
452 }
453 return false;
454}
455
456inline bool MarkSweep::MarkObjectParallel(const Object* obj) {
457 DCHECK(obj != NULL);
458
Mathieu Chartier9642c962013-08-05 17:40:36 -0700459 if (IsImmune(obj)) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700460 DCHECK(IsMarked(obj));
461 return false;
462 }
463
464 // Try to take advantage of locality of references within a space, failing this find the space
465 // the hard way.
Ian Rogers1d54e732013-05-02 21:10:01 -0700466 accounting::SpaceBitmap* object_bitmap = current_mark_bitmap_;
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700467 if (UNLIKELY(!object_bitmap->HasAddress(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700468 accounting::SpaceBitmap* new_bitmap = heap_->GetMarkBitmap()->GetContinuousSpaceBitmap(obj);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700469 if (new_bitmap != NULL) {
470 object_bitmap = new_bitmap;
471 } else {
472 // TODO: Remove the Thread::Current here?
473 // TODO: Convert this to some kind of atomic marking?
474 MutexLock mu(Thread::Current(), large_object_lock_);
Mathieu Chartier9642c962013-08-05 17:40:36 -0700475 return MarkLargeObject(obj, true);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700476 }
477 }
478
479 // Return true if the object was not previously marked.
480 return !object_bitmap->AtomicTestAndSet(obj);
481}
482
Carl Shapiro69759ea2011-07-21 18:13:35 -0700483// Used to mark objects when recursing. Recursion is done by moving
484// the finger across the bitmaps in address order and marking child
485// objects. Any newly-marked objects whose addresses are lower than
486// the finger won't be visited by the bitmap scan, so those objects
487// need to be added to the mark stack.
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700488inline void MarkSweep::MarkObject(const Object* obj) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700489 if (obj != NULL) {
Mathieu Chartier9642c962013-08-05 17:40:36 -0700490 MarkObjectNonNull(obj);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700491 }
492}
493
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800494void MarkSweep::MarkRoot(const Object* obj) {
495 if (obj != NULL) {
Mathieu Chartier9642c962013-08-05 17:40:36 -0700496 MarkObjectNonNull(obj);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800497 }
498}
499
Mathieu Chartier423d2a32013-09-12 17:33:56 -0700500Object* MarkSweep::MarkRootParallelCallback(Object* root, void* arg) {
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800501 DCHECK(root != NULL);
502 DCHECK(arg != NULL);
Mathieu Chartierba311b42013-08-27 13:02:30 -0700503 reinterpret_cast<MarkSweep*>(arg)->MarkObjectNonNullParallel(root);
Mathieu Chartier423d2a32013-09-12 17:33:56 -0700504 return root;
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800505}
506
Mathieu Chartier423d2a32013-09-12 17:33:56 -0700507Object* MarkSweep::MarkRootCallback(Object* root, void* arg) {
508 DCHECK(root != nullptr);
509 DCHECK(arg != nullptr);
510 reinterpret_cast<MarkSweep*>(arg)->MarkObjectNonNull(root);
511 return root;
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700512}
513
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700514void MarkSweep::VerifyRootCallback(const Object* root, void* arg, size_t vreg,
Ian Rogers40e3bac2012-11-20 00:09:14 -0800515 const StackVisitor* visitor) {
516 reinterpret_cast<MarkSweep*>(arg)->VerifyRoot(root, vreg, visitor);
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700517}
518
Ian Rogers40e3bac2012-11-20 00:09:14 -0800519void MarkSweep::VerifyRoot(const Object* root, size_t vreg, const StackVisitor* visitor) {
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700520 // See if the root is on any space bitmap.
Ian Rogers1d54e732013-05-02 21:10:01 -0700521 if (GetHeap()->GetLiveBitmap()->GetContinuousSpaceBitmap(root) == NULL) {
522 space::LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
Mathieu Chartier4202b742012-10-17 17:51:25 -0700523 if (!large_object_space->Contains(root)) {
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700524 LOG(ERROR) << "Found invalid root: " << root;
Ian Rogers40e3bac2012-11-20 00:09:14 -0800525 if (visitor != NULL) {
526 LOG(ERROR) << visitor->DescribeLocation() << " in VReg: " << vreg;
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700527 }
528 }
529 }
530}
531
532void MarkSweep::VerifyRoots() {
533 Runtime::Current()->GetThreadList()->VerifyRoots(VerifyRootCallback, this);
534}
535
Carl Shapiro69759ea2011-07-21 18:13:35 -0700536// Marks all objects in the root set.
537void MarkSweep::MarkRoots() {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700538 timings_.StartSplit("MarkRoots");
Mathieu Chartier423d2a32013-09-12 17:33:56 -0700539 Runtime::Current()->VisitNonConcurrentRoots(MarkRootCallback, this);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700540 timings_.EndSplit();
Mathieu Chartier9ebae1f2012-10-15 17:38:16 -0700541}
542
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700543void MarkSweep::MarkNonThreadRoots() {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700544 timings_.StartSplit("MarkNonThreadRoots");
Mathieu Chartier423d2a32013-09-12 17:33:56 -0700545 Runtime::Current()->VisitNonThreadRoots(MarkRootCallback, this);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700546 timings_.EndSplit();
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700547}
548
Mathieu Chartier9ebae1f2012-10-15 17:38:16 -0700549void MarkSweep::MarkConcurrentRoots() {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700550 timings_.StartSplit("MarkConcurrentRoots");
Ian Rogers1d54e732013-05-02 21:10:01 -0700551 // Visit all runtime roots and clear dirty flags.
Mathieu Chartier423d2a32013-09-12 17:33:56 -0700552 Runtime::Current()->VisitConcurrentRoots(MarkRootCallback, this, false, true);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700553 timings_.EndSplit();
Carl Shapiro69759ea2011-07-21 18:13:35 -0700554}
555
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700556void MarkSweep::CheckObject(const Object* obj) {
557 DCHECK(obj != NULL);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700558 VisitObjectReferences(obj, [this](const Object* obj, const Object* ref, MemberOffset offset,
559 bool is_static) NO_THREAD_SAFETY_ANALYSIS {
560 Locks::heap_bitmap_lock_->AssertSharedHeld(Thread::Current());
561 CheckReference(obj, ref, offset, is_static);
562 });
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700563}
564
565void MarkSweep::VerifyImageRootVisitor(Object* root, void* arg) {
566 DCHECK(root != NULL);
567 DCHECK(arg != NULL);
568 MarkSweep* mark_sweep = reinterpret_cast<MarkSweep*>(arg);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700569 DCHECK(mark_sweep->heap_->GetMarkBitmap()->Test(root));
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700570 mark_sweep->CheckObject(root);
571}
572
Ian Rogers1d54e732013-05-02 21:10:01 -0700573void MarkSweep::BindLiveToMarkBitmap(space::ContinuousSpace* space) {
574 CHECK(space->IsDlMallocSpace());
575 space::DlMallocSpace* alloc_space = space->AsDlMallocSpace();
576 accounting::SpaceBitmap* live_bitmap = space->GetLiveBitmap();
577 accounting::SpaceBitmap* mark_bitmap = alloc_space->mark_bitmap_.release();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700578 GetHeap()->GetMarkBitmap()->ReplaceBitmap(mark_bitmap, live_bitmap);
579 alloc_space->temp_bitmap_.reset(mark_bitmap);
580 alloc_space->mark_bitmap_.reset(live_bitmap);
581}
582
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700583class ScanObjectVisitor {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700584 public:
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700585 explicit ScanObjectVisitor(MarkSweep* const mark_sweep) ALWAYS_INLINE
586 : mark_sweep_(mark_sweep) {}
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700587
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800588 // TODO: Fixme when anotatalysis works with visitors.
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700589 void operator()(const Object* obj) const ALWAYS_INLINE NO_THREAD_SAFETY_ANALYSIS {
590 if (kCheckLocks) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800591 Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
592 Locks::heap_bitmap_lock_->AssertExclusiveHeld(Thread::Current());
593 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700594 mark_sweep_->ScanObject(obj);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700595 }
596
597 private:
598 MarkSweep* const mark_sweep_;
599};
600
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700601template <bool kUseFinger = false>
602class MarkStackTask : public Task {
603 public:
604 MarkStackTask(ThreadPool* thread_pool, MarkSweep* mark_sweep, size_t mark_stack_size,
605 const Object** mark_stack)
606 : mark_sweep_(mark_sweep),
607 thread_pool_(thread_pool),
608 mark_stack_pos_(mark_stack_size) {
609 // We may have to copy part of an existing mark stack when another mark stack overflows.
610 if (mark_stack_size != 0) {
611 DCHECK(mark_stack != NULL);
612 // TODO: Check performance?
613 std::copy(mark_stack, mark_stack + mark_stack_size, mark_stack_);
Ian Rogers1d54e732013-05-02 21:10:01 -0700614 }
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700615 if (kCountTasks) {
616 ++mark_sweep_->work_chunks_created_;
617 }
618 }
619
620 static const size_t kMaxSize = 1 * KB;
621
622 protected:
623 class ScanObjectParallelVisitor {
624 public:
625 explicit ScanObjectParallelVisitor(MarkStackTask<kUseFinger>* chunk_task) ALWAYS_INLINE
626 : chunk_task_(chunk_task) {}
627
628 void operator()(const Object* obj) const {
629 MarkSweep* mark_sweep = chunk_task_->mark_sweep_;
630 mark_sweep->ScanObjectVisit(obj,
631 [mark_sweep, this](const Object* /* obj */, const Object* ref,
632 const MemberOffset& /* offset */, bool /* is_static */) ALWAYS_INLINE {
633 if (ref != nullptr && mark_sweep->MarkObjectParallel(ref)) {
634 if (kUseFinger) {
635 android_memory_barrier();
636 if (reinterpret_cast<uintptr_t>(ref) >=
637 static_cast<uintptr_t>(mark_sweep->atomic_finger_)) {
638 return;
639 }
640 }
641 chunk_task_->MarkStackPush(ref);
642 }
643 });
644 }
645
646 private:
647 MarkStackTask<kUseFinger>* const chunk_task_;
648 };
649
650 virtual ~MarkStackTask() {
651 // Make sure that we have cleared our mark stack.
652 DCHECK_EQ(mark_stack_pos_, 0U);
653 if (kCountTasks) {
654 ++mark_sweep_->work_chunks_deleted_;
655 }
656 }
657
658 MarkSweep* const mark_sweep_;
659 ThreadPool* const thread_pool_;
660 // Thread local mark stack for this task.
661 const Object* mark_stack_[kMaxSize];
662 // Mark stack position.
663 size_t mark_stack_pos_;
664
665 void MarkStackPush(const Object* obj) ALWAYS_INLINE {
666 if (UNLIKELY(mark_stack_pos_ == kMaxSize)) {
667 // Mark stack overflow, give 1/2 the stack to the thread pool as a new work task.
668 mark_stack_pos_ /= 2;
669 auto* task = new MarkStackTask(thread_pool_, mark_sweep_, kMaxSize - mark_stack_pos_,
670 mark_stack_ + mark_stack_pos_);
671 thread_pool_->AddTask(Thread::Current(), task);
672 }
673 DCHECK(obj != nullptr);
674 DCHECK(mark_stack_pos_ < kMaxSize);
675 mark_stack_[mark_stack_pos_++] = obj;
676 }
677
678 virtual void Finalize() {
679 delete this;
680 }
681
682 // Scans all of the objects
683 virtual void Run(Thread* self) {
684 ScanObjectParallelVisitor visitor(this);
685 // TODO: Tune this.
686 static const size_t kFifoSize = 4;
687 BoundedFifoPowerOfTwo<const Object*, kFifoSize> prefetch_fifo;
688 for (;;) {
689 const Object* obj = NULL;
690 if (kUseMarkStackPrefetch) {
691 while (mark_stack_pos_ != 0 && prefetch_fifo.size() < kFifoSize) {
692 const Object* obj = mark_stack_[--mark_stack_pos_];
693 DCHECK(obj != NULL);
694 __builtin_prefetch(obj);
695 prefetch_fifo.push_back(obj);
696 }
697 if (UNLIKELY(prefetch_fifo.empty())) {
698 break;
699 }
700 obj = prefetch_fifo.front();
701 prefetch_fifo.pop_front();
702 } else {
703 if (UNLIKELY(mark_stack_pos_ == 0)) {
704 break;
705 }
706 obj = mark_stack_[--mark_stack_pos_];
707 }
708 DCHECK(obj != NULL);
709 visitor(obj);
710 }
711 }
712};
713
714class CardScanTask : public MarkStackTask<false> {
715 public:
716 CardScanTask(ThreadPool* thread_pool, MarkSweep* mark_sweep, accounting::SpaceBitmap* bitmap,
717 byte* begin, byte* end, byte minimum_age, size_t mark_stack_size,
718 const Object** mark_stack_obj)
719 : MarkStackTask<false>(thread_pool, mark_sweep, mark_stack_size, mark_stack_obj),
720 bitmap_(bitmap),
721 begin_(begin),
722 end_(end),
723 minimum_age_(minimum_age) {
724 }
725
726 protected:
727 accounting::SpaceBitmap* const bitmap_;
728 byte* const begin_;
729 byte* const end_;
730 const byte minimum_age_;
731
732 virtual void Finalize() {
733 delete this;
734 }
735
736 virtual void Run(Thread* self) NO_THREAD_SAFETY_ANALYSIS {
737 ScanObjectParallelVisitor visitor(this);
738 accounting::CardTable* card_table = mark_sweep_->GetHeap()->GetCardTable();
739 card_table->Scan(bitmap_, begin_, end_, visitor, minimum_age_);
740 // Finish by emptying our local mark stack.
741 MarkStackTask::Run(self);
742 }
743};
744
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700745size_t MarkSweep::GetThreadCount(bool paused) const {
746 if (heap_->GetThreadPool() == nullptr || !heap_->CareAboutPauseTimes()) {
747 return 0;
748 }
749 if (paused) {
750 return heap_->GetParallelGCThreadCount() + 1;
751 } else {
752 return heap_->GetConcGCThreadCount() + 1;
753 }
754}
755
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700756void MarkSweep::ScanGrayObjects(bool paused, byte minimum_age) {
757 accounting::CardTable* card_table = GetHeap()->GetCardTable();
758 ThreadPool* thread_pool = GetHeap()->GetThreadPool();
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700759 size_t thread_count = GetThreadCount(paused);
760 // The parallel version with only one thread is faster for card scanning, TODO: fix.
761 if (kParallelCardScan && thread_count > 0) {
Mathieu Chartier720ef762013-08-17 14:46:54 -0700762 Thread* self = Thread::Current();
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700763 // Can't have a different split for each space since multiple spaces can have their cards being
764 // scanned at the same time.
765 timings_.StartSplit(paused ? "(Paused)ScanGrayObjects" : "ScanGrayObjects");
766 // Try to take some of the mark stack since we can pass this off to the worker tasks.
767 const Object** mark_stack_begin = const_cast<const Object**>(mark_stack_->Begin());
768 const Object** mark_stack_end = const_cast<const Object**>(mark_stack_->End());
Mathieu Chartier720ef762013-08-17 14:46:54 -0700769 const size_t mark_stack_size = mark_stack_end - mark_stack_begin;
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700770 // Estimated number of work tasks we will create.
771 const size_t mark_stack_tasks = GetHeap()->GetContinuousSpaces().size() * thread_count;
772 DCHECK_NE(mark_stack_tasks, 0U);
773 const size_t mark_stack_delta = std::min(CardScanTask::kMaxSize / 2,
774 mark_stack_size / mark_stack_tasks + 1);
775 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
776 byte* card_begin = space->Begin();
777 byte* card_end = space->End();
778 // Calculate how many bytes of heap we will scan,
779 const size_t address_range = card_end - card_begin;
780 // Calculate how much address range each task gets.
781 const size_t card_delta = RoundUp(address_range / thread_count + 1,
782 accounting::CardTable::kCardSize);
783 // Create the worker tasks for this space.
784 while (card_begin != card_end) {
785 // Add a range of cards.
786 size_t addr_remaining = card_end - card_begin;
787 size_t card_increment = std::min(card_delta, addr_remaining);
788 // Take from the back of the mark stack.
789 size_t mark_stack_remaining = mark_stack_end - mark_stack_begin;
790 size_t mark_stack_increment = std::min(mark_stack_delta, mark_stack_remaining);
791 mark_stack_end -= mark_stack_increment;
792 mark_stack_->PopBackCount(static_cast<int32_t>(mark_stack_increment));
793 DCHECK_EQ(mark_stack_end, mark_stack_->End());
794 // Add the new task to the thread pool.
795 auto* task = new CardScanTask(thread_pool, this, space->GetMarkBitmap(), card_begin,
796 card_begin + card_increment, minimum_age,
797 mark_stack_increment, mark_stack_end);
798 thread_pool->AddTask(self, task);
799 card_begin += card_increment;
800 }
801 }
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700802 thread_pool->SetMaxActiveWorkers(thread_count - 1);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700803 thread_pool->StartWorkers(self);
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700804 thread_pool->Wait(self, true, true);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700805 thread_pool->StopWorkers(self);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700806 timings_.EndSplit();
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700807 } else {
808 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
809 // Image spaces are handled properly since live == marked for them.
810 switch (space->GetGcRetentionPolicy()) {
811 case space::kGcRetentionPolicyNeverCollect:
812 timings_.StartSplit(paused ? "(Paused)ScanGrayImageSpaceObjects" :
813 "ScanGrayImageSpaceObjects");
814 break;
815 case space::kGcRetentionPolicyFullCollect:
816 timings_.StartSplit(paused ? "(Paused)ScanGrayZygoteSpaceObjects" :
817 "ScanGrayZygoteSpaceObjects");
818 break;
819 case space::kGcRetentionPolicyAlwaysCollect:
820 timings_.StartSplit(paused ? "(Paused)ScanGrayAllocSpaceObjects" :
821 "ScanGrayAllocSpaceObjects");
822 break;
823 }
824 ScanObjectVisitor visitor(this);
825 card_table->Scan(space->GetMarkBitmap(), space->Begin(), space->End(), visitor, minimum_age);
826 timings_.EndSplit();
827 }
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700828 }
829}
830
831void MarkSweep::VerifyImageRoots() {
832 // Verify roots ensures that all the references inside the image space point
833 // objects which are either in the image space or marked objects in the alloc
834 // space
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700835 timings_.StartSplit("VerifyImageRoots");
Mathieu Chartier02e25112013-08-14 16:14:24 -0700836 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
837 if (space->IsImageSpace()) {
838 space::ImageSpace* image_space = space->AsImageSpace();
839 uintptr_t begin = reinterpret_cast<uintptr_t>(image_space->Begin());
840 uintptr_t end = reinterpret_cast<uintptr_t>(image_space->End());
841 accounting::SpaceBitmap* live_bitmap = image_space->GetLiveBitmap();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700842 DCHECK(live_bitmap != NULL);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700843 live_bitmap->VisitMarkedRange(begin, end, [this](const Object* obj) {
844 if (kCheckLocks) {
845 Locks::heap_bitmap_lock_->AssertSharedHeld(Thread::Current());
846 }
847 DCHECK(obj != NULL);
848 CheckObject(obj);
849 });
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700850 }
851 }
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700852 timings_.EndSplit();
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700853}
854
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700855class RecursiveMarkTask : public MarkStackTask<false> {
856 public:
857 RecursiveMarkTask(ThreadPool* thread_pool, MarkSweep* mark_sweep,
858 accounting::SpaceBitmap* bitmap, uintptr_t begin, uintptr_t end)
859 : MarkStackTask<false>(thread_pool, mark_sweep, 0, NULL),
860 bitmap_(bitmap),
861 begin_(begin),
862 end_(end) {
863 }
864
865 protected:
866 accounting::SpaceBitmap* const bitmap_;
867 const uintptr_t begin_;
868 const uintptr_t end_;
869
870 virtual void Finalize() {
871 delete this;
872 }
873
874 // Scans all of the objects
875 virtual void Run(Thread* self) NO_THREAD_SAFETY_ANALYSIS {
876 ScanObjectParallelVisitor visitor(this);
877 bitmap_->VisitMarkedRange(begin_, end_, visitor);
878 // Finish by emptying our local mark stack.
879 MarkStackTask::Run(self);
880 }
881};
882
Carl Shapiro58551df2011-07-24 03:09:51 -0700883// Populates the mark stack based on the set of marked objects and
884// recursively marks until the mark stack is emptied.
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800885void MarkSweep::RecursiveMark() {
Anwar Ghuloum46543222013-08-12 09:28:42 -0700886 base::TimingLogger::ScopedSplit split("RecursiveMark", &timings_);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700887 // RecursiveMark will build the lists of known instances of the Reference classes.
888 // See DelayReferenceReferent for details.
889 CHECK(soft_reference_list_ == NULL);
890 CHECK(weak_reference_list_ == NULL);
891 CHECK(finalizer_reference_list_ == NULL);
892 CHECK(phantom_reference_list_ == NULL);
893 CHECK(cleared_reference_list_ == NULL);
894
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700895 if (kUseRecursiveMark) {
896 const bool partial = GetGcType() == kGcTypePartial;
897 ScanObjectVisitor scan_visitor(this);
898 auto* self = Thread::Current();
899 ThreadPool* thread_pool = heap_->GetThreadPool();
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700900 size_t thread_count = GetThreadCount(false);
901 const bool parallel = kParallelRecursiveMark && thread_count > 1;
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700902 mark_stack_->Reset();
Mathieu Chartier02e25112013-08-14 16:14:24 -0700903 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700904 if ((space->GetGcRetentionPolicy() == space::kGcRetentionPolicyAlwaysCollect) ||
905 (!partial && space->GetGcRetentionPolicy() == space::kGcRetentionPolicyFullCollect)) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800906 current_mark_bitmap_ = space->GetMarkBitmap();
907 if (current_mark_bitmap_ == NULL) {
908 GetHeap()->DumpSpaces();
909 LOG(FATAL) << "invalid bitmap";
910 }
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700911 if (parallel) {
912 // We will use the mark stack the future.
913 // CHECK(mark_stack_->IsEmpty());
914 // This function does not handle heap end increasing, so we must use the space end.
915 uintptr_t begin = reinterpret_cast<uintptr_t>(space->Begin());
916 uintptr_t end = reinterpret_cast<uintptr_t>(space->End());
917 atomic_finger_ = static_cast<int32_t>(0xFFFFFFFF);
918
919 // Create a few worker tasks.
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700920 const size_t n = thread_count * 2;
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700921 while (begin != end) {
922 uintptr_t start = begin;
923 uintptr_t delta = (end - begin) / n;
924 delta = RoundUp(delta, KB);
925 if (delta < 16 * KB) delta = end - begin;
926 begin += delta;
927 auto* task = new RecursiveMarkTask(thread_pool, this, current_mark_bitmap_, start,
928 begin);
929 thread_pool->AddTask(self, task);
930 }
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700931 thread_pool->SetMaxActiveWorkers(thread_count - 1);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700932 thread_pool->StartWorkers(self);
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700933 thread_pool->Wait(self, true, true);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700934 thread_pool->StopWorkers(self);
935 } else {
936 // This function does not handle heap end increasing, so we must use the space end.
937 uintptr_t begin = reinterpret_cast<uintptr_t>(space->Begin());
938 uintptr_t end = reinterpret_cast<uintptr_t>(space->End());
939 current_mark_bitmap_->VisitMarkedRange(begin, end, scan_visitor);
940 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700941 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700942 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700943 }
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700944 ProcessMarkStack(false);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700945}
946
947bool MarkSweep::IsMarkedCallback(const Object* object, void* arg) {
948 return
949 reinterpret_cast<MarkSweep*>(arg)->IsMarked(object) ||
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700950 !reinterpret_cast<MarkSweep*>(arg)->GetHeap()->GetLiveBitmap()->Test(object);
951}
952
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700953void MarkSweep::RecursiveMarkDirtyObjects(bool paused, byte minimum_age) {
954 ScanGrayObjects(paused, minimum_age);
955 ProcessMarkStack(paused);
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700956}
957
Carl Shapiro58551df2011-07-24 03:09:51 -0700958void MarkSweep::ReMarkRoots() {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700959 timings_.StartSplit("ReMarkRoots");
Mathieu Chartier423d2a32013-09-12 17:33:56 -0700960 Runtime::Current()->VisitRoots(MarkRootCallback, this, true, true);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700961 timings_.EndSplit();
Carl Shapiro69759ea2011-07-21 18:13:35 -0700962}
963
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800964void MarkSweep::SweepJniWeakGlobals(IsMarkedTester is_marked, void* arg) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700965 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
Ian Rogersb8a0b942013-08-20 18:09:52 -0700966 WriterMutexLock mu(Thread::Current(), vm->weak_globals_lock);
Mathieu Chartier423d2a32013-09-12 17:33:56 -0700967 for (Object** entry : vm->weak_globals) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700968 if (!is_marked(*entry, arg)) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700969 *entry = kClearedJniWeakGlobal;
970 }
971 }
972}
973
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700974struct ArrayMarkedCheck {
Ian Rogers1d54e732013-05-02 21:10:01 -0700975 accounting::ObjectStack* live_stack;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700976 MarkSweep* mark_sweep;
977};
978
979// Either marked or not live.
980bool MarkSweep::IsMarkedArrayCallback(const Object* object, void* arg) {
981 ArrayMarkedCheck* array_check = reinterpret_cast<ArrayMarkedCheck*>(arg);
982 if (array_check->mark_sweep->IsMarked(object)) {
983 return true;
984 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700985 accounting::ObjectStack* live_stack = array_check->live_stack;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700986 return std::find(live_stack->Begin(), live_stack->End(), object) == live_stack->End();
987}
988
Ian Rogers1d54e732013-05-02 21:10:01 -0700989void MarkSweep::SweepSystemWeaksArray(accounting::ObjectStack* allocations) {
Mathieu Chartier46a23632012-08-07 18:44:40 -0700990 Runtime* runtime = Runtime::Current();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700991 // The callbacks check
992 // !is_marked where is_marked is the callback but we want
993 // !IsMarked && IsLive
994 // So compute !(!IsMarked && IsLive) which is equal to (IsMarked || !IsLive).
995 // Or for swapped (IsLive || !IsMarked).
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700996
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700997 timings_.StartSplit("SweepSystemWeaksArray");
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700998 ArrayMarkedCheck visitor;
999 visitor.live_stack = allocations;
1000 visitor.mark_sweep = this;
1001 runtime->GetInternTable()->SweepInternTableWeaks(IsMarkedArrayCallback, &visitor);
1002 runtime->GetMonitorList()->SweepMonitorList(IsMarkedArrayCallback, &visitor);
1003 SweepJniWeakGlobals(IsMarkedArrayCallback, &visitor);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001004 timings_.EndSplit();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001005}
1006
1007void MarkSweep::SweepSystemWeaks() {
1008 Runtime* runtime = Runtime::Current();
1009 // The callbacks check
1010 // !is_marked where is_marked is the callback but we want
1011 // !IsMarked && IsLive
1012 // So compute !(!IsMarked && IsLive) which is equal to (IsMarked || !IsLive).
1013 // Or for swapped (IsLive || !IsMarked).
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001014 timings_.StartSplit("SweepSystemWeaks");
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001015 runtime->GetInternTable()->SweepInternTableWeaks(IsMarkedCallback, this);
1016 runtime->GetMonitorList()->SweepMonitorList(IsMarkedCallback, this);
1017 SweepJniWeakGlobals(IsMarkedCallback, this);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001018 timings_.EndSplit();
Carl Shapiro58551df2011-07-24 03:09:51 -07001019}
1020
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001021bool MarkSweep::VerifyIsLiveCallback(const Object* obj, void* arg) {
1022 reinterpret_cast<MarkSweep*>(arg)->VerifyIsLive(obj);
1023 // We don't actually want to sweep the object, so lets return "marked"
1024 return true;
1025}
1026
1027void MarkSweep::VerifyIsLive(const Object* obj) {
1028 Heap* heap = GetHeap();
1029 if (!heap->GetLiveBitmap()->Test(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001030 space::LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001031 if (!large_object_space->GetLiveObjects()->Test(obj)) {
1032 if (std::find(heap->allocation_stack_->Begin(), heap->allocation_stack_->End(), obj) ==
1033 heap->allocation_stack_->End()) {
1034 // Object not found!
1035 heap->DumpSpaces();
1036 LOG(FATAL) << "Found dead object " << obj;
1037 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001038 }
1039 }
1040}
1041
1042void MarkSweep::VerifySystemWeaks() {
1043 Runtime* runtime = Runtime::Current();
1044 // Verify system weaks, uses a special IsMarked callback which always returns true.
1045 runtime->GetInternTable()->SweepInternTableWeaks(VerifyIsLiveCallback, this);
1046 runtime->GetMonitorList()->SweepMonitorList(VerifyIsLiveCallback, this);
1047
1048 JavaVMExt* vm = runtime->GetJavaVM();
Ian Rogersb8a0b942013-08-20 18:09:52 -07001049 ReaderMutexLock mu(Thread::Current(), vm->weak_globals_lock);
Mathieu Chartier423d2a32013-09-12 17:33:56 -07001050 for (Object** entry : vm->weak_globals) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001051 VerifyIsLive(*entry);
1052 }
1053}
1054
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001055struct SweepCallbackContext {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001056 MarkSweep* mark_sweep;
Ian Rogers1d54e732013-05-02 21:10:01 -07001057 space::AllocSpace* space;
Ian Rogers50b35e22012-10-04 10:09:15 -07001058 Thread* self;
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001059};
1060
Mathieu Chartier0e4627e2012-10-23 16:13:36 -07001061class CheckpointMarkThreadRoots : public Closure {
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001062 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001063 explicit CheckpointMarkThreadRoots(MarkSweep* mark_sweep) : mark_sweep_(mark_sweep) {}
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001064
1065 virtual void Run(Thread* thread) NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier3f966702013-09-04 16:50:05 -07001066 ATRACE_BEGIN("Marking thread roots");
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001067 // Note: self is not necessarily equal to thread since thread may be suspended.
1068 Thread* self = Thread::Current();
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001069 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
1070 << thread->GetState() << " thread " << thread << " self " << self;
Mathieu Chartierac86a7c2012-11-12 15:03:16 -08001071 thread->VisitRoots(MarkSweep::MarkRootParallelCallback, mark_sweep_);
Mathieu Chartier3f966702013-09-04 16:50:05 -07001072 ATRACE_END();
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001073 mark_sweep_->GetBarrier().Pass(self);
1074 }
1075
1076 private:
1077 MarkSweep* mark_sweep_;
1078};
1079
Ian Rogers1d54e732013-05-02 21:10:01 -07001080void MarkSweep::MarkRootsCheckpoint(Thread* self) {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001081 CheckpointMarkThreadRoots check_point(this);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001082 timings_.StartSplit("MarkRootsCheckpoint");
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001083 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Ian Rogers1d54e732013-05-02 21:10:01 -07001084 // Request the check point is run on all threads returning a count of the threads that must
1085 // run through the barrier including self.
1086 size_t barrier_count = thread_list->RunCheckpoint(&check_point);
1087 // Release locks then wait for all mutator threads to pass the barrier.
1088 // TODO: optimize to not release locks when there are no threads to wait for.
1089 Locks::heap_bitmap_lock_->ExclusiveUnlock(self);
1090 Locks::mutator_lock_->SharedUnlock(self);
1091 ThreadState old_state = self->SetState(kWaitingForCheckPointsToRun);
1092 CHECK_EQ(old_state, kWaitingPerformingGc);
1093 gc_barrier_->Increment(self, barrier_count);
1094 self->SetState(kWaitingPerformingGc);
1095 Locks::mutator_lock_->SharedLock(self);
1096 Locks::heap_bitmap_lock_->ExclusiveLock(self);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001097 timings_.EndSplit();
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001098}
1099
Ian Rogers30fab402012-01-23 15:43:46 -08001100void MarkSweep::SweepCallback(size_t num_ptrs, Object** ptrs, void* arg) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001101 SweepCallbackContext* context = static_cast<SweepCallbackContext*>(arg);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001102 MarkSweep* mark_sweep = context->mark_sweep;
1103 Heap* heap = mark_sweep->GetHeap();
Ian Rogers1d54e732013-05-02 21:10:01 -07001104 space::AllocSpace* space = context->space;
Ian Rogers50b35e22012-10-04 10:09:15 -07001105 Thread* self = context->self;
1106 Locks::heap_bitmap_lock_->AssertExclusiveHeld(self);
Ian Rogers5d76c432011-10-31 21:42:49 -07001107 // Use a bulk free, that merges consecutive objects before freeing or free per object?
1108 // Documentation suggests better free performance with merging, but this may be at the expensive
1109 // of allocation.
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001110 size_t freed_objects = num_ptrs;
1111 // AllocSpace::FreeList clears the value in ptrs, so perform after clearing the live bit
1112 size_t freed_bytes = space->FreeList(self, num_ptrs, ptrs);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001113 heap->RecordFree(freed_objects, freed_bytes);
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -07001114 mark_sweep->freed_objects_.fetch_add(freed_objects);
1115 mark_sweep->freed_bytes_.fetch_add(freed_bytes);
Carl Shapiro58551df2011-07-24 03:09:51 -07001116}
1117
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001118void MarkSweep::ZygoteSweepCallback(size_t num_ptrs, Object** ptrs, void* arg) {
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001119 SweepCallbackContext* context = static_cast<SweepCallbackContext*>(arg);
Ian Rogers50b35e22012-10-04 10:09:15 -07001120 Locks::heap_bitmap_lock_->AssertExclusiveHeld(context->self);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001121 Heap* heap = context->mark_sweep->GetHeap();
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001122 // We don't free any actual memory to avoid dirtying the shared zygote pages.
1123 for (size_t i = 0; i < num_ptrs; ++i) {
1124 Object* obj = static_cast<Object*>(ptrs[i]);
1125 heap->GetLiveBitmap()->Clear(obj);
1126 heap->GetCardTable()->MarkCard(obj);
1127 }
1128}
1129
Ian Rogers1d54e732013-05-02 21:10:01 -07001130void MarkSweep::SweepArray(accounting::ObjectStack* allocations, bool swap_bitmaps) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001131 space::DlMallocSpace* space = heap_->GetAllocSpace();
Elliott Hughes2da50362011-10-10 16:57:08 -07001132
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001133 // If we don't swap bitmaps then newly allocated Weaks go into the live bitmap but not mark
1134 // bitmap, resulting in occasional frees of Weaks which are still in use.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001135 SweepSystemWeaksArray(allocations);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001136
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001137 timings_.StartSplit("SweepArray");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001138 // Newly allocated objects MUST be in the alloc space and those are the only objects which we are
1139 // going to free.
Ian Rogers1d54e732013-05-02 21:10:01 -07001140 accounting::SpaceBitmap* live_bitmap = space->GetLiveBitmap();
1141 accounting::SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
1142 space::LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
1143 accounting::SpaceSetMap* large_live_objects = large_object_space->GetLiveObjects();
1144 accounting::SpaceSetMap* large_mark_objects = large_object_space->GetMarkObjects();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001145 if (swap_bitmaps) {
1146 std::swap(live_bitmap, mark_bitmap);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001147 std::swap(large_live_objects, large_mark_objects);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001148 }
1149
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001150 size_t freed_bytes = 0;
1151 size_t freed_large_object_bytes = 0;
Hiroshi Yamauchib22a4512013-08-13 15:03:22 -07001152 size_t freed_objects = 0;
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001153 size_t freed_large_objects = 0;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001154 size_t count = allocations->Size();
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001155 Object** objects = const_cast<Object**>(allocations->Begin());
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001156 Object** out = objects;
Hiroshi Yamauchib22a4512013-08-13 15:03:22 -07001157 Object** objects_to_chunk_free = out;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001158
1159 // Empty the allocation stack.
Ian Rogers50b35e22012-10-04 10:09:15 -07001160 Thread* self = Thread::Current();
Brian Carlstrom02c8cc62013-07-18 15:54:44 -07001161 for (size_t i = 0; i < count; ++i) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001162 Object* obj = objects[i];
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001163 // There should only be objects in the AllocSpace/LargeObjectSpace in the allocation stack.
1164 if (LIKELY(mark_bitmap->HasAddress(obj))) {
1165 if (!mark_bitmap->Test(obj)) {
1166 // Don't bother un-marking since we clear the mark bitmap anyways.
1167 *(out++) = obj;
Hiroshi Yamauchib22a4512013-08-13 15:03:22 -07001168 // Free objects in chunks.
1169 DCHECK_GE(out, objects_to_chunk_free);
1170 DCHECK_LE(static_cast<size_t>(out - objects_to_chunk_free), kSweepArrayChunkFreeSize);
1171 if (static_cast<size_t>(out - objects_to_chunk_free) == kSweepArrayChunkFreeSize) {
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001172 timings_.StartSplit("FreeList");
Hiroshi Yamauchib22a4512013-08-13 15:03:22 -07001173 size_t chunk_freed_objects = out - objects_to_chunk_free;
1174 freed_objects += chunk_freed_objects;
1175 freed_bytes += space->FreeList(self, chunk_freed_objects, objects_to_chunk_free);
1176 objects_to_chunk_free = out;
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001177 timings_.EndSplit();
Hiroshi Yamauchib22a4512013-08-13 15:03:22 -07001178 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001179 }
1180 } else if (!large_mark_objects->Test(obj)) {
1181 ++freed_large_objects;
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001182 freed_large_object_bytes += large_object_space->Free(self, obj);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001183 }
1184 }
Hiroshi Yamauchib22a4512013-08-13 15:03:22 -07001185 // Free the remaining objects in chunks.
1186 DCHECK_GE(out, objects_to_chunk_free);
1187 DCHECK_LE(static_cast<size_t>(out - objects_to_chunk_free), kSweepArrayChunkFreeSize);
1188 if (out - objects_to_chunk_free > 0) {
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001189 timings_.StartSplit("FreeList");
Hiroshi Yamauchib22a4512013-08-13 15:03:22 -07001190 size_t chunk_freed_objects = out - objects_to_chunk_free;
1191 freed_objects += chunk_freed_objects;
1192 freed_bytes += space->FreeList(self, chunk_freed_objects, objects_to_chunk_free);
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001193 timings_.EndSplit();
Hiroshi Yamauchib22a4512013-08-13 15:03:22 -07001194 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001195 CHECK_EQ(count, allocations->Size());
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001196 timings_.EndSplit();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001197
Hiroshi Yamauchib22a4512013-08-13 15:03:22 -07001198 timings_.StartSplit("RecordFree");
Mathieu Chartier40e978b2012-09-07 11:38:36 -07001199 VLOG(heap) << "Freed " << freed_objects << "/" << count
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001200 << " objects with size " << PrettySize(freed_bytes);
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001201 heap_->RecordFree(freed_objects + freed_large_objects, freed_bytes + freed_large_object_bytes);
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -07001202 freed_objects_.fetch_add(freed_objects);
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001203 freed_large_objects_.fetch_add(freed_large_objects);
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -07001204 freed_bytes_.fetch_add(freed_bytes);
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001205 freed_large_object_bytes_.fetch_add(freed_large_object_bytes);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001206 timings_.EndSplit();
Ian Rogers1d54e732013-05-02 21:10:01 -07001207
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001208 timings_.StartSplit("ResetStack");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001209 allocations->Reset();
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001210 timings_.EndSplit();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001211}
1212
Ian Rogers1d54e732013-05-02 21:10:01 -07001213void MarkSweep::Sweep(bool swap_bitmaps) {
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001214 DCHECK(mark_stack_->IsEmpty());
Anwar Ghuloum46543222013-08-12 09:28:42 -07001215 base::TimingLogger::ScopedSplit("Sweep", &timings_);
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001216
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001217 // If we don't swap bitmaps then newly allocated Weaks go into the live bitmap but not mark
1218 // bitmap, resulting in occasional frees of Weaks which are still in use.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001219 SweepSystemWeaks();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001220
Ian Rogers1d54e732013-05-02 21:10:01 -07001221 const bool partial = (GetGcType() == kGcTypePartial);
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001222 SweepCallbackContext scc;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001223 scc.mark_sweep = this;
Ian Rogers50b35e22012-10-04 10:09:15 -07001224 scc.self = Thread::Current();
Mathieu Chartier02e25112013-08-14 16:14:24 -07001225 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001226 // We always sweep always collect spaces.
1227 bool sweep_space = (space->GetGcRetentionPolicy() == space::kGcRetentionPolicyAlwaysCollect);
1228 if (!partial && !sweep_space) {
1229 // We sweep full collect spaces when the GC isn't a partial GC (ie its full).
1230 sweep_space = (space->GetGcRetentionPolicy() == space::kGcRetentionPolicyFullCollect);
1231 }
1232 if (sweep_space) {
Mathieu Chartier720ef762013-08-17 14:46:54 -07001233 uintptr_t begin = reinterpret_cast<uintptr_t>(space->Begin());
1234 uintptr_t end = reinterpret_cast<uintptr_t>(space->End());
Ian Rogers1d54e732013-05-02 21:10:01 -07001235 scc.space = space->AsDlMallocSpace();
1236 accounting::SpaceBitmap* live_bitmap = space->GetLiveBitmap();
1237 accounting::SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001238 if (swap_bitmaps) {
1239 std::swap(live_bitmap, mark_bitmap);
1240 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001241 if (!space->IsZygoteSpace()) {
Anwar Ghuloum46543222013-08-12 09:28:42 -07001242 base::TimingLogger::ScopedSplit split("SweepAllocSpace", &timings_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001243 // Bitmaps are pre-swapped for optimization which enables sweeping with the heap unlocked.
Ian Rogers1d54e732013-05-02 21:10:01 -07001244 accounting::SpaceBitmap::SweepWalk(*live_bitmap, *mark_bitmap, begin, end,
1245 &SweepCallback, reinterpret_cast<void*>(&scc));
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001246 } else {
Anwar Ghuloum46543222013-08-12 09:28:42 -07001247 base::TimingLogger::ScopedSplit split("SweepZygote", &timings_);
Ian Rogers1d54e732013-05-02 21:10:01 -07001248 // Zygote sweep takes care of dirtying cards and clearing live bits, does not free actual
1249 // memory.
1250 accounting::SpaceBitmap::SweepWalk(*live_bitmap, *mark_bitmap, begin, end,
1251 &ZygoteSweepCallback, reinterpret_cast<void*>(&scc));
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001252 }
Carl Shapiro58551df2011-07-24 03:09:51 -07001253 }
1254 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001255
1256 SweepLargeObjects(swap_bitmaps);
Carl Shapiro58551df2011-07-24 03:09:51 -07001257}
1258
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001259void MarkSweep::SweepLargeObjects(bool swap_bitmaps) {
Anwar Ghuloum46543222013-08-12 09:28:42 -07001260 base::TimingLogger::ScopedSplit("SweepLargeObjects", &timings_);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001261 // Sweep large objects
Ian Rogers1d54e732013-05-02 21:10:01 -07001262 space::LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
1263 accounting::SpaceSetMap* large_live_objects = large_object_space->GetLiveObjects();
1264 accounting::SpaceSetMap* large_mark_objects = large_object_space->GetMarkObjects();
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001265 if (swap_bitmaps) {
1266 std::swap(large_live_objects, large_mark_objects);
1267 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001268 // O(n*log(n)) but hopefully there are not too many large objects.
1269 size_t freed_objects = 0;
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001270 size_t freed_bytes = 0;
Ian Rogers50b35e22012-10-04 10:09:15 -07001271 Thread* self = Thread::Current();
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001272 for (const Object* obj : large_live_objects->GetObjects()) {
Mathieu Chartier02e25112013-08-14 16:14:24 -07001273 if (!large_mark_objects->Test(obj)) {
1274 freed_bytes += large_object_space->Free(self, const_cast<Object*>(obj));
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001275 ++freed_objects;
1276 }
1277 }
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001278 freed_large_objects_.fetch_add(freed_objects);
1279 freed_large_object_bytes_.fetch_add(freed_bytes);
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001280 GetHeap()->RecordFree(freed_objects, freed_bytes);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001281}
1282
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001283void MarkSweep::CheckReference(const Object* obj, const Object* ref, MemberOffset offset, bool is_static) {
Mathieu Chartier02e25112013-08-14 16:14:24 -07001284 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001285 if (space->IsDlMallocSpace() && space->Contains(ref)) {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001286 DCHECK(IsMarked(obj));
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001287
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001288 bool is_marked = IsMarked(ref);
1289 if (!is_marked) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001290 LOG(INFO) << *space;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001291 LOG(WARNING) << (is_static ? "Static ref'" : "Instance ref'") << PrettyTypeOf(ref)
1292 << "' (" << reinterpret_cast<const void*>(ref) << ") in '" << PrettyTypeOf(obj)
1293 << "' (" << reinterpret_cast<const void*>(obj) << ") at offset "
1294 << reinterpret_cast<void*>(offset.Int32Value()) << " wasn't marked";
Mathieu Chartier262e5ff2012-06-01 17:35:38 -07001295
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001296 const Class* klass = is_static ? obj->AsClass() : obj->GetClass();
1297 DCHECK(klass != NULL);
Brian Carlstromea46f952013-07-30 01:26:50 -07001298 const ObjectArray<ArtField>* fields = is_static ? klass->GetSFields() : klass->GetIFields();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001299 DCHECK(fields != NULL);
1300 bool found = false;
1301 for (int32_t i = 0; i < fields->GetLength(); ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001302 const ArtField* cur = fields->Get(i);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001303 if (cur->GetOffset().Int32Value() == offset.Int32Value()) {
1304 LOG(WARNING) << "Field referencing the alloc space was " << PrettyField(cur);
1305 found = true;
1306 break;
1307 }
1308 }
1309 if (!found) {
1310 LOG(WARNING) << "Could not find field in object alloc space with offset " << offset.Int32Value();
1311 }
Mathieu Chartier262e5ff2012-06-01 17:35:38 -07001312
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001313 bool obj_marked = heap_->GetCardTable()->IsDirty(obj);
1314 if (!obj_marked) {
1315 LOG(WARNING) << "Object '" << PrettyTypeOf(obj) << "' "
1316 << "(" << reinterpret_cast<const void*>(obj) << ") contains references to "
1317 << "the alloc space, but wasn't card marked";
Mathieu Chartier262e5ff2012-06-01 17:35:38 -07001318 }
1319 }
Ian Rogers5d76c432011-10-31 21:42:49 -07001320 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001321 break;
Ian Rogers5d76c432011-10-31 21:42:49 -07001322 }
1323}
1324
Carl Shapiro69759ea2011-07-21 18:13:35 -07001325// Process the "referent" field in a java.lang.ref.Reference. If the
1326// referent has not yet been marked, put it on the appropriate list in
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001327// the heap for later processing.
1328void MarkSweep::DelayReferenceReferent(mirror::Class* klass, Object* obj) {
1329 DCHECK(klass != nullptr);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001330 DCHECK(klass->IsReferenceClass());
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001331 DCHECK(obj != NULL);
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001332 Object* referent = heap_->GetReferenceReferent(obj);
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001333 if (referent != NULL && !IsMarked(referent)) {
1334 if (kCountJavaLangRefs) {
1335 ++reference_count_;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001336 }
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001337 Thread* self = Thread::Current();
1338 // TODO: Remove these locks, and use atomic stacks for storing references?
1339 if (klass->IsSoftReferenceClass()) {
1340 MutexLock mu(self, *heap_->GetSoftRefQueueLock());
1341 heap_->EnqueuePendingReference(obj, &soft_reference_list_);
1342 } else if (klass->IsWeakReferenceClass()) {
1343 MutexLock mu(self, *heap_->GetWeakRefQueueLock());
1344 heap_->EnqueuePendingReference(obj, &weak_reference_list_);
1345 } else if (klass->IsFinalizerReferenceClass()) {
1346 MutexLock mu(self, *heap_->GetFinalizerRefQueueLock());
1347 heap_->EnqueuePendingReference(obj, &finalizer_reference_list_);
1348 } else if (klass->IsPhantomReferenceClass()) {
1349 MutexLock mu(self, *heap_->GetPhantomRefQueueLock());
1350 heap_->EnqueuePendingReference(obj, &phantom_reference_list_);
1351 } else {
1352 LOG(FATAL) << "Invalid reference type " << PrettyClass(klass)
1353 << " " << std::hex << klass->GetAccessFlags();
1354 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001355 }
1356}
1357
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001358void MarkSweep::ScanRoot(const Object* obj) {
1359 ScanObject(obj);
1360}
1361
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001362class MarkObjectVisitor {
1363 public:
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001364 explicit MarkObjectVisitor(MarkSweep* const mark_sweep) ALWAYS_INLINE : mark_sweep_(mark_sweep) {}
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001365
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001366 // TODO: Fixme when anotatalysis works with visitors.
Brian Carlstromdf629502013-07-17 22:39:56 -07001367 void operator()(const Object* /* obj */, const Object* ref, const MemberOffset& /* offset */,
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001368 bool /* is_static */) const ALWAYS_INLINE
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001369 NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001370 if (kCheckLocks) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001371 Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
1372 Locks::heap_bitmap_lock_->AssertExclusiveHeld(Thread::Current());
1373 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001374 mark_sweep_->MarkObject(ref);
1375 }
1376
1377 private:
1378 MarkSweep* const mark_sweep_;
1379};
1380
Carl Shapiro69759ea2011-07-21 18:13:35 -07001381// Scans an object reference. Determines the type of the reference
1382// and dispatches to a specialized scanning routine.
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001383void MarkSweep::ScanObject(const Object* obj) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001384 MarkObjectVisitor visitor(this);
1385 ScanObjectVisit(obj, visitor);
1386}
1387
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001388void MarkSweep::ProcessMarkStackParallel(size_t thread_count) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001389 Thread* self = Thread::Current();
1390 ThreadPool* thread_pool = GetHeap()->GetThreadPool();
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001391 const size_t chunk_size = std::min(mark_stack_->Size() / thread_count + 1,
1392 static_cast<size_t>(MarkStackTask<false>::kMaxSize));
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001393 CHECK_GT(chunk_size, 0U);
1394 // Split the current mark stack up into work tasks.
1395 for (mirror::Object **it = mark_stack_->Begin(), **end = mark_stack_->End(); it < end; ) {
1396 const size_t delta = std::min(static_cast<size_t>(end - it), chunk_size);
1397 thread_pool->AddTask(self, new MarkStackTask<false>(thread_pool, this, delta,
1398 const_cast<const mirror::Object**>(it)));
1399 it += delta;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001400 }
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001401 thread_pool->SetMaxActiveWorkers(thread_count - 1);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001402 thread_pool->StartWorkers(self);
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001403 thread_pool->Wait(self, true, true);
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001404 thread_pool->StopWorkers(self);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001405 mark_stack_->Reset();
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001406 CHECK_EQ(work_chunks_created_, work_chunks_deleted_) << " some of the work chunks were leaked";
Carl Shapiro69759ea2011-07-21 18:13:35 -07001407}
1408
Ian Rogers5d76c432011-10-31 21:42:49 -07001409// Scan anything that's on the mark stack.
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001410void MarkSweep::ProcessMarkStack(bool paused) {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001411 timings_.StartSplit("ProcessMarkStack");
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001412 size_t thread_count = GetThreadCount(paused);
1413 if (kParallelProcessMarkStack && thread_count > 1 &&
1414 mark_stack_->Size() >= kMinimumParallelMarkStackSize) {
1415 ProcessMarkStackParallel(thread_count);
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001416 } else {
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001417 // TODO: Tune this.
1418 static const size_t kFifoSize = 4;
1419 BoundedFifoPowerOfTwo<const Object*, kFifoSize> prefetch_fifo;
1420 for (;;) {
1421 const Object* obj = NULL;
1422 if (kUseMarkStackPrefetch) {
1423 while (!mark_stack_->IsEmpty() && prefetch_fifo.size() < kFifoSize) {
1424 const Object* obj = mark_stack_->PopBack();
1425 DCHECK(obj != NULL);
1426 __builtin_prefetch(obj);
1427 prefetch_fifo.push_back(obj);
1428 }
1429 if (prefetch_fifo.empty()) {
1430 break;
1431 }
1432 obj = prefetch_fifo.front();
1433 prefetch_fifo.pop_front();
1434 } else {
1435 if (mark_stack_->IsEmpty()) {
1436 break;
1437 }
1438 obj = mark_stack_->PopBack();
1439 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001440 DCHECK(obj != NULL);
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001441 ScanObject(obj);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001442 }
1443 }
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001444 timings_.EndSplit();
Carl Shapiro69759ea2011-07-21 18:13:35 -07001445}
1446
Carl Shapiro69759ea2011-07-21 18:13:35 -07001447// Walks the reference list marking any references subject to the
1448// reference clearing policy. References with a black referent are
1449// removed from the list. References with white referents biased
1450// toward saving are blackened and also removed from the list.
1451void MarkSweep::PreserveSomeSoftReferences(Object** list) {
1452 DCHECK(list != NULL);
1453 Object* clear = NULL;
1454 size_t counter = 0;
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001455
1456 DCHECK(mark_stack_->IsEmpty());
1457
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001458 timings_.StartSplit("PreserveSomeSoftReferences");
Carl Shapiro69759ea2011-07-21 18:13:35 -07001459 while (*list != NULL) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001460 Object* ref = heap_->DequeuePendingReference(list);
1461 Object* referent = heap_->GetReferenceReferent(ref);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001462 if (referent == NULL) {
1463 // Referent was cleared by the user during marking.
1464 continue;
1465 }
1466 bool is_marked = IsMarked(referent);
1467 if (!is_marked && ((++counter) & 1)) {
1468 // Referent is white and biased toward saving, mark it.
1469 MarkObject(referent);
1470 is_marked = true;
1471 }
1472 if (!is_marked) {
1473 // Referent is white, queue it for clearing.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001474 heap_->EnqueuePendingReference(ref, &clear);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001475 }
1476 }
1477 *list = clear;
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001478 timings_.EndSplit();
1479
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001480 // Restart the mark with the newly black references added to the root set.
1481 ProcessMarkStack(true);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001482}
1483
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001484inline bool MarkSweep::IsMarked(const Object* object) const
1485 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
Mathieu Chartier9642c962013-08-05 17:40:36 -07001486 if (IsImmune(object)) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001487 return true;
1488 }
1489 DCHECK(current_mark_bitmap_ != NULL);
1490 if (current_mark_bitmap_->HasAddress(object)) {
1491 return current_mark_bitmap_->Test(object);
1492 }
1493 return heap_->GetMarkBitmap()->Test(object);
1494}
1495
1496
Carl Shapiro69759ea2011-07-21 18:13:35 -07001497// Unlink the reference list clearing references objects with white
1498// referents. Cleared references registered to a reference queue are
1499// scheduled for appending by the heap worker thread.
1500void MarkSweep::ClearWhiteReferences(Object** list) {
1501 DCHECK(list != NULL);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001502 while (*list != NULL) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001503 Object* ref = heap_->DequeuePendingReference(list);
1504 Object* referent = heap_->GetReferenceReferent(ref);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001505 if (referent != NULL && !IsMarked(referent)) {
1506 // Referent is white, clear it.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001507 heap_->ClearReferenceReferent(ref);
1508 if (heap_->IsEnqueuable(ref)) {
1509 heap_->EnqueueReference(ref, &cleared_reference_list_);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001510 }
1511 }
1512 }
1513 DCHECK(*list == NULL);
1514}
1515
1516// Enqueues finalizer references with white referents. White
1517// referents are blackened, moved to the zombie field, and the
1518// referent field is cleared.
1519void MarkSweep::EnqueueFinalizerReferences(Object** list) {
1520 DCHECK(list != NULL);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001521 timings_.StartSplit("EnqueueFinalizerReferences");
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001522 MemberOffset zombie_offset = heap_->GetFinalizerReferenceZombieOffset();
Carl Shapiro69759ea2011-07-21 18:13:35 -07001523 bool has_enqueued = false;
1524 while (*list != NULL) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001525 Object* ref = heap_->DequeuePendingReference(list);
1526 Object* referent = heap_->GetReferenceReferent(ref);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001527 if (referent != NULL && !IsMarked(referent)) {
1528 MarkObject(referent);
1529 // If the referent is non-null the reference must queuable.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001530 DCHECK(heap_->IsEnqueuable(ref));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001531 ref->SetFieldObject(zombie_offset, referent, false);
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001532 heap_->ClearReferenceReferent(ref);
1533 heap_->EnqueueReference(ref, &cleared_reference_list_);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001534 has_enqueued = true;
1535 }
1536 }
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001537 timings_.EndSplit();
Carl Shapiro69759ea2011-07-21 18:13:35 -07001538 if (has_enqueued) {
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001539 ProcessMarkStack(true);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001540 }
1541 DCHECK(*list == NULL);
1542}
1543
Carl Shapiro58551df2011-07-24 03:09:51 -07001544// Process reference class instances and schedule finalizations.
Carl Shapiro69759ea2011-07-21 18:13:35 -07001545void MarkSweep::ProcessReferences(Object** soft_references, bool clear_soft,
1546 Object** weak_references,
1547 Object** finalizer_references,
1548 Object** phantom_references) {
1549 DCHECK(soft_references != NULL);
1550 DCHECK(weak_references != NULL);
1551 DCHECK(finalizer_references != NULL);
1552 DCHECK(phantom_references != NULL);
1553
1554 // Unless we are in the zygote or required to clear soft references
1555 // with white references, preserve some white referents.
Ian Rogers2945e242012-06-03 14:45:16 -07001556 if (!clear_soft && !Runtime::Current()->IsZygote()) {
Carl Shapiro69759ea2011-07-21 18:13:35 -07001557 PreserveSomeSoftReferences(soft_references);
1558 }
1559
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001560 timings_.StartSplit("ProcessReferences");
Carl Shapiro69759ea2011-07-21 18:13:35 -07001561 // Clear all remaining soft and weak references with white
1562 // referents.
1563 ClearWhiteReferences(soft_references);
1564 ClearWhiteReferences(weak_references);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001565 timings_.EndSplit();
Carl Shapiro69759ea2011-07-21 18:13:35 -07001566
1567 // Preserve all white objects with finalize methods and schedule
1568 // them for finalization.
1569 EnqueueFinalizerReferences(finalizer_references);
1570
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001571 timings_.StartSplit("ProcessReferences");
Carl Shapiro69759ea2011-07-21 18:13:35 -07001572 // Clear all f-reachable soft and weak references with white
1573 // referents.
1574 ClearWhiteReferences(soft_references);
1575 ClearWhiteReferences(weak_references);
1576
1577 // Clear all phantom references with white referents.
1578 ClearWhiteReferences(phantom_references);
1579
1580 // At this point all reference lists should be empty.
1581 DCHECK(*soft_references == NULL);
1582 DCHECK(*weak_references == NULL);
1583 DCHECK(*finalizer_references == NULL);
1584 DCHECK(*phantom_references == NULL);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001585 timings_.EndSplit();
Carl Shapiro69759ea2011-07-21 18:13:35 -07001586}
1587
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001588void MarkSweep::UnBindBitmaps() {
Anwar Ghuloum46543222013-08-12 09:28:42 -07001589 base::TimingLogger::ScopedSplit split("UnBindBitmaps", &timings_);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001590 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001591 if (space->IsDlMallocSpace()) {
1592 space::DlMallocSpace* alloc_space = space->AsDlMallocSpace();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001593 if (alloc_space->temp_bitmap_.get() != NULL) {
1594 // At this point, the temp_bitmap holds our old mark bitmap.
Ian Rogers1d54e732013-05-02 21:10:01 -07001595 accounting::SpaceBitmap* new_bitmap = alloc_space->temp_bitmap_.release();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001596 GetHeap()->GetMarkBitmap()->ReplaceBitmap(alloc_space->mark_bitmap_.get(), new_bitmap);
1597 CHECK_EQ(alloc_space->mark_bitmap_.release(), alloc_space->live_bitmap_.get());
1598 alloc_space->mark_bitmap_.reset(new_bitmap);
1599 DCHECK(alloc_space->temp_bitmap_.get() == NULL);
1600 }
1601 }
1602 }
1603}
1604
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001605void MarkSweep::FinishPhase() {
Anwar Ghuloum46543222013-08-12 09:28:42 -07001606 base::TimingLogger::ScopedSplit split("FinishPhase", &timings_);
1607 // Can't enqueue references if we hold the mutator lock.
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001608 Object* cleared_references = GetClearedReferences();
Ian Rogers1d54e732013-05-02 21:10:01 -07001609 Heap* heap = GetHeap();
Anwar Ghuloum46543222013-08-12 09:28:42 -07001610 timings_.NewSplit("EnqueueClearedReferences");
Ian Rogers1d54e732013-05-02 21:10:01 -07001611 heap->EnqueueClearedReferences(&cleared_references);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001612
Anwar Ghuloum46543222013-08-12 09:28:42 -07001613 timings_.NewSplit("PostGcVerification");
Ian Rogers1d54e732013-05-02 21:10:01 -07001614 heap->PostGcVerification(this);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001615
Anwar Ghuloum46543222013-08-12 09:28:42 -07001616 timings_.NewSplit("GrowForUtilization");
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001617 heap->GrowForUtilization(GetGcType(), GetDurationNs());
Mathieu Chartier65db8802012-11-20 12:36:46 -08001618
Anwar Ghuloum46543222013-08-12 09:28:42 -07001619 timings_.NewSplit("RequestHeapTrim");
Ian Rogers1d54e732013-05-02 21:10:01 -07001620 heap->RequestHeapTrim();
Mathieu Chartier65db8802012-11-20 12:36:46 -08001621
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001622 // Update the cumulative statistics
Ian Rogers1d54e732013-05-02 21:10:01 -07001623 total_time_ns_ += GetDurationNs();
1624 total_paused_time_ns_ += std::accumulate(GetPauseTimes().begin(), GetPauseTimes().end(), 0,
1625 std::plus<uint64_t>());
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001626 total_freed_objects_ += GetFreedObjects() + GetFreedLargeObjects();
1627 total_freed_bytes_ += GetFreedBytes() + GetFreedLargeObjectBytes();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001628
1629 // Ensure that the mark stack is empty.
1630 CHECK(mark_stack_->IsEmpty());
1631
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001632 if (kCountScannedTypes) {
1633 VLOG(gc) << "MarkSweep scanned classes=" << class_count_ << " arrays=" << array_count_
1634 << " other=" << other_count_;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001635 }
1636
1637 if (kCountTasks) {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001638 VLOG(gc) << "Total number of work chunks allocated: " << work_chunks_created_;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001639 }
1640
1641 if (kMeasureOverhead) {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001642 VLOG(gc) << "Overhead time " << PrettyDuration(overhead_time_);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001643 }
1644
1645 if (kProfileLargeObjects) {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001646 VLOG(gc) << "Large objects tested " << large_object_test_ << " marked " << large_object_mark_;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001647 }
1648
1649 if (kCountClassesMarked) {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001650 VLOG(gc) << "Classes marked " << classes_marked_;
1651 }
1652
1653 if (kCountJavaLangRefs) {
1654 VLOG(gc) << "References scanned " << reference_count_;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001655 }
1656
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001657 // Update the cumulative loggers.
1658 cumulative_timings_.Start();
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001659 cumulative_timings_.AddLogger(timings_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001660 cumulative_timings_.End();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001661
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001662 // Clear all of the spaces' mark bitmaps.
Mathieu Chartier02e25112013-08-14 16:14:24 -07001663 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001664 if (space->GetGcRetentionPolicy() != space::kGcRetentionPolicyNeverCollect) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001665 space->GetMarkBitmap()->Clear();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001666 }
1667 }
Mathieu Chartier5301cd22012-05-31 12:11:36 -07001668 mark_stack_->Reset();
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001669
1670 // Reset the marked large objects.
Ian Rogers1d54e732013-05-02 21:10:01 -07001671 space::LargeObjectSpace* large_objects = GetHeap()->GetLargeObjectsSpace();
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001672 large_objects->GetMarkObjects()->Clear();
Carl Shapiro69759ea2011-07-21 18:13:35 -07001673}
1674
Ian Rogers1d54e732013-05-02 21:10:01 -07001675} // namespace collector
1676} // namespace gc
Carl Shapiro69759ea2011-07-21 18:13:35 -07001677} // namespace art