blob: a5e66d20df015453d6b1480f3c87b15398ab6c02 [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Carl Shapiro69759ea2011-07-21 18:13:35 -070016
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070017#include "mark_sweep.h"
Carl Shapiro69759ea2011-07-21 18:13:35 -070018
Mathieu Chartier2b82db42012-11-14 17:29:05 -080019#include <functional>
20#include <numeric>
Carl Shapiro58551df2011-07-24 03:09:51 -070021#include <climits>
22#include <vector>
23
Mathieu Chartier94c32c52013-08-09 11:14:04 -070024#include "base/bounded_fifo.h"
Elliott Hughes07ed66b2012-12-12 18:34:25 -080025#include "base/logging.h"
Elliott Hughes76160052012-12-12 16:31:20 -080026#include "base/macros.h"
Ian Rogers693ff612013-02-01 10:56:12 -080027#include "base/mutex-inl.h"
Sameer Abu Asala8439542013-02-14 16:06:42 -080028#include "base/timing_logger.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070029#include "gc/accounting/card_table-inl.h"
30#include "gc/accounting/heap_bitmap.h"
Mathieu Chartier11409ae2013-09-23 11:49:36 -070031#include "gc/accounting/mod_union_table.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070032#include "gc/accounting/space_bitmap-inl.h"
33#include "gc/heap.h"
34#include "gc/space/image_space.h"
35#include "gc/space/large_object_space.h"
36#include "gc/space/space-inl.h"
Elliott Hughes410c0c82011-09-01 17:58:25 -070037#include "indirect_reference_table.h"
38#include "intern_table.h"
Ian Rogers81d425b2012-09-27 16:03:43 -070039#include "jni_internal.h"
Elliott Hughesc33a32b2011-10-11 18:18:07 -070040#include "monitor.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080041#include "mark_sweep-inl.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070042#include "mirror/art_field.h"
43#include "mirror/art_field-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080044#include "mirror/class-inl.h"
45#include "mirror/class_loader.h"
46#include "mirror/dex_cache.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080047#include "mirror/object-inl.h"
48#include "mirror/object_array.h"
49#include "mirror/object_array-inl.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070050#include "runtime.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070051#include "thread-inl.h"
Mathieu Chartier6f1c9492012-10-15 12:08:41 -070052#include "thread_list.h"
Ian Rogers08254272012-10-23 17:49:23 -070053#include "verifier/method_verifier.h"
Carl Shapiro69759ea2011-07-21 18:13:35 -070054
Brian Carlstromea46f952013-07-30 01:26:50 -070055using ::art::mirror::ArtField;
Brian Carlstrom3e3d5912013-07-18 00:19:45 -070056using ::art::mirror::Class;
Brian Carlstrom3e3d5912013-07-18 00:19:45 -070057using ::art::mirror::Object;
58using ::art::mirror::ObjectArray;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080059
Carl Shapiro69759ea2011-07-21 18:13:35 -070060namespace art {
Ian Rogers1d54e732013-05-02 21:10:01 -070061namespace gc {
62namespace collector {
Carl Shapiro69759ea2011-07-21 18:13:35 -070063
Mathieu Chartier02b6a782012-10-26 13:51:26 -070064// Performance options.
Mathieu Chartier94c32c52013-08-09 11:14:04 -070065constexpr bool kUseRecursiveMark = false;
66constexpr bool kUseMarkStackPrefetch = true;
67constexpr size_t kSweepArrayChunkFreeSize = 1024;
68
69// Parallelism options.
70constexpr bool kParallelCardScan = true;
71constexpr bool kParallelRecursiveMark = true;
72// Don't attempt to parallelize mark stack processing unless the mark stack is at least n
73// elements. This is temporary until we reduce the overhead caused by allocating tasks, etc.. Not
74// having this can add overhead in ProcessReferences since we may end up doing many calls of
75// ProcessMarkStack with very small mark stacks.
76constexpr size_t kMinimumParallelMarkStackSize = 128;
77constexpr bool kParallelProcessMarkStack = true;
Mathieu Chartier858f1c52012-10-17 17:45:55 -070078
Mathieu Chartier02b6a782012-10-26 13:51:26 -070079// Profiling and information flags.
Mathieu Chartier94c32c52013-08-09 11:14:04 -070080constexpr bool kCountClassesMarked = false;
81constexpr bool kProfileLargeObjects = false;
82constexpr bool kMeasureOverhead = false;
83constexpr bool kCountTasks = false;
84constexpr bool kCountJavaLangRefs = false;
85
86// Turn off kCheckLocks when profiling the GC since it slows the GC down by up to 40%.
87constexpr bool kCheckLocks = kDebugLocking;
Mathieu Chartier02b6a782012-10-26 13:51:26 -070088
Ian Rogers1d54e732013-05-02 21:10:01 -070089void MarkSweep::ImmuneSpace(space::ContinuousSpace* space) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -080090 // Bind live to mark bitmap if necessary.
91 if (space->GetLiveBitmap() != space->GetMarkBitmap()) {
92 BindLiveToMarkBitmap(space);
93 }
94
95 // Add the space to the immune region.
96 if (immune_begin_ == NULL) {
97 DCHECK(immune_end_ == NULL);
98 SetImmuneRange(reinterpret_cast<Object*>(space->Begin()),
99 reinterpret_cast<Object*>(space->End()));
100 } else {
Mathieu Chartier02e25112013-08-14 16:14:24 -0700101 const space::ContinuousSpace* prev_space = nullptr;
Ian Rogers1d54e732013-05-02 21:10:01 -0700102 // Find out if the previous space is immune.
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700103 for (const space::ContinuousSpace* cur_space : GetHeap()->GetContinuousSpaces()) {
Mathieu Chartier02e25112013-08-14 16:14:24 -0700104 if (cur_space == space) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700105 break;
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800106 }
Mathieu Chartier02e25112013-08-14 16:14:24 -0700107 prev_space = cur_space;
Ian Rogers1d54e732013-05-02 21:10:01 -0700108 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700109 // If previous space was immune, then extend the immune region. Relies on continuous spaces
110 // being sorted by Heap::AddContinuousSpace.
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700111 if (prev_space != NULL && IsImmuneSpace(prev_space)) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800112 immune_begin_ = std::min(reinterpret_cast<Object*>(space->Begin()), immune_begin_);
113 immune_end_ = std::max(reinterpret_cast<Object*>(space->End()), immune_end_);
114 }
115 }
116}
117
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700118bool MarkSweep::IsImmuneSpace(const space::ContinuousSpace* space) {
119 return
120 immune_begin_ <= reinterpret_cast<Object*>(space->Begin()) &&
121 immune_end_ >= reinterpret_cast<Object*>(space->End());
122}
123
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800124void MarkSweep::BindBitmaps() {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700125 timings_.StartSplit("BindBitmaps");
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800126 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800127 // Mark all of the spaces we never collect as immune.
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700128 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700129 if (space->GetGcRetentionPolicy() == space::kGcRetentionPolicyNeverCollect) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800130 ImmuneSpace(space);
131 }
132 }
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700133 timings_.EndSplit();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800134}
135
Ian Rogers1d54e732013-05-02 21:10:01 -0700136MarkSweep::MarkSweep(Heap* heap, bool is_concurrent, const std::string& name_prefix)
137 : GarbageCollector(heap,
138 name_prefix + (name_prefix.empty() ? "" : " ") +
139 (is_concurrent ? "concurrent mark sweep": "mark sweep")),
140 current_mark_bitmap_(NULL),
141 java_lang_Class_(NULL),
142 mark_stack_(NULL),
Ian Rogers1d54e732013-05-02 21:10:01 -0700143 immune_begin_(NULL),
144 immune_end_(NULL),
145 soft_reference_list_(NULL),
146 weak_reference_list_(NULL),
147 finalizer_reference_list_(NULL),
148 phantom_reference_list_(NULL),
149 cleared_reference_list_(NULL),
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800150 gc_barrier_(new Barrier(0)),
Ian Rogers62d6c772013-02-27 08:32:07 -0800151 large_object_lock_("mark sweep large object lock", kMarkSweepLargeObjectLock),
Mathieu Chartier958291c2013-08-27 18:14:55 -0700152 mark_stack_lock_("mark sweep mark stack lock", kMarkSweepMarkStackLock),
Ian Rogers1bd4b4c2013-04-18 17:47:42 -0700153 is_concurrent_(is_concurrent),
Ian Rogers1d54e732013-05-02 21:10:01 -0700154 clear_soft_references_(false) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800155}
156
157void MarkSweep::InitializePhase() {
Ian Rogers1d54e732013-05-02 21:10:01 -0700158 timings_.Reset();
Anwar Ghuloum46543222013-08-12 09:28:42 -0700159 base::TimingLogger::ScopedSplit split("InitializePhase", &timings_);
Mathieu Chartiere53225c2013-08-19 10:59:11 -0700160 mark_stack_ = heap_->mark_stack_.get();
161 DCHECK(mark_stack_ != nullptr);
162 SetImmuneRange(nullptr, nullptr);
163 soft_reference_list_ = nullptr;
164 weak_reference_list_ = nullptr;
165 finalizer_reference_list_ = nullptr;
166 phantom_reference_list_ = nullptr;
167 cleared_reference_list_ = nullptr;
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800168 freed_bytes_ = 0;
Mathieu Chartiere53225c2013-08-19 10:59:11 -0700169 freed_large_object_bytes_ = 0;
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800170 freed_objects_ = 0;
Mathieu Chartiere53225c2013-08-19 10:59:11 -0700171 freed_large_objects_ = 0;
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800172 class_count_ = 0;
173 array_count_ = 0;
174 other_count_ = 0;
175 large_object_test_ = 0;
176 large_object_mark_ = 0;
177 classes_marked_ = 0;
178 overhead_time_ = 0;
179 work_chunks_created_ = 0;
180 work_chunks_deleted_ = 0;
181 reference_count_ = 0;
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700182 java_lang_Class_ = Class::GetJavaLangClass();
Mathieu Chartiere53225c2013-08-19 10:59:11 -0700183 CHECK(java_lang_Class_ != nullptr);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700184
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700185 FindDefaultMarkBitmap();
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700186
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700187 // Do any pre GC verification.
Anwar Ghuloum46543222013-08-12 09:28:42 -0700188 timings_.NewSplit("PreGcVerification");
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800189 heap_->PreGcVerification(this);
190}
191
192void MarkSweep::ProcessReferences(Thread* self) {
Mathieu Chartier9e452d12013-09-18 16:35:15 -0700193 base::TimingLogger::ScopedSplit split("ProcessReferences", &timings_);
Mathieu Chartier8e56c7e2012-11-20 13:25:50 -0800194 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800195 ProcessReferences(&soft_reference_list_, clear_soft_references_, &weak_reference_list_,
196 &finalizer_reference_list_, &phantom_reference_list_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800197}
198
199bool MarkSweep::HandleDirtyObjectsPhase() {
Anwar Ghuloum46543222013-08-12 09:28:42 -0700200 base::TimingLogger::ScopedSplit split("HandleDirtyObjectsPhase", &timings_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800201 Thread* self = Thread::Current();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800202 Locks::mutator_lock_->AssertExclusiveHeld(self);
203
204 {
205 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
206
207 // Re-mark root set.
208 ReMarkRoots();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800209
210 // Scan dirty objects, this is only required if we are not doing concurrent GC.
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700211 RecursiveMarkDirtyObjects(true, accounting::CardTable::kCardDirty);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800212 }
213
214 ProcessReferences(self);
215
216 // Only need to do this if we have the card mark verification on, and only during concurrent GC.
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700217 if (GetHeap()->verify_missing_card_marks_ || GetHeap()->verify_pre_gc_heap_||
218 GetHeap()->verify_post_gc_heap_) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800219 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
220 // This second sweep makes sure that we don't have any objects in the live stack which point to
221 // freed objects. These cause problems since their references may be previously freed objects.
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700222 SweepArray(GetHeap()->allocation_stack_.get(), false);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800223 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700224
225 timings_.StartSplit("PreSweepingGcVerification");
226 heap_->PreSweepingGcVerification(this);
227 timings_.EndSplit();
228
229 // Ensure that nobody inserted items in the live stack after we swapped the stacks.
230 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
231 CHECK_GE(live_stack_freeze_size_, GetHeap()->GetLiveStack()->Size());
Mathieu Chartierc11d9b82013-09-19 10:01:59 -0700232
233 // Disallow new system weaks to prevent a race which occurs when someone adds a new system
234 // weak before we sweep them. Since this new system weak may not be marked, the GC may
235 // incorrectly sweep it. This also fixes a race where interning may attempt to return a strong
236 // reference to a string that is about to be swept.
237 Runtime::Current()->DisallowNewSystemWeaks();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800238 return true;
239}
240
241bool MarkSweep::IsConcurrent() const {
242 return is_concurrent_;
243}
244
245void MarkSweep::MarkingPhase() {
Anwar Ghuloum46543222013-08-12 09:28:42 -0700246 base::TimingLogger::ScopedSplit split("MarkingPhase", &timings_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800247 Thread* self = Thread::Current();
248
249 BindBitmaps();
250 FindDefaultMarkBitmap();
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700251
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800252 // Process dirty cards and add dirty cards to mod union tables.
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700253 heap_->ProcessCards(timings_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800254
255 // Need to do this before the checkpoint since we don't want any threads to add references to
256 // the live stack during the recursive mark.
Anwar Ghuloum46543222013-08-12 09:28:42 -0700257 timings_.NewSplit("SwapStacks");
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700258 heap_->SwapStacks();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800259
260 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
261 if (Locks::mutator_lock_->IsExclusiveHeld(self)) {
262 // If we exclusively hold the mutator lock, all threads must be suspended.
263 MarkRoots();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800264 } else {
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700265 MarkThreadRoots(self);
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700266 // At this point the live stack should no longer have any mutators which push into it.
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800267 MarkNonThreadRoots();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800268 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700269 live_stack_freeze_size_ = heap_->GetLiveStack()->Size();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800270 MarkConcurrentRoots();
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700271 UpdateAndMarkModUnion();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800272 MarkReachableObjects();
273}
274
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700275void MarkSweep::UpdateAndMarkModUnion() {
276 for (const auto& space : heap_->GetContinuousSpaces()) {
277 if (IsImmuneSpace(space)) {
278 const char* name = space->IsZygoteSpace() ? "UpdateAndMarkZygoteModUnionTable" :
279 "UpdateAndMarkImageModUnionTable";
280 base::TimingLogger::ScopedSplit split(name, &timings_);
281 accounting::ModUnionTable* mod_union_table = heap_->FindModUnionTableFromSpace(space);
282 CHECK(mod_union_table != nullptr);
283 mod_union_table->UpdateAndMarkReferences(MarkRootCallback, this);
284 }
285 }
286}
287
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700288void MarkSweep::MarkThreadRoots(Thread* self) {
289 MarkRootsCheckpoint(self);
290}
291
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800292void MarkSweep::MarkReachableObjects() {
293 // Mark everything allocated since the last as GC live so that we can sweep concurrently,
294 // knowing that new allocations won't be marked as live.
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700295 timings_.StartSplit("MarkStackAsLive");
Ian Rogers1d54e732013-05-02 21:10:01 -0700296 accounting::ObjectStack* live_stack = heap_->GetLiveStack();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800297 heap_->MarkAllocStack(heap_->alloc_space_->GetLiveBitmap(),
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700298 heap_->large_object_space_->GetLiveObjects(), live_stack);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800299 live_stack->Reset();
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700300 timings_.EndSplit();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800301 // Recursively mark all the non-image bits set in the mark bitmap.
302 RecursiveMark();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800303}
304
305void MarkSweep::ReclaimPhase() {
Anwar Ghuloum46543222013-08-12 09:28:42 -0700306 base::TimingLogger::ScopedSplit split("ReclaimPhase", &timings_);
Mathieu Chartier720ef762013-08-17 14:46:54 -0700307 Thread* self = Thread::Current();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800308
309 if (!IsConcurrent()) {
310 ProcessReferences(self);
Mathieu Chartierc11d9b82013-09-19 10:01:59 -0700311 }
312
313 {
314 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
315 SweepSystemWeaks();
316 }
317
318 if (IsConcurrent()) {
319 Runtime::Current()->AllowNewSystemWeaks();
320
Anwar Ghulouma9a50922013-08-09 21:34:20 -0700321 base::TimingLogger::ScopedSplit split("UnMarkAllocStack", &timings_);
Mathieu Chartier9642c962013-08-05 17:40:36 -0700322 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700323 accounting::ObjectStack* allocation_stack = GetHeap()->allocation_stack_.get();
Mathieu Chartier9642c962013-08-05 17:40:36 -0700324 // The allocation stack contains things allocated since the start of the GC. These may have been
325 // marked during this GC meaning they won't be eligible for reclaiming in the next sticky GC.
326 // Remove these objects from the mark bitmaps so that they will be eligible for sticky
327 // collection.
328 // There is a race here which is safely handled. Another thread such as the hprof could
329 // have flushed the alloc stack after we resumed the threads. This is safe however, since
330 // reseting the allocation stack zeros it out with madvise. This means that we will either
331 // read NULLs or attempt to unmark a newly allocated object which will not be marked in the
332 // first place.
333 mirror::Object** end = allocation_stack->End();
334 for (mirror::Object** it = allocation_stack->Begin(); it != end; ++it) {
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700335 const Object* obj = *it;
Mathieu Chartier9642c962013-08-05 17:40:36 -0700336 if (obj != NULL) {
337 UnMarkObjectNonNull(obj);
338 }
339 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800340 }
341
342 // Before freeing anything, lets verify the heap.
343 if (kIsDebugBuild) {
344 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
345 VerifyImageRoots();
346 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800347
348 {
349 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
350
351 // Reclaim unmarked objects.
Ian Rogers1d54e732013-05-02 21:10:01 -0700352 Sweep(false);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800353
354 // Swap the live and mark bitmaps for each space which we modified space. This is an
355 // optimization that enables us to not clear live bits inside of the sweep. Only swaps unbound
356 // bitmaps.
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700357 timings_.StartSplit("SwapBitmaps");
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800358 SwapBitmaps();
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700359 timings_.EndSplit();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800360
361 // Unbind the live and mark bitmaps.
362 UnBindBitmaps();
363 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800364}
365
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800366void MarkSweep::SetImmuneRange(Object* begin, Object* end) {
367 immune_begin_ = begin;
368 immune_end_ = end;
Carl Shapiro58551df2011-07-24 03:09:51 -0700369}
370
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700371void MarkSweep::FindDefaultMarkBitmap() {
Anwar Ghuloum46543222013-08-12 09:28:42 -0700372 base::TimingLogger::ScopedSplit split("FindDefaultMarkBitmap", &timings_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700373 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700374 if (space->GetGcRetentionPolicy() == space::kGcRetentionPolicyAlwaysCollect) {
Mathieu Chartier02e25112013-08-14 16:14:24 -0700375 current_mark_bitmap_ = space->GetMarkBitmap();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700376 CHECK(current_mark_bitmap_ != NULL);
377 return;
378 }
379 }
380 GetHeap()->DumpSpaces();
381 LOG(FATAL) << "Could not find a default mark bitmap";
382}
383
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800384void MarkSweep::ExpandMarkStack() {
Mathieu Chartierba311b42013-08-27 13:02:30 -0700385 ResizeMarkStack(mark_stack_->Capacity() * 2);
386}
387
388void MarkSweep::ResizeMarkStack(size_t new_size) {
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800389 // Rare case, no need to have Thread::Current be a parameter.
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800390 if (UNLIKELY(mark_stack_->Size() < mark_stack_->Capacity())) {
391 // Someone else acquired the lock and expanded the mark stack before us.
392 return;
393 }
Mathieu Chartier02e25112013-08-14 16:14:24 -0700394 std::vector<Object*> temp(mark_stack_->Begin(), mark_stack_->End());
Mathieu Chartierba311b42013-08-27 13:02:30 -0700395 CHECK_LE(mark_stack_->Size(), new_size);
396 mark_stack_->Resize(new_size);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700397 for (const auto& obj : temp) {
398 mark_stack_->PushBack(obj);
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800399 }
400}
401
Mathieu Chartier9642c962013-08-05 17:40:36 -0700402inline void MarkSweep::MarkObjectNonNullParallel(const Object* obj) {
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800403 DCHECK(obj != NULL);
404 if (MarkObjectParallel(obj)) {
Mathieu Chartierba311b42013-08-27 13:02:30 -0700405 MutexLock mu(Thread::Current(), mark_stack_lock_);
406 if (UNLIKELY(mark_stack_->Size() >= mark_stack_->Capacity())) {
Mathieu Chartier184e3222013-08-03 14:02:57 -0700407 ExpandMarkStack();
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800408 }
Mathieu Chartierba311b42013-08-27 13:02:30 -0700409 // The object must be pushed on to the mark stack.
410 mark_stack_->PushBack(const_cast<Object*>(obj));
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800411 }
412}
413
Mathieu Chartier9642c962013-08-05 17:40:36 -0700414inline void MarkSweep::UnMarkObjectNonNull(const Object* obj) {
415 DCHECK(!IsImmune(obj));
416 // Try to take advantage of locality of references within a space, failing this find the space
417 // the hard way.
418 accounting::SpaceBitmap* object_bitmap = current_mark_bitmap_;
419 if (UNLIKELY(!object_bitmap->HasAddress(obj))) {
420 accounting::SpaceBitmap* new_bitmap = heap_->GetMarkBitmap()->GetContinuousSpaceBitmap(obj);
421 if (LIKELY(new_bitmap != NULL)) {
422 object_bitmap = new_bitmap;
423 } else {
424 MarkLargeObject(obj, false);
425 return;
426 }
427 }
428
429 DCHECK(object_bitmap->HasAddress(obj));
430 object_bitmap->Clear(obj);
431}
432
433inline void MarkSweep::MarkObjectNonNull(const Object* obj) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700434 DCHECK(obj != NULL);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700435
Mathieu Chartier9642c962013-08-05 17:40:36 -0700436 if (IsImmune(obj)) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700437 DCHECK(IsMarked(obj));
Carl Shapiro69759ea2011-07-21 18:13:35 -0700438 return;
439 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700440
441 // Try to take advantage of locality of references within a space, failing this find the space
442 // the hard way.
Ian Rogers1d54e732013-05-02 21:10:01 -0700443 accounting::SpaceBitmap* object_bitmap = current_mark_bitmap_;
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700444 if (UNLIKELY(!object_bitmap->HasAddress(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700445 accounting::SpaceBitmap* new_bitmap = heap_->GetMarkBitmap()->GetContinuousSpaceBitmap(obj);
446 if (LIKELY(new_bitmap != NULL)) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700447 object_bitmap = new_bitmap;
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700448 } else {
Mathieu Chartier9642c962013-08-05 17:40:36 -0700449 MarkLargeObject(obj, true);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700450 return;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700451 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700452 }
453
Carl Shapiro69759ea2011-07-21 18:13:35 -0700454 // This object was not previously marked.
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700455 if (!object_bitmap->Test(obj)) {
456 object_bitmap->Set(obj);
Mathieu Chartier184e3222013-08-03 14:02:57 -0700457 if (UNLIKELY(mark_stack_->Size() >= mark_stack_->Capacity())) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700458 // Lock is not needed but is here anyways to please annotalysis.
459 MutexLock mu(Thread::Current(), mark_stack_lock_);
Mathieu Chartier184e3222013-08-03 14:02:57 -0700460 ExpandMarkStack();
Carl Shapiro69759ea2011-07-21 18:13:35 -0700461 }
Mathieu Chartier184e3222013-08-03 14:02:57 -0700462 // The object must be pushed on to the mark stack.
463 mark_stack_->PushBack(const_cast<Object*>(obj));
Carl Shapiro69759ea2011-07-21 18:13:35 -0700464 }
465}
466
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700467// Rare case, probably not worth inlining since it will increase instruction cache miss rate.
Mathieu Chartier9642c962013-08-05 17:40:36 -0700468bool MarkSweep::MarkLargeObject(const Object* obj, bool set) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700469 // TODO: support >1 discontinuous space.
470 space::LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
471 accounting::SpaceSetMap* large_objects = large_object_space->GetMarkObjects();
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700472 if (kProfileLargeObjects) {
473 ++large_object_test_;
474 }
475 if (UNLIKELY(!large_objects->Test(obj))) {
Mathieu Chartier4fcb8d32013-07-15 12:43:36 -0700476 if (!large_object_space->Contains(obj)) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700477 LOG(ERROR) << "Tried to mark " << obj << " not contained by any spaces";
478 LOG(ERROR) << "Attempting see if it's a bad root";
479 VerifyRoots();
480 LOG(FATAL) << "Can't mark bad root";
481 }
482 if (kProfileLargeObjects) {
483 ++large_object_mark_;
484 }
Mathieu Chartier9642c962013-08-05 17:40:36 -0700485 if (set) {
486 large_objects->Set(obj);
487 } else {
488 large_objects->Clear(obj);
489 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700490 return true;
491 }
492 return false;
493}
494
495inline bool MarkSweep::MarkObjectParallel(const Object* obj) {
496 DCHECK(obj != NULL);
497
Mathieu Chartier9642c962013-08-05 17:40:36 -0700498 if (IsImmune(obj)) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700499 DCHECK(IsMarked(obj));
500 return false;
501 }
502
503 // Try to take advantage of locality of references within a space, failing this find the space
504 // the hard way.
Ian Rogers1d54e732013-05-02 21:10:01 -0700505 accounting::SpaceBitmap* object_bitmap = current_mark_bitmap_;
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700506 if (UNLIKELY(!object_bitmap->HasAddress(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700507 accounting::SpaceBitmap* new_bitmap = heap_->GetMarkBitmap()->GetContinuousSpaceBitmap(obj);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700508 if (new_bitmap != NULL) {
509 object_bitmap = new_bitmap;
510 } else {
511 // TODO: Remove the Thread::Current here?
512 // TODO: Convert this to some kind of atomic marking?
513 MutexLock mu(Thread::Current(), large_object_lock_);
Mathieu Chartier9642c962013-08-05 17:40:36 -0700514 return MarkLargeObject(obj, true);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700515 }
516 }
517
518 // Return true if the object was not previously marked.
519 return !object_bitmap->AtomicTestAndSet(obj);
520}
521
Carl Shapiro69759ea2011-07-21 18:13:35 -0700522// Used to mark objects when recursing. Recursion is done by moving
523// the finger across the bitmaps in address order and marking child
524// objects. Any newly-marked objects whose addresses are lower than
525// the finger won't be visited by the bitmap scan, so those objects
526// need to be added to the mark stack.
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700527inline void MarkSweep::MarkObject(const Object* obj) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700528 if (obj != NULL) {
Mathieu Chartier9642c962013-08-05 17:40:36 -0700529 MarkObjectNonNull(obj);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700530 }
531}
532
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800533void MarkSweep::MarkRoot(const Object* obj) {
534 if (obj != NULL) {
Mathieu Chartier9642c962013-08-05 17:40:36 -0700535 MarkObjectNonNull(obj);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800536 }
537}
538
Mathieu Chartier423d2a32013-09-12 17:33:56 -0700539Object* MarkSweep::MarkRootParallelCallback(Object* root, void* arg) {
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800540 DCHECK(root != NULL);
541 DCHECK(arg != NULL);
Mathieu Chartierba311b42013-08-27 13:02:30 -0700542 reinterpret_cast<MarkSweep*>(arg)->MarkObjectNonNullParallel(root);
Mathieu Chartier423d2a32013-09-12 17:33:56 -0700543 return root;
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800544}
545
Mathieu Chartier423d2a32013-09-12 17:33:56 -0700546Object* MarkSweep::MarkRootCallback(Object* root, void* arg) {
547 DCHECK(root != nullptr);
548 DCHECK(arg != nullptr);
549 reinterpret_cast<MarkSweep*>(arg)->MarkObjectNonNull(root);
550 return root;
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700551}
552
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700553void MarkSweep::VerifyRootCallback(const Object* root, void* arg, size_t vreg,
Ian Rogers40e3bac2012-11-20 00:09:14 -0800554 const StackVisitor* visitor) {
555 reinterpret_cast<MarkSweep*>(arg)->VerifyRoot(root, vreg, visitor);
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700556}
557
Ian Rogers40e3bac2012-11-20 00:09:14 -0800558void MarkSweep::VerifyRoot(const Object* root, size_t vreg, const StackVisitor* visitor) {
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700559 // See if the root is on any space bitmap.
Ian Rogers1d54e732013-05-02 21:10:01 -0700560 if (GetHeap()->GetLiveBitmap()->GetContinuousSpaceBitmap(root) == NULL) {
561 space::LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
Mathieu Chartier4202b742012-10-17 17:51:25 -0700562 if (!large_object_space->Contains(root)) {
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700563 LOG(ERROR) << "Found invalid root: " << root;
Ian Rogers40e3bac2012-11-20 00:09:14 -0800564 if (visitor != NULL) {
565 LOG(ERROR) << visitor->DescribeLocation() << " in VReg: " << vreg;
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700566 }
567 }
568 }
569}
570
571void MarkSweep::VerifyRoots() {
572 Runtime::Current()->GetThreadList()->VerifyRoots(VerifyRootCallback, this);
573}
574
Carl Shapiro69759ea2011-07-21 18:13:35 -0700575// Marks all objects in the root set.
576void MarkSweep::MarkRoots() {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700577 timings_.StartSplit("MarkRoots");
Mathieu Chartier423d2a32013-09-12 17:33:56 -0700578 Runtime::Current()->VisitNonConcurrentRoots(MarkRootCallback, this);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700579 timings_.EndSplit();
Mathieu Chartier9ebae1f2012-10-15 17:38:16 -0700580}
581
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700582void MarkSweep::MarkNonThreadRoots() {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700583 timings_.StartSplit("MarkNonThreadRoots");
Mathieu Chartier423d2a32013-09-12 17:33:56 -0700584 Runtime::Current()->VisitNonThreadRoots(MarkRootCallback, this);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700585 timings_.EndSplit();
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700586}
587
Mathieu Chartier9ebae1f2012-10-15 17:38:16 -0700588void MarkSweep::MarkConcurrentRoots() {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700589 timings_.StartSplit("MarkConcurrentRoots");
Ian Rogers1d54e732013-05-02 21:10:01 -0700590 // Visit all runtime roots and clear dirty flags.
Mathieu Chartier423d2a32013-09-12 17:33:56 -0700591 Runtime::Current()->VisitConcurrentRoots(MarkRootCallback, this, false, true);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700592 timings_.EndSplit();
Carl Shapiro69759ea2011-07-21 18:13:35 -0700593}
594
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700595void MarkSweep::CheckObject(const Object* obj) {
596 DCHECK(obj != NULL);
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700597 VisitObjectReferences(const_cast<Object*>(obj), [this](const Object* obj, const Object* ref,
598 MemberOffset offset, bool is_static) NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700599 Locks::heap_bitmap_lock_->AssertSharedHeld(Thread::Current());
600 CheckReference(obj, ref, offset, is_static);
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700601 }, true);
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700602}
603
604void MarkSweep::VerifyImageRootVisitor(Object* root, void* arg) {
605 DCHECK(root != NULL);
606 DCHECK(arg != NULL);
607 MarkSweep* mark_sweep = reinterpret_cast<MarkSweep*>(arg);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700608 DCHECK(mark_sweep->heap_->GetMarkBitmap()->Test(root));
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700609 mark_sweep->CheckObject(root);
610}
611
Ian Rogers1d54e732013-05-02 21:10:01 -0700612void MarkSweep::BindLiveToMarkBitmap(space::ContinuousSpace* space) {
613 CHECK(space->IsDlMallocSpace());
614 space::DlMallocSpace* alloc_space = space->AsDlMallocSpace();
615 accounting::SpaceBitmap* live_bitmap = space->GetLiveBitmap();
616 accounting::SpaceBitmap* mark_bitmap = alloc_space->mark_bitmap_.release();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700617 GetHeap()->GetMarkBitmap()->ReplaceBitmap(mark_bitmap, live_bitmap);
618 alloc_space->temp_bitmap_.reset(mark_bitmap);
619 alloc_space->mark_bitmap_.reset(live_bitmap);
620}
621
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700622class ScanObjectVisitor {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700623 public:
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700624 explicit ScanObjectVisitor(MarkSweep* const mark_sweep) ALWAYS_INLINE
625 : mark_sweep_(mark_sweep) {}
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700626
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800627 // TODO: Fixme when anotatalysis works with visitors.
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700628 void operator()(const Object* obj) const ALWAYS_INLINE NO_THREAD_SAFETY_ANALYSIS {
629 if (kCheckLocks) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800630 Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
631 Locks::heap_bitmap_lock_->AssertExclusiveHeld(Thread::Current());
632 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700633 mark_sweep_->ScanObject(obj);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700634 }
635
636 private:
637 MarkSweep* const mark_sweep_;
638};
639
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700640template <bool kUseFinger = false>
641class MarkStackTask : public Task {
642 public:
643 MarkStackTask(ThreadPool* thread_pool, MarkSweep* mark_sweep, size_t mark_stack_size,
644 const Object** mark_stack)
645 : mark_sweep_(mark_sweep),
646 thread_pool_(thread_pool),
647 mark_stack_pos_(mark_stack_size) {
648 // We may have to copy part of an existing mark stack when another mark stack overflows.
649 if (mark_stack_size != 0) {
650 DCHECK(mark_stack != NULL);
651 // TODO: Check performance?
652 std::copy(mark_stack, mark_stack + mark_stack_size, mark_stack_);
Ian Rogers1d54e732013-05-02 21:10:01 -0700653 }
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700654 if (kCountTasks) {
655 ++mark_sweep_->work_chunks_created_;
656 }
657 }
658
659 static const size_t kMaxSize = 1 * KB;
660
661 protected:
662 class ScanObjectParallelVisitor {
663 public:
664 explicit ScanObjectParallelVisitor(MarkStackTask<kUseFinger>* chunk_task) ALWAYS_INLINE
665 : chunk_task_(chunk_task) {}
666
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700667 void operator()(Object* obj) const {
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700668 MarkSweep* mark_sweep = chunk_task_->mark_sweep_;
669 mark_sweep->ScanObjectVisit(obj,
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700670 [mark_sweep, this](Object* /* obj */, Object* ref, const MemberOffset& /* offset */,
671 bool /* is_static */) ALWAYS_INLINE {
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700672 if (ref != nullptr && mark_sweep->MarkObjectParallel(ref)) {
673 if (kUseFinger) {
674 android_memory_barrier();
675 if (reinterpret_cast<uintptr_t>(ref) >=
676 static_cast<uintptr_t>(mark_sweep->atomic_finger_)) {
677 return;
678 }
679 }
680 chunk_task_->MarkStackPush(ref);
681 }
682 });
683 }
684
685 private:
686 MarkStackTask<kUseFinger>* const chunk_task_;
687 };
688
689 virtual ~MarkStackTask() {
690 // Make sure that we have cleared our mark stack.
691 DCHECK_EQ(mark_stack_pos_, 0U);
692 if (kCountTasks) {
693 ++mark_sweep_->work_chunks_deleted_;
694 }
695 }
696
697 MarkSweep* const mark_sweep_;
698 ThreadPool* const thread_pool_;
699 // Thread local mark stack for this task.
700 const Object* mark_stack_[kMaxSize];
701 // Mark stack position.
702 size_t mark_stack_pos_;
703
704 void MarkStackPush(const Object* obj) ALWAYS_INLINE {
705 if (UNLIKELY(mark_stack_pos_ == kMaxSize)) {
706 // Mark stack overflow, give 1/2 the stack to the thread pool as a new work task.
707 mark_stack_pos_ /= 2;
708 auto* task = new MarkStackTask(thread_pool_, mark_sweep_, kMaxSize - mark_stack_pos_,
709 mark_stack_ + mark_stack_pos_);
710 thread_pool_->AddTask(Thread::Current(), task);
711 }
712 DCHECK(obj != nullptr);
713 DCHECK(mark_stack_pos_ < kMaxSize);
714 mark_stack_[mark_stack_pos_++] = obj;
715 }
716
717 virtual void Finalize() {
718 delete this;
719 }
720
721 // Scans all of the objects
722 virtual void Run(Thread* self) {
723 ScanObjectParallelVisitor visitor(this);
724 // TODO: Tune this.
725 static const size_t kFifoSize = 4;
726 BoundedFifoPowerOfTwo<const Object*, kFifoSize> prefetch_fifo;
727 for (;;) {
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700728 const Object* obj = nullptr;
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700729 if (kUseMarkStackPrefetch) {
730 while (mark_stack_pos_ != 0 && prefetch_fifo.size() < kFifoSize) {
731 const Object* obj = mark_stack_[--mark_stack_pos_];
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700732 DCHECK(obj != nullptr);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700733 __builtin_prefetch(obj);
734 prefetch_fifo.push_back(obj);
735 }
736 if (UNLIKELY(prefetch_fifo.empty())) {
737 break;
738 }
739 obj = prefetch_fifo.front();
740 prefetch_fifo.pop_front();
741 } else {
742 if (UNLIKELY(mark_stack_pos_ == 0)) {
743 break;
744 }
745 obj = mark_stack_[--mark_stack_pos_];
746 }
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700747 DCHECK(obj != nullptr);
748 visitor(const_cast<mirror::Object*>(obj));
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700749 }
750 }
751};
752
753class CardScanTask : public MarkStackTask<false> {
754 public:
755 CardScanTask(ThreadPool* thread_pool, MarkSweep* mark_sweep, accounting::SpaceBitmap* bitmap,
756 byte* begin, byte* end, byte minimum_age, size_t mark_stack_size,
757 const Object** mark_stack_obj)
758 : MarkStackTask<false>(thread_pool, mark_sweep, mark_stack_size, mark_stack_obj),
759 bitmap_(bitmap),
760 begin_(begin),
761 end_(end),
762 minimum_age_(minimum_age) {
763 }
764
765 protected:
766 accounting::SpaceBitmap* const bitmap_;
767 byte* const begin_;
768 byte* const end_;
769 const byte minimum_age_;
770
771 virtual void Finalize() {
772 delete this;
773 }
774
775 virtual void Run(Thread* self) NO_THREAD_SAFETY_ANALYSIS {
776 ScanObjectParallelVisitor visitor(this);
777 accounting::CardTable* card_table = mark_sweep_->GetHeap()->GetCardTable();
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700778 size_t cards_scanned = card_table->Scan(bitmap_, begin_, end_, visitor, minimum_age_);
779 mark_sweep_->cards_scanned_.fetch_add(cards_scanned);
780 VLOG(heap) << "Parallel scanning cards " << reinterpret_cast<void*>(begin_) << " - "
781 << reinterpret_cast<void*>(end_) << " = " << cards_scanned;
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700782 // Finish by emptying our local mark stack.
783 MarkStackTask::Run(self);
784 }
785};
786
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700787size_t MarkSweep::GetThreadCount(bool paused) const {
788 if (heap_->GetThreadPool() == nullptr || !heap_->CareAboutPauseTimes()) {
789 return 0;
790 }
791 if (paused) {
792 return heap_->GetParallelGCThreadCount() + 1;
793 } else {
794 return heap_->GetConcGCThreadCount() + 1;
795 }
796}
797
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700798void MarkSweep::ScanGrayObjects(bool paused, byte minimum_age) {
799 accounting::CardTable* card_table = GetHeap()->GetCardTable();
800 ThreadPool* thread_pool = GetHeap()->GetThreadPool();
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700801 size_t thread_count = GetThreadCount(paused);
802 // The parallel version with only one thread is faster for card scanning, TODO: fix.
803 if (kParallelCardScan && thread_count > 0) {
Mathieu Chartier720ef762013-08-17 14:46:54 -0700804 Thread* self = Thread::Current();
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700805 // Can't have a different split for each space since multiple spaces can have their cards being
806 // scanned at the same time.
807 timings_.StartSplit(paused ? "(Paused)ScanGrayObjects" : "ScanGrayObjects");
808 // Try to take some of the mark stack since we can pass this off to the worker tasks.
809 const Object** mark_stack_begin = const_cast<const Object**>(mark_stack_->Begin());
810 const Object** mark_stack_end = const_cast<const Object**>(mark_stack_->End());
Mathieu Chartier720ef762013-08-17 14:46:54 -0700811 const size_t mark_stack_size = mark_stack_end - mark_stack_begin;
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700812 // Estimated number of work tasks we will create.
813 const size_t mark_stack_tasks = GetHeap()->GetContinuousSpaces().size() * thread_count;
814 DCHECK_NE(mark_stack_tasks, 0U);
815 const size_t mark_stack_delta = std::min(CardScanTask::kMaxSize / 2,
816 mark_stack_size / mark_stack_tasks + 1);
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700817 size_t ref_card_count = 0;
818 cards_scanned_ = 0;
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700819 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
820 byte* card_begin = space->Begin();
821 byte* card_end = space->End();
822 // Calculate how many bytes of heap we will scan,
823 const size_t address_range = card_end - card_begin;
824 // Calculate how much address range each task gets.
825 const size_t card_delta = RoundUp(address_range / thread_count + 1,
826 accounting::CardTable::kCardSize);
827 // Create the worker tasks for this space.
828 while (card_begin != card_end) {
829 // Add a range of cards.
830 size_t addr_remaining = card_end - card_begin;
831 size_t card_increment = std::min(card_delta, addr_remaining);
832 // Take from the back of the mark stack.
833 size_t mark_stack_remaining = mark_stack_end - mark_stack_begin;
834 size_t mark_stack_increment = std::min(mark_stack_delta, mark_stack_remaining);
835 mark_stack_end -= mark_stack_increment;
836 mark_stack_->PopBackCount(static_cast<int32_t>(mark_stack_increment));
837 DCHECK_EQ(mark_stack_end, mark_stack_->End());
838 // Add the new task to the thread pool.
839 auto* task = new CardScanTask(thread_pool, this, space->GetMarkBitmap(), card_begin,
840 card_begin + card_increment, minimum_age,
841 mark_stack_increment, mark_stack_end);
842 thread_pool->AddTask(self, task);
843 card_begin += card_increment;
844 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700845
846 if (paused && kIsDebugBuild) {
847 // Make sure we don't miss scanning any cards.
848 size_t scanned_cards = card_table->Scan(space->GetMarkBitmap(), space->Begin(),
849 space->End(), VoidFunctor(), minimum_age);
850 VLOG(heap) << "Scanning space cards " << reinterpret_cast<void*>(space->Begin()) << " - "
851 << reinterpret_cast<void*>(space->End()) << " = " << scanned_cards;
852 ref_card_count += scanned_cards;
853 }
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700854 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700855
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700856 thread_pool->SetMaxActiveWorkers(thread_count - 1);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700857 thread_pool->StartWorkers(self);
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700858 thread_pool->Wait(self, true, true);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700859 thread_pool->StopWorkers(self);
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700860 if (paused) {
861 DCHECK_EQ(ref_card_count, static_cast<size_t>(cards_scanned_.load()));
862 }
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700863 timings_.EndSplit();
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700864 } else {
865 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
866 // Image spaces are handled properly since live == marked for them.
867 switch (space->GetGcRetentionPolicy()) {
868 case space::kGcRetentionPolicyNeverCollect:
869 timings_.StartSplit(paused ? "(Paused)ScanGrayImageSpaceObjects" :
870 "ScanGrayImageSpaceObjects");
871 break;
872 case space::kGcRetentionPolicyFullCollect:
873 timings_.StartSplit(paused ? "(Paused)ScanGrayZygoteSpaceObjects" :
874 "ScanGrayZygoteSpaceObjects");
875 break;
876 case space::kGcRetentionPolicyAlwaysCollect:
877 timings_.StartSplit(paused ? "(Paused)ScanGrayAllocSpaceObjects" :
878 "ScanGrayAllocSpaceObjects");
879 break;
880 }
881 ScanObjectVisitor visitor(this);
882 card_table->Scan(space->GetMarkBitmap(), space->Begin(), space->End(), visitor, minimum_age);
883 timings_.EndSplit();
884 }
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700885 }
886}
887
888void MarkSweep::VerifyImageRoots() {
889 // Verify roots ensures that all the references inside the image space point
890 // objects which are either in the image space or marked objects in the alloc
891 // space
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700892 timings_.StartSplit("VerifyImageRoots");
Mathieu Chartier02e25112013-08-14 16:14:24 -0700893 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
894 if (space->IsImageSpace()) {
895 space::ImageSpace* image_space = space->AsImageSpace();
896 uintptr_t begin = reinterpret_cast<uintptr_t>(image_space->Begin());
897 uintptr_t end = reinterpret_cast<uintptr_t>(image_space->End());
898 accounting::SpaceBitmap* live_bitmap = image_space->GetLiveBitmap();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700899 DCHECK(live_bitmap != NULL);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700900 live_bitmap->VisitMarkedRange(begin, end, [this](const Object* obj) {
901 if (kCheckLocks) {
902 Locks::heap_bitmap_lock_->AssertSharedHeld(Thread::Current());
903 }
904 DCHECK(obj != NULL);
905 CheckObject(obj);
906 });
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700907 }
908 }
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700909 timings_.EndSplit();
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700910}
911
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700912class RecursiveMarkTask : public MarkStackTask<false> {
913 public:
914 RecursiveMarkTask(ThreadPool* thread_pool, MarkSweep* mark_sweep,
915 accounting::SpaceBitmap* bitmap, uintptr_t begin, uintptr_t end)
916 : MarkStackTask<false>(thread_pool, mark_sweep, 0, NULL),
917 bitmap_(bitmap),
918 begin_(begin),
919 end_(end) {
920 }
921
922 protected:
923 accounting::SpaceBitmap* const bitmap_;
924 const uintptr_t begin_;
925 const uintptr_t end_;
926
927 virtual void Finalize() {
928 delete this;
929 }
930
931 // Scans all of the objects
932 virtual void Run(Thread* self) NO_THREAD_SAFETY_ANALYSIS {
933 ScanObjectParallelVisitor visitor(this);
934 bitmap_->VisitMarkedRange(begin_, end_, visitor);
935 // Finish by emptying our local mark stack.
936 MarkStackTask::Run(self);
937 }
938};
939
Carl Shapiro58551df2011-07-24 03:09:51 -0700940// Populates the mark stack based on the set of marked objects and
941// recursively marks until the mark stack is emptied.
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800942void MarkSweep::RecursiveMark() {
Anwar Ghuloum46543222013-08-12 09:28:42 -0700943 base::TimingLogger::ScopedSplit split("RecursiveMark", &timings_);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700944 // RecursiveMark will build the lists of known instances of the Reference classes.
945 // See DelayReferenceReferent for details.
946 CHECK(soft_reference_list_ == NULL);
947 CHECK(weak_reference_list_ == NULL);
948 CHECK(finalizer_reference_list_ == NULL);
949 CHECK(phantom_reference_list_ == NULL);
950 CHECK(cleared_reference_list_ == NULL);
951
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700952 if (kUseRecursiveMark) {
953 const bool partial = GetGcType() == kGcTypePartial;
954 ScanObjectVisitor scan_visitor(this);
955 auto* self = Thread::Current();
956 ThreadPool* thread_pool = heap_->GetThreadPool();
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700957 size_t thread_count = GetThreadCount(false);
958 const bool parallel = kParallelRecursiveMark && thread_count > 1;
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700959 mark_stack_->Reset();
Mathieu Chartier02e25112013-08-14 16:14:24 -0700960 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700961 if ((space->GetGcRetentionPolicy() == space::kGcRetentionPolicyAlwaysCollect) ||
962 (!partial && space->GetGcRetentionPolicy() == space::kGcRetentionPolicyFullCollect)) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800963 current_mark_bitmap_ = space->GetMarkBitmap();
964 if (current_mark_bitmap_ == NULL) {
965 GetHeap()->DumpSpaces();
966 LOG(FATAL) << "invalid bitmap";
967 }
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700968 if (parallel) {
969 // We will use the mark stack the future.
970 // CHECK(mark_stack_->IsEmpty());
971 // This function does not handle heap end increasing, so we must use the space end.
972 uintptr_t begin = reinterpret_cast<uintptr_t>(space->Begin());
973 uintptr_t end = reinterpret_cast<uintptr_t>(space->End());
974 atomic_finger_ = static_cast<int32_t>(0xFFFFFFFF);
975
976 // Create a few worker tasks.
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700977 const size_t n = thread_count * 2;
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700978 while (begin != end) {
979 uintptr_t start = begin;
980 uintptr_t delta = (end - begin) / n;
981 delta = RoundUp(delta, KB);
982 if (delta < 16 * KB) delta = end - begin;
983 begin += delta;
984 auto* task = new RecursiveMarkTask(thread_pool, this, current_mark_bitmap_, start,
985 begin);
986 thread_pool->AddTask(self, task);
987 }
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700988 thread_pool->SetMaxActiveWorkers(thread_count - 1);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700989 thread_pool->StartWorkers(self);
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700990 thread_pool->Wait(self, true, true);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700991 thread_pool->StopWorkers(self);
992 } else {
993 // This function does not handle heap end increasing, so we must use the space end.
994 uintptr_t begin = reinterpret_cast<uintptr_t>(space->Begin());
995 uintptr_t end = reinterpret_cast<uintptr_t>(space->End());
996 current_mark_bitmap_->VisitMarkedRange(begin, end, scan_visitor);
997 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700998 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700999 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001000 }
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001001 ProcessMarkStack(false);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001002}
1003
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001004mirror::Object* MarkSweep::SystemWeakIsMarkedCallback(Object* object, void* arg) {
Mathieu Chartier5712d5d2013-09-18 17:59:36 -07001005 if (reinterpret_cast<MarkSweep*>(arg)->IsMarked(object)) {
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001006 return object;
1007 }
1008 return nullptr;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001009}
1010
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001011void MarkSweep::RecursiveMarkDirtyObjects(bool paused, byte minimum_age) {
1012 ScanGrayObjects(paused, minimum_age);
1013 ProcessMarkStack(paused);
Mathieu Chartier262e5ff2012-06-01 17:35:38 -07001014}
1015
Carl Shapiro58551df2011-07-24 03:09:51 -07001016void MarkSweep::ReMarkRoots() {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001017 timings_.StartSplit("ReMarkRoots");
Mathieu Chartier423d2a32013-09-12 17:33:56 -07001018 Runtime::Current()->VisitRoots(MarkRootCallback, this, true, true);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001019 timings_.EndSplit();
Carl Shapiro69759ea2011-07-21 18:13:35 -07001020}
1021
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001022void MarkSweep::SweepSystemWeaks() {
1023 Runtime* runtime = Runtime::Current();
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001024 timings_.StartSplit("SweepSystemWeaks");
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001025 runtime->SweepSystemWeaks(SystemWeakIsMarkedCallback, this);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001026 timings_.EndSplit();
Carl Shapiro58551df2011-07-24 03:09:51 -07001027}
1028
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001029mirror::Object* MarkSweep::VerifySystemWeakIsLiveCallback(Object* obj, void* arg) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001030 reinterpret_cast<MarkSweep*>(arg)->VerifyIsLive(obj);
1031 // We don't actually want to sweep the object, so lets return "marked"
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001032 return obj;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001033}
1034
1035void MarkSweep::VerifyIsLive(const Object* obj) {
1036 Heap* heap = GetHeap();
1037 if (!heap->GetLiveBitmap()->Test(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001038 space::LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001039 if (!large_object_space->GetLiveObjects()->Test(obj)) {
1040 if (std::find(heap->allocation_stack_->Begin(), heap->allocation_stack_->End(), obj) ==
1041 heap->allocation_stack_->End()) {
1042 // Object not found!
1043 heap->DumpSpaces();
1044 LOG(FATAL) << "Found dead object " << obj;
1045 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001046 }
1047 }
1048}
1049
1050void MarkSweep::VerifySystemWeaks() {
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001051 // Verify system weaks, uses a special object visitor which returns the input object.
1052 Runtime::Current()->SweepSystemWeaks(VerifySystemWeakIsLiveCallback, this);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001053}
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();
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001132 timings_.StartSplit("SweepArray");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001133 // Newly allocated objects MUST be in the alloc space and those are the only objects which we are
1134 // going to free.
Ian Rogers1d54e732013-05-02 21:10:01 -07001135 accounting::SpaceBitmap* live_bitmap = space->GetLiveBitmap();
1136 accounting::SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
1137 space::LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
1138 accounting::SpaceSetMap* large_live_objects = large_object_space->GetLiveObjects();
1139 accounting::SpaceSetMap* large_mark_objects = large_object_space->GetMarkObjects();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001140 if (swap_bitmaps) {
1141 std::swap(live_bitmap, mark_bitmap);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001142 std::swap(large_live_objects, large_mark_objects);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001143 }
1144
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001145 size_t freed_bytes = 0;
1146 size_t freed_large_object_bytes = 0;
Hiroshi Yamauchib22a4512013-08-13 15:03:22 -07001147 size_t freed_objects = 0;
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001148 size_t freed_large_objects = 0;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001149 size_t count = allocations->Size();
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001150 Object** objects = const_cast<Object**>(allocations->Begin());
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001151 Object** out = objects;
Hiroshi Yamauchib22a4512013-08-13 15:03:22 -07001152 Object** objects_to_chunk_free = out;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001153
1154 // Empty the allocation stack.
Ian Rogers50b35e22012-10-04 10:09:15 -07001155 Thread* self = Thread::Current();
Brian Carlstrom02c8cc62013-07-18 15:54:44 -07001156 for (size_t i = 0; i < count; ++i) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001157 Object* obj = objects[i];
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001158 // There should only be objects in the AllocSpace/LargeObjectSpace in the allocation stack.
1159 if (LIKELY(mark_bitmap->HasAddress(obj))) {
1160 if (!mark_bitmap->Test(obj)) {
1161 // Don't bother un-marking since we clear the mark bitmap anyways.
1162 *(out++) = obj;
Hiroshi Yamauchib22a4512013-08-13 15:03:22 -07001163 // Free objects in chunks.
1164 DCHECK_GE(out, objects_to_chunk_free);
1165 DCHECK_LE(static_cast<size_t>(out - objects_to_chunk_free), kSweepArrayChunkFreeSize);
1166 if (static_cast<size_t>(out - objects_to_chunk_free) == kSweepArrayChunkFreeSize) {
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001167 timings_.StartSplit("FreeList");
Hiroshi Yamauchib22a4512013-08-13 15:03:22 -07001168 size_t chunk_freed_objects = out - objects_to_chunk_free;
1169 freed_objects += chunk_freed_objects;
1170 freed_bytes += space->FreeList(self, chunk_freed_objects, objects_to_chunk_free);
1171 objects_to_chunk_free = out;
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001172 timings_.EndSplit();
Hiroshi Yamauchib22a4512013-08-13 15:03:22 -07001173 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001174 }
1175 } else if (!large_mark_objects->Test(obj)) {
1176 ++freed_large_objects;
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001177 freed_large_object_bytes += large_object_space->Free(self, obj);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001178 }
1179 }
Hiroshi Yamauchib22a4512013-08-13 15:03:22 -07001180 // Free the remaining objects in chunks.
1181 DCHECK_GE(out, objects_to_chunk_free);
1182 DCHECK_LE(static_cast<size_t>(out - objects_to_chunk_free), kSweepArrayChunkFreeSize);
1183 if (out - objects_to_chunk_free > 0) {
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001184 timings_.StartSplit("FreeList");
Hiroshi Yamauchib22a4512013-08-13 15:03:22 -07001185 size_t chunk_freed_objects = out - objects_to_chunk_free;
1186 freed_objects += chunk_freed_objects;
1187 freed_bytes += space->FreeList(self, chunk_freed_objects, objects_to_chunk_free);
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001188 timings_.EndSplit();
Hiroshi Yamauchib22a4512013-08-13 15:03:22 -07001189 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001190 CHECK_EQ(count, allocations->Size());
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001191 timings_.EndSplit();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001192
Hiroshi Yamauchib22a4512013-08-13 15:03:22 -07001193 timings_.StartSplit("RecordFree");
Mathieu Chartier40e978b2012-09-07 11:38:36 -07001194 VLOG(heap) << "Freed " << freed_objects << "/" << count
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001195 << " objects with size " << PrettySize(freed_bytes);
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001196 heap_->RecordFree(freed_objects + freed_large_objects, freed_bytes + freed_large_object_bytes);
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -07001197 freed_objects_.fetch_add(freed_objects);
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001198 freed_large_objects_.fetch_add(freed_large_objects);
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -07001199 freed_bytes_.fetch_add(freed_bytes);
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001200 freed_large_object_bytes_.fetch_add(freed_large_object_bytes);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001201 timings_.EndSplit();
Ian Rogers1d54e732013-05-02 21:10:01 -07001202
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001203 timings_.StartSplit("ResetStack");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001204 allocations->Reset();
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001205 timings_.EndSplit();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001206}
1207
Ian Rogers1d54e732013-05-02 21:10:01 -07001208void MarkSweep::Sweep(bool swap_bitmaps) {
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001209 DCHECK(mark_stack_->IsEmpty());
Anwar Ghuloum46543222013-08-12 09:28:42 -07001210 base::TimingLogger::ScopedSplit("Sweep", &timings_);
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001211
Ian Rogers1d54e732013-05-02 21:10:01 -07001212 const bool partial = (GetGcType() == kGcTypePartial);
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001213 SweepCallbackContext scc;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001214 scc.mark_sweep = this;
Ian Rogers50b35e22012-10-04 10:09:15 -07001215 scc.self = Thread::Current();
Mathieu Chartier02e25112013-08-14 16:14:24 -07001216 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001217 // We always sweep always collect spaces.
1218 bool sweep_space = (space->GetGcRetentionPolicy() == space::kGcRetentionPolicyAlwaysCollect);
1219 if (!partial && !sweep_space) {
1220 // We sweep full collect spaces when the GC isn't a partial GC (ie its full).
1221 sweep_space = (space->GetGcRetentionPolicy() == space::kGcRetentionPolicyFullCollect);
1222 }
1223 if (sweep_space) {
Mathieu Chartier720ef762013-08-17 14:46:54 -07001224 uintptr_t begin = reinterpret_cast<uintptr_t>(space->Begin());
1225 uintptr_t end = reinterpret_cast<uintptr_t>(space->End());
Ian Rogers1d54e732013-05-02 21:10:01 -07001226 scc.space = space->AsDlMallocSpace();
1227 accounting::SpaceBitmap* live_bitmap = space->GetLiveBitmap();
1228 accounting::SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001229 if (swap_bitmaps) {
1230 std::swap(live_bitmap, mark_bitmap);
1231 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001232 if (!space->IsZygoteSpace()) {
Anwar Ghuloum46543222013-08-12 09:28:42 -07001233 base::TimingLogger::ScopedSplit split("SweepAllocSpace", &timings_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001234 // Bitmaps are pre-swapped for optimization which enables sweeping with the heap unlocked.
Ian Rogers1d54e732013-05-02 21:10:01 -07001235 accounting::SpaceBitmap::SweepWalk(*live_bitmap, *mark_bitmap, begin, end,
1236 &SweepCallback, reinterpret_cast<void*>(&scc));
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001237 } else {
Anwar Ghuloum46543222013-08-12 09:28:42 -07001238 base::TimingLogger::ScopedSplit split("SweepZygote", &timings_);
Ian Rogers1d54e732013-05-02 21:10:01 -07001239 // Zygote sweep takes care of dirtying cards and clearing live bits, does not free actual
1240 // memory.
1241 accounting::SpaceBitmap::SweepWalk(*live_bitmap, *mark_bitmap, begin, end,
1242 &ZygoteSweepCallback, reinterpret_cast<void*>(&scc));
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001243 }
Carl Shapiro58551df2011-07-24 03:09:51 -07001244 }
1245 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001246
1247 SweepLargeObjects(swap_bitmaps);
Carl Shapiro58551df2011-07-24 03:09:51 -07001248}
1249
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001250void MarkSweep::SweepLargeObjects(bool swap_bitmaps) {
Anwar Ghuloum46543222013-08-12 09:28:42 -07001251 base::TimingLogger::ScopedSplit("SweepLargeObjects", &timings_);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001252 // Sweep large objects
Ian Rogers1d54e732013-05-02 21:10:01 -07001253 space::LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
1254 accounting::SpaceSetMap* large_live_objects = large_object_space->GetLiveObjects();
1255 accounting::SpaceSetMap* large_mark_objects = large_object_space->GetMarkObjects();
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001256 if (swap_bitmaps) {
1257 std::swap(large_live_objects, large_mark_objects);
1258 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001259 // O(n*log(n)) but hopefully there are not too many large objects.
1260 size_t freed_objects = 0;
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001261 size_t freed_bytes = 0;
Ian Rogers50b35e22012-10-04 10:09:15 -07001262 Thread* self = Thread::Current();
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001263 for (const Object* obj : large_live_objects->GetObjects()) {
Mathieu Chartier02e25112013-08-14 16:14:24 -07001264 if (!large_mark_objects->Test(obj)) {
1265 freed_bytes += large_object_space->Free(self, const_cast<Object*>(obj));
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001266 ++freed_objects;
1267 }
1268 }
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001269 freed_large_objects_.fetch_add(freed_objects);
1270 freed_large_object_bytes_.fetch_add(freed_bytes);
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001271 GetHeap()->RecordFree(freed_objects, freed_bytes);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001272}
1273
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001274void MarkSweep::CheckReference(const Object* obj, const Object* ref, MemberOffset offset, bool is_static) {
Mathieu Chartier02e25112013-08-14 16:14:24 -07001275 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001276 if (space->IsDlMallocSpace() && space->Contains(ref)) {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001277 DCHECK(IsMarked(obj));
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001278
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001279 bool is_marked = IsMarked(ref);
1280 if (!is_marked) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001281 LOG(INFO) << *space;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001282 LOG(WARNING) << (is_static ? "Static ref'" : "Instance ref'") << PrettyTypeOf(ref)
1283 << "' (" << reinterpret_cast<const void*>(ref) << ") in '" << PrettyTypeOf(obj)
1284 << "' (" << reinterpret_cast<const void*>(obj) << ") at offset "
1285 << reinterpret_cast<void*>(offset.Int32Value()) << " wasn't marked";
Mathieu Chartier262e5ff2012-06-01 17:35:38 -07001286
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001287 const Class* klass = is_static ? obj->AsClass() : obj->GetClass();
1288 DCHECK(klass != NULL);
Brian Carlstromea46f952013-07-30 01:26:50 -07001289 const ObjectArray<ArtField>* fields = is_static ? klass->GetSFields() : klass->GetIFields();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001290 DCHECK(fields != NULL);
1291 bool found = false;
1292 for (int32_t i = 0; i < fields->GetLength(); ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001293 const ArtField* cur = fields->Get(i);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001294 if (cur->GetOffset().Int32Value() == offset.Int32Value()) {
1295 LOG(WARNING) << "Field referencing the alloc space was " << PrettyField(cur);
1296 found = true;
1297 break;
1298 }
1299 }
1300 if (!found) {
1301 LOG(WARNING) << "Could not find field in object alloc space with offset " << offset.Int32Value();
1302 }
Mathieu Chartier262e5ff2012-06-01 17:35:38 -07001303
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001304 bool obj_marked = heap_->GetCardTable()->IsDirty(obj);
1305 if (!obj_marked) {
1306 LOG(WARNING) << "Object '" << PrettyTypeOf(obj) << "' "
1307 << "(" << reinterpret_cast<const void*>(obj) << ") contains references to "
1308 << "the alloc space, but wasn't card marked";
Mathieu Chartier262e5ff2012-06-01 17:35:38 -07001309 }
1310 }
Ian Rogers5d76c432011-10-31 21:42:49 -07001311 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001312 break;
Ian Rogers5d76c432011-10-31 21:42:49 -07001313 }
1314}
1315
Carl Shapiro69759ea2011-07-21 18:13:35 -07001316// Process the "referent" field in a java.lang.ref.Reference. If the
1317// referent has not yet been marked, put it on the appropriate list in
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001318// the heap for later processing.
1319void MarkSweep::DelayReferenceReferent(mirror::Class* klass, Object* obj) {
1320 DCHECK(klass != nullptr);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001321 DCHECK(klass->IsReferenceClass());
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001322 DCHECK(obj != NULL);
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001323 Object* referent = heap_->GetReferenceReferent(obj);
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001324 if (referent != NULL && !IsMarked(referent)) {
1325 if (kCountJavaLangRefs) {
1326 ++reference_count_;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001327 }
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001328 Thread* self = Thread::Current();
1329 // TODO: Remove these locks, and use atomic stacks for storing references?
Mathieu Chartierb4ea4de2013-09-18 09:58:29 -07001330 // We need to check that the references haven't already been enqueued since we can end up
1331 // scanning the same reference multiple times due to dirty cards.
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001332 if (klass->IsSoftReferenceClass()) {
1333 MutexLock mu(self, *heap_->GetSoftRefQueueLock());
Mathieu Chartierb4ea4de2013-09-18 09:58:29 -07001334 if (!heap_->IsEnqueued(obj)) {
1335 heap_->EnqueuePendingReference(obj, &soft_reference_list_);
1336 }
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001337 } else if (klass->IsWeakReferenceClass()) {
1338 MutexLock mu(self, *heap_->GetWeakRefQueueLock());
Mathieu Chartierb4ea4de2013-09-18 09:58:29 -07001339 if (!heap_->IsEnqueued(obj)) {
1340 heap_->EnqueuePendingReference(obj, &weak_reference_list_);
1341 }
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001342 } else if (klass->IsFinalizerReferenceClass()) {
1343 MutexLock mu(self, *heap_->GetFinalizerRefQueueLock());
Mathieu Chartierb4ea4de2013-09-18 09:58:29 -07001344 if (!heap_->IsEnqueued(obj)) {
1345 heap_->EnqueuePendingReference(obj, &finalizer_reference_list_);
1346 }
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001347 } else if (klass->IsPhantomReferenceClass()) {
1348 MutexLock mu(self, *heap_->GetPhantomRefQueueLock());
Mathieu Chartierb4ea4de2013-09-18 09:58:29 -07001349 if (!heap_->IsEnqueued(obj)) {
1350 heap_->EnqueuePendingReference(obj, &phantom_reference_list_);
1351 }
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001352 } else {
1353 LOG(FATAL) << "Invalid reference type " << PrettyClass(klass)
1354 << " " << std::hex << klass->GetAccessFlags();
1355 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001356 }
1357}
1358
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001359void MarkSweep::ScanRoot(const Object* obj) {
1360 ScanObject(obj);
1361}
1362
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001363class MarkObjectVisitor {
1364 public:
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001365 explicit MarkObjectVisitor(MarkSweep* const mark_sweep) ALWAYS_INLINE : mark_sweep_(mark_sweep) {}
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001366
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001367 // TODO: Fixme when anotatalysis works with visitors.
Brian Carlstromdf629502013-07-17 22:39:56 -07001368 void operator()(const Object* /* obj */, const Object* ref, const MemberOffset& /* offset */,
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001369 bool /* is_static */) const ALWAYS_INLINE
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001370 NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001371 if (kCheckLocks) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001372 Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
1373 Locks::heap_bitmap_lock_->AssertExclusiveHeld(Thread::Current());
1374 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001375 mark_sweep_->MarkObject(ref);
1376 }
1377
1378 private:
1379 MarkSweep* const mark_sweep_;
1380};
1381
Carl Shapiro69759ea2011-07-21 18:13:35 -07001382// Scans an object reference. Determines the type of the reference
1383// and dispatches to a specialized scanning routine.
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001384void MarkSweep::ScanObject(const Object* obj) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001385 MarkObjectVisitor visitor(this);
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001386 ScanObjectVisit(const_cast<Object*>(obj), visitor);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001387}
1388
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001389void MarkSweep::ProcessMarkStackParallel(size_t thread_count) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001390 Thread* self = Thread::Current();
1391 ThreadPool* thread_pool = GetHeap()->GetThreadPool();
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001392 const size_t chunk_size = std::min(mark_stack_->Size() / thread_count + 1,
1393 static_cast<size_t>(MarkStackTask<false>::kMaxSize));
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001394 CHECK_GT(chunk_size, 0U);
1395 // Split the current mark stack up into work tasks.
1396 for (mirror::Object **it = mark_stack_->Begin(), **end = mark_stack_->End(); it < end; ) {
1397 const size_t delta = std::min(static_cast<size_t>(end - it), chunk_size);
1398 thread_pool->AddTask(self, new MarkStackTask<false>(thread_pool, this, delta,
1399 const_cast<const mirror::Object**>(it)));
1400 it += delta;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001401 }
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001402 thread_pool->SetMaxActiveWorkers(thread_count - 1);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001403 thread_pool->StartWorkers(self);
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001404 thread_pool->Wait(self, true, true);
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001405 thread_pool->StopWorkers(self);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001406 mark_stack_->Reset();
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001407 CHECK_EQ(work_chunks_created_, work_chunks_deleted_) << " some of the work chunks were leaked";
Carl Shapiro69759ea2011-07-21 18:13:35 -07001408}
1409
Ian Rogers5d76c432011-10-31 21:42:49 -07001410// Scan anything that's on the mark stack.
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001411void MarkSweep::ProcessMarkStack(bool paused) {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001412 timings_.StartSplit("ProcessMarkStack");
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001413 size_t thread_count = GetThreadCount(paused);
1414 if (kParallelProcessMarkStack && thread_count > 1 &&
1415 mark_stack_->Size() >= kMinimumParallelMarkStackSize) {
1416 ProcessMarkStackParallel(thread_count);
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001417 } else {
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001418 // TODO: Tune this.
1419 static const size_t kFifoSize = 4;
1420 BoundedFifoPowerOfTwo<const Object*, kFifoSize> prefetch_fifo;
1421 for (;;) {
1422 const Object* obj = NULL;
1423 if (kUseMarkStackPrefetch) {
1424 while (!mark_stack_->IsEmpty() && prefetch_fifo.size() < kFifoSize) {
1425 const Object* obj = mark_stack_->PopBack();
1426 DCHECK(obj != NULL);
1427 __builtin_prefetch(obj);
1428 prefetch_fifo.push_back(obj);
1429 }
1430 if (prefetch_fifo.empty()) {
1431 break;
1432 }
1433 obj = prefetch_fifo.front();
1434 prefetch_fifo.pop_front();
1435 } else {
1436 if (mark_stack_->IsEmpty()) {
1437 break;
1438 }
1439 obj = mark_stack_->PopBack();
1440 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001441 DCHECK(obj != NULL);
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001442 ScanObject(obj);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001443 }
1444 }
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001445 timings_.EndSplit();
Carl Shapiro69759ea2011-07-21 18:13:35 -07001446}
1447
Carl Shapiro69759ea2011-07-21 18:13:35 -07001448// Walks the reference list marking any references subject to the
1449// reference clearing policy. References with a black referent are
1450// removed from the list. References with white referents biased
1451// toward saving are blackened and also removed from the list.
1452void MarkSweep::PreserveSomeSoftReferences(Object** list) {
1453 DCHECK(list != NULL);
1454 Object* clear = NULL;
1455 size_t counter = 0;
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001456
1457 DCHECK(mark_stack_->IsEmpty());
1458
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001459 timings_.StartSplit("PreserveSomeSoftReferences");
Carl Shapiro69759ea2011-07-21 18:13:35 -07001460 while (*list != NULL) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001461 Object* ref = heap_->DequeuePendingReference(list);
1462 Object* referent = heap_->GetReferenceReferent(ref);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001463 if (referent == NULL) {
1464 // Referent was cleared by the user during marking.
1465 continue;
1466 }
1467 bool is_marked = IsMarked(referent);
1468 if (!is_marked && ((++counter) & 1)) {
1469 // Referent is white and biased toward saving, mark it.
1470 MarkObject(referent);
1471 is_marked = true;
1472 }
1473 if (!is_marked) {
1474 // Referent is white, queue it for clearing.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001475 heap_->EnqueuePendingReference(ref, &clear);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001476 }
1477 }
1478 *list = clear;
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001479 timings_.EndSplit();
1480
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001481 // Restart the mark with the newly black references added to the root set.
1482 ProcessMarkStack(true);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001483}
1484
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001485inline bool MarkSweep::IsMarked(const Object* object) const
1486 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
Mathieu Chartier9642c962013-08-05 17:40:36 -07001487 if (IsImmune(object)) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001488 return true;
1489 }
1490 DCHECK(current_mark_bitmap_ != NULL);
1491 if (current_mark_bitmap_->HasAddress(object)) {
1492 return current_mark_bitmap_->Test(object);
1493 }
1494 return heap_->GetMarkBitmap()->Test(object);
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) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001549 CHECK(soft_references != NULL);
1550 CHECK(weak_references != NULL);
1551 CHECK(finalizer_references != NULL);
1552 CHECK(phantom_references != NULL);
1553 CHECK(mark_stack_->IsEmpty());
Carl Shapiro69759ea2011-07-21 18:13:35 -07001554
1555 // Unless we are in the zygote or required to clear soft references
1556 // with white references, preserve some white referents.
Ian Rogers2945e242012-06-03 14:45:16 -07001557 if (!clear_soft && !Runtime::Current()->IsZygote()) {
Carl Shapiro69759ea2011-07-21 18:13:35 -07001558 PreserveSomeSoftReferences(soft_references);
1559 }
1560
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001561 timings_.StartSplit("ProcessReferences");
Carl Shapiro69759ea2011-07-21 18:13:35 -07001562 // Clear all remaining soft and weak references with white
1563 // referents.
1564 ClearWhiteReferences(soft_references);
1565 ClearWhiteReferences(weak_references);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001566 timings_.EndSplit();
Carl Shapiro69759ea2011-07-21 18:13:35 -07001567
1568 // Preserve all white objects with finalize methods and schedule
1569 // them for finalization.
1570 EnqueueFinalizerReferences(finalizer_references);
1571
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001572 timings_.StartSplit("ProcessReferences");
Carl Shapiro69759ea2011-07-21 18:13:35 -07001573 // Clear all f-reachable soft and weak references with white
1574 // referents.
1575 ClearWhiteReferences(soft_references);
1576 ClearWhiteReferences(weak_references);
1577
1578 // Clear all phantom references with white referents.
1579 ClearWhiteReferences(phantom_references);
1580
1581 // At this point all reference lists should be empty.
1582 DCHECK(*soft_references == NULL);
1583 DCHECK(*weak_references == NULL);
1584 DCHECK(*finalizer_references == NULL);
1585 DCHECK(*phantom_references == NULL);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001586 timings_.EndSplit();
Carl Shapiro69759ea2011-07-21 18:13:35 -07001587}
1588
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001589void MarkSweep::UnBindBitmaps() {
Anwar Ghuloum46543222013-08-12 09:28:42 -07001590 base::TimingLogger::ScopedSplit split("UnBindBitmaps", &timings_);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001591 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001592 if (space->IsDlMallocSpace()) {
1593 space::DlMallocSpace* alloc_space = space->AsDlMallocSpace();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001594 if (alloc_space->temp_bitmap_.get() != NULL) {
1595 // At this point, the temp_bitmap holds our old mark bitmap.
Ian Rogers1d54e732013-05-02 21:10:01 -07001596 accounting::SpaceBitmap* new_bitmap = alloc_space->temp_bitmap_.release();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001597 GetHeap()->GetMarkBitmap()->ReplaceBitmap(alloc_space->mark_bitmap_.get(), new_bitmap);
1598 CHECK_EQ(alloc_space->mark_bitmap_.release(), alloc_space->live_bitmap_.get());
1599 alloc_space->mark_bitmap_.reset(new_bitmap);
1600 DCHECK(alloc_space->temp_bitmap_.get() == NULL);
1601 }
1602 }
1603 }
1604}
1605
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001606void MarkSweep::FinishPhase() {
Anwar Ghuloum46543222013-08-12 09:28:42 -07001607 base::TimingLogger::ScopedSplit split("FinishPhase", &timings_);
1608 // Can't enqueue references if we hold the mutator lock.
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001609 Object* cleared_references = GetClearedReferences();
Ian Rogers1d54e732013-05-02 21:10:01 -07001610 Heap* heap = GetHeap();
Anwar Ghuloum46543222013-08-12 09:28:42 -07001611 timings_.NewSplit("EnqueueClearedReferences");
Ian Rogers1d54e732013-05-02 21:10:01 -07001612 heap->EnqueueClearedReferences(&cleared_references);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001613
Anwar Ghuloum46543222013-08-12 09:28:42 -07001614 timings_.NewSplit("PostGcVerification");
Ian Rogers1d54e732013-05-02 21:10:01 -07001615 heap->PostGcVerification(this);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001616
Anwar Ghuloum46543222013-08-12 09:28:42 -07001617 timings_.NewSplit("GrowForUtilization");
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001618 heap->GrowForUtilization(GetGcType(), GetDurationNs());
Mathieu Chartier65db8802012-11-20 12:36:46 -08001619
Anwar Ghuloum46543222013-08-12 09:28:42 -07001620 timings_.NewSplit("RequestHeapTrim");
Ian Rogers1d54e732013-05-02 21:10:01 -07001621 heap->RequestHeapTrim();
Mathieu Chartier65db8802012-11-20 12:36:46 -08001622
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001623 // Update the cumulative statistics
Ian Rogers1d54e732013-05-02 21:10:01 -07001624 total_time_ns_ += GetDurationNs();
1625 total_paused_time_ns_ += std::accumulate(GetPauseTimes().begin(), GetPauseTimes().end(), 0,
1626 std::plus<uint64_t>());
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001627 total_freed_objects_ += GetFreedObjects() + GetFreedLargeObjects();
1628 total_freed_bytes_ += GetFreedBytes() + GetFreedLargeObjectBytes();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001629
1630 // Ensure that the mark stack is empty.
1631 CHECK(mark_stack_->IsEmpty());
1632
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001633 if (kCountScannedTypes) {
1634 VLOG(gc) << "MarkSweep scanned classes=" << class_count_ << " arrays=" << array_count_
1635 << " other=" << other_count_;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001636 }
1637
1638 if (kCountTasks) {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001639 VLOG(gc) << "Total number of work chunks allocated: " << work_chunks_created_;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001640 }
1641
1642 if (kMeasureOverhead) {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001643 VLOG(gc) << "Overhead time " << PrettyDuration(overhead_time_);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001644 }
1645
1646 if (kProfileLargeObjects) {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001647 VLOG(gc) << "Large objects tested " << large_object_test_ << " marked " << large_object_mark_;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001648 }
1649
1650 if (kCountClassesMarked) {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001651 VLOG(gc) << "Classes marked " << classes_marked_;
1652 }
1653
1654 if (kCountJavaLangRefs) {
1655 VLOG(gc) << "References scanned " << reference_count_;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001656 }
1657
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001658 // Update the cumulative loggers.
1659 cumulative_timings_.Start();
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001660 cumulative_timings_.AddLogger(timings_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001661 cumulative_timings_.End();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001662
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001663 // Clear all of the spaces' mark bitmaps.
Mathieu Chartier02e25112013-08-14 16:14:24 -07001664 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001665 if (space->GetGcRetentionPolicy() != space::kGcRetentionPolicyNeverCollect) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001666 space->GetMarkBitmap()->Clear();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001667 }
1668 }
Mathieu Chartier5301cd22012-05-31 12:11:36 -07001669 mark_stack_->Reset();
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001670
1671 // Reset the marked large objects.
Ian Rogers1d54e732013-05-02 21:10:01 -07001672 space::LargeObjectSpace* large_objects = GetHeap()->GetLargeObjectsSpace();
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001673 large_objects->GetMarkObjects()->Clear();
Carl Shapiro69759ea2011-07-21 18:13:35 -07001674}
1675
Ian Rogers1d54e732013-05-02 21:10:01 -07001676} // namespace collector
1677} // namespace gc
Carl Shapiro69759ea2011-07-21 18:13:35 -07001678} // namespace art