blob: c1ca55a5b724843c582affb4eb06c553d2f53ae5 [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
Elliott Hughes07ed66b2012-12-12 18:34:25 -080024#include "base/logging.h"
Elliott Hughes76160052012-12-12 16:31:20 -080025#include "base/macros.h"
Ian Rogers693ff612013-02-01 10:56:12 -080026#include "base/mutex-inl.h"
Sameer Abu Asala8439542013-02-14 16:06:42 -080027#include "base/timing_logger.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070028#include "gc/accounting/card_table-inl.h"
29#include "gc/accounting/heap_bitmap.h"
30#include "gc/accounting/space_bitmap-inl.h"
31#include "gc/heap.h"
32#include "gc/space/image_space.h"
33#include "gc/space/large_object_space.h"
34#include "gc/space/space-inl.h"
Elliott Hughes410c0c82011-09-01 17:58:25 -070035#include "indirect_reference_table.h"
36#include "intern_table.h"
Ian Rogers81d425b2012-09-27 16:03:43 -070037#include "jni_internal.h"
Elliott Hughesc33a32b2011-10-11 18:18:07 -070038#include "monitor.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080039#include "mark_sweep-inl.h"
40#include "mirror/class-inl.h"
41#include "mirror/class_loader.h"
42#include "mirror/dex_cache.h"
43#include "mirror/field.h"
44#include "mirror/field-inl.h"
45#include "mirror/object-inl.h"
46#include "mirror/object_array.h"
47#include "mirror/object_array-inl.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070048#include "runtime.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070049#include "thread-inl.h"
Mathieu Chartier6f1c9492012-10-15 12:08:41 -070050#include "thread_list.h"
Ian Rogers08254272012-10-23 17:49:23 -070051#include "verifier/method_verifier.h"
Carl Shapiro69759ea2011-07-21 18:13:35 -070052
Brian Carlstrom3e3d5912013-07-18 00:19:45 -070053using ::art::mirror::Class;
54using ::art::mirror::Field;
55using ::art::mirror::Object;
56using ::art::mirror::ObjectArray;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080057
Carl Shapiro69759ea2011-07-21 18:13:35 -070058namespace art {
Ian Rogers1d54e732013-05-02 21:10:01 -070059namespace gc {
60namespace collector {
Carl Shapiro69759ea2011-07-21 18:13:35 -070061
Mathieu Chartier02b6a782012-10-26 13:51:26 -070062// Performance options.
63static const bool kParallelMarkStack = true;
Brian Carlstrom7934ac22013-07-26 10:54:15 -070064static const bool kDisableFinger = true; // TODO: Fix, bit rotten.
Mathieu Chartier858f1c52012-10-17 17:45:55 -070065static const bool kUseMarkStackPrefetch = true;
66
Mathieu Chartier02b6a782012-10-26 13:51:26 -070067// Profiling and information flags.
68static const bool kCountClassesMarked = false;
69static const bool kProfileLargeObjects = false;
70static const bool kMeasureOverhead = false;
71static const bool kCountTasks = false;
Mathieu Chartierd22d5482012-11-06 17:14:12 -080072static const bool kCountJavaLangRefs = false;
Mathieu Chartier02b6a782012-10-26 13:51:26 -070073
Ian Rogers1d54e732013-05-02 21:10:01 -070074void MarkSweep::ImmuneSpace(space::ContinuousSpace* space) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -080075 // Bind live to mark bitmap if necessary.
76 if (space->GetLiveBitmap() != space->GetMarkBitmap()) {
77 BindLiveToMarkBitmap(space);
78 }
79
80 // Add the space to the immune region.
81 if (immune_begin_ == NULL) {
82 DCHECK(immune_end_ == NULL);
83 SetImmuneRange(reinterpret_cast<Object*>(space->Begin()),
84 reinterpret_cast<Object*>(space->End()));
85 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -070086 const std::vector<space::ContinuousSpace*>& spaces = GetHeap()->GetContinuousSpaces();
87 const space::ContinuousSpace* prev_space = NULL;
88 // Find out if the previous space is immune.
89 // TODO: C++0x
90 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
91 for (It it = spaces.begin(), end = spaces.end(); it != end; ++it) {
92 if (*it == space) {
93 break;
Mathieu Chartier2b82db42012-11-14 17:29:05 -080094 }
Ian Rogers1d54e732013-05-02 21:10:01 -070095 prev_space = *it;
96 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -080097
Ian Rogers1d54e732013-05-02 21:10:01 -070098 // If previous space was immune, then extend the immune region. Relies on continuous spaces
99 // being sorted by Heap::AddContinuousSpace.
100 if (prev_space != NULL &&
101 immune_begin_ <= reinterpret_cast<Object*>(prev_space->Begin()) &&
102 immune_end_ >= reinterpret_cast<Object*>(prev_space->End())) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800103 immune_begin_ = std::min(reinterpret_cast<Object*>(space->Begin()), immune_begin_);
104 immune_end_ = std::max(reinterpret_cast<Object*>(space->End()), immune_end_);
105 }
106 }
107}
108
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800109void MarkSweep::BindBitmaps() {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700110 timings_.StartSplit("BindBitmaps");
Ian Rogers1d54e732013-05-02 21:10:01 -0700111 const std::vector<space::ContinuousSpace*>& spaces = GetHeap()->GetContinuousSpaces();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800112 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
113
114 // Mark all of the spaces we never collect as immune.
Ian Rogers1d54e732013-05-02 21:10:01 -0700115 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
116 for (It it = spaces.begin(), end = spaces.end(); it != end; ++it) {
117 space::ContinuousSpace* space = *it;
118 if (space->GetGcRetentionPolicy() == space::kGcRetentionPolicyNeverCollect) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800119 ImmuneSpace(space);
120 }
121 }
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700122 timings_.EndSplit();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800123}
124
Ian Rogers1d54e732013-05-02 21:10:01 -0700125MarkSweep::MarkSweep(Heap* heap, bool is_concurrent, const std::string& name_prefix)
126 : GarbageCollector(heap,
127 name_prefix + (name_prefix.empty() ? "" : " ") +
128 (is_concurrent ? "concurrent mark sweep": "mark sweep")),
129 current_mark_bitmap_(NULL),
130 java_lang_Class_(NULL),
131 mark_stack_(NULL),
Ian Rogers1d54e732013-05-02 21:10:01 -0700132 immune_begin_(NULL),
133 immune_end_(NULL),
134 soft_reference_list_(NULL),
135 weak_reference_list_(NULL),
136 finalizer_reference_list_(NULL),
137 phantom_reference_list_(NULL),
138 cleared_reference_list_(NULL),
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800139 gc_barrier_(new Barrier(0)),
Ian Rogers62d6c772013-02-27 08:32:07 -0800140 large_object_lock_("mark sweep large object lock", kMarkSweepLargeObjectLock),
141 mark_stack_expand_lock_("mark sweep mark stack expand lock"),
Ian Rogers1bd4b4c2013-04-18 17:47:42 -0700142 is_concurrent_(is_concurrent),
Ian Rogers1d54e732013-05-02 21:10:01 -0700143 clear_soft_references_(false) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800144}
145
146void MarkSweep::InitializePhase() {
Ian Rogers1d54e732013-05-02 21:10:01 -0700147 timings_.Reset();
148 timings_.StartSplit("InitializePhase");
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800149 mark_stack_ = GetHeap()->mark_stack_.get();
150 DCHECK(mark_stack_ != NULL);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800151 SetImmuneRange(NULL, NULL);
152 soft_reference_list_ = NULL;
153 weak_reference_list_ = NULL;
154 finalizer_reference_list_ = NULL;
155 phantom_reference_list_ = NULL;
156 cleared_reference_list_ = NULL;
157 freed_bytes_ = 0;
158 freed_objects_ = 0;
159 class_count_ = 0;
160 array_count_ = 0;
161 other_count_ = 0;
162 large_object_test_ = 0;
163 large_object_mark_ = 0;
164 classes_marked_ = 0;
165 overhead_time_ = 0;
166 work_chunks_created_ = 0;
167 work_chunks_deleted_ = 0;
168 reference_count_ = 0;
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700169 java_lang_Class_ = Class::GetJavaLangClass();
170 CHECK(java_lang_Class_ != NULL);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700171 timings_.EndSplit();
172
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700173 FindDefaultMarkBitmap();
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700174
175// Do any pre GC verification.
176 timings_.StartSplit("PreGcVerification");
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800177 heap_->PreGcVerification(this);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700178 timings_.EndSplit();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800179}
180
181void MarkSweep::ProcessReferences(Thread* self) {
Mathieu Chartier8e56c7e2012-11-20 13:25:50 -0800182 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800183 ProcessReferences(&soft_reference_list_, clear_soft_references_, &weak_reference_list_,
184 &finalizer_reference_list_, &phantom_reference_list_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800185}
186
187bool MarkSweep::HandleDirtyObjectsPhase() {
188 Thread* self = Thread::Current();
Ian Rogers1d54e732013-05-02 21:10:01 -0700189 accounting::ObjectStack* allocation_stack = GetHeap()->allocation_stack_.get();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800190 Locks::mutator_lock_->AssertExclusiveHeld(self);
191
192 {
193 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
194
195 // Re-mark root set.
196 ReMarkRoots();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800197
198 // Scan dirty objects, this is only required if we are not doing concurrent GC.
Ian Rogers1d54e732013-05-02 21:10:01 -0700199 RecursiveMarkDirtyObjects(accounting::CardTable::kCardDirty);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800200 }
201
202 ProcessReferences(self);
203
204 // Only need to do this if we have the card mark verification on, and only during concurrent GC.
205 if (GetHeap()->verify_missing_card_marks_) {
206 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
207 // This second sweep makes sure that we don't have any objects in the live stack which point to
208 // freed objects. These cause problems since their references may be previously freed objects.
Ian Rogers1d54e732013-05-02 21:10:01 -0700209 SweepArray(allocation_stack, false);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800210 }
211 return true;
212}
213
214bool MarkSweep::IsConcurrent() const {
215 return is_concurrent_;
216}
217
218void MarkSweep::MarkingPhase() {
219 Heap* heap = GetHeap();
220 Thread* self = Thread::Current();
221
222 BindBitmaps();
223 FindDefaultMarkBitmap();
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700224
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800225 // Process dirty cards and add dirty cards to mod union tables.
226 heap->ProcessCards(timings_);
227
228 // Need to do this before the checkpoint since we don't want any threads to add references to
229 // the live stack during the recursive mark.
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700230 timings_.StartSplit("SwapStacks");
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800231 heap->SwapStacks();
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700232 timings_.EndSplit();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800233
234 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
235 if (Locks::mutator_lock_->IsExclusiveHeld(self)) {
236 // If we exclusively hold the mutator lock, all threads must be suspended.
237 MarkRoots();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800238 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -0700239 MarkRootsCheckpoint(self);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800240 MarkNonThreadRoots();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800241 }
242 MarkConcurrentRoots();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800243
244 heap->UpdateAndMarkModUnion(this, timings_, GetGcType());
245 MarkReachableObjects();
246}
247
248void MarkSweep::MarkReachableObjects() {
249 // Mark everything allocated since the last as GC live so that we can sweep concurrently,
250 // knowing that new allocations won't be marked as live.
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700251 timings_.StartSplit("MarkStackAsLive");
Ian Rogers1d54e732013-05-02 21:10:01 -0700252 accounting::ObjectStack* live_stack = heap_->GetLiveStack();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800253 heap_->MarkAllocStack(heap_->alloc_space_->GetLiveBitmap(),
254 heap_->large_object_space_->GetLiveObjects(),
255 live_stack);
256 live_stack->Reset();
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700257 timings_.EndSplit();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800258 // Recursively mark all the non-image bits set in the mark bitmap.
259 RecursiveMark();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800260}
261
262void MarkSweep::ReclaimPhase() {
263 Thread* self = Thread::Current();
264
265 if (!IsConcurrent()) {
Anwar Ghulouma9a50922013-08-09 21:34:20 -0700266 base::TimingLogger::ScopedSplit split("ProcessReferences", &timings_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800267 ProcessReferences(self);
Mathieu Chartier9642c962013-08-05 17:40:36 -0700268 } else {
Anwar Ghulouma9a50922013-08-09 21:34:20 -0700269 base::TimingLogger::ScopedSplit split("UnMarkAllocStack", &timings_);
Mathieu Chartier9642c962013-08-05 17:40:36 -0700270 accounting::ObjectStack* allocation_stack = GetHeap()->allocation_stack_.get();
271 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
272 // The allocation stack contains things allocated since the start of the GC. These may have been
273 // marked during this GC meaning they won't be eligible for reclaiming in the next sticky GC.
274 // Remove these objects from the mark bitmaps so that they will be eligible for sticky
275 // collection.
276 // There is a race here which is safely handled. Another thread such as the hprof could
277 // have flushed the alloc stack after we resumed the threads. This is safe however, since
278 // reseting the allocation stack zeros it out with madvise. This means that we will either
279 // read NULLs or attempt to unmark a newly allocated object which will not be marked in the
280 // first place.
281 mirror::Object** end = allocation_stack->End();
282 for (mirror::Object** it = allocation_stack->Begin(); it != end; ++it) {
283 Object* obj = *it;
284 if (obj != NULL) {
285 UnMarkObjectNonNull(obj);
286 }
287 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800288 }
289
290 // Before freeing anything, lets verify the heap.
291 if (kIsDebugBuild) {
292 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
293 VerifyImageRoots();
294 }
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700295 timings_.StartSplit("PreSweepingGcVerification");
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800296 heap_->PreSweepingGcVerification(this);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700297 timings_.EndSplit();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800298
299 {
300 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
301
302 // Reclaim unmarked objects.
Ian Rogers1d54e732013-05-02 21:10:01 -0700303 Sweep(false);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800304
305 // Swap the live and mark bitmaps for each space which we modified space. This is an
306 // optimization that enables us to not clear live bits inside of the sweep. Only swaps unbound
307 // bitmaps.
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700308 timings_.StartSplit("SwapBitmaps");
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800309 SwapBitmaps();
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700310 timings_.EndSplit();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800311
312 // Unbind the live and mark bitmaps.
313 UnBindBitmaps();
314 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800315}
316
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800317void MarkSweep::SetImmuneRange(Object* begin, Object* end) {
318 immune_begin_ = begin;
319 immune_end_ = end;
Carl Shapiro58551df2011-07-24 03:09:51 -0700320}
321
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700322void MarkSweep::FindDefaultMarkBitmap() {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700323 timings_.StartSplit("FindDefaultMarkBitmap");
Ian Rogers1d54e732013-05-02 21:10:01 -0700324 const std::vector<space::ContinuousSpace*>& spaces = GetHeap()->GetContinuousSpaces();
325 // TODO: C++0x
326 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
327 for (It it = spaces.begin(), end = spaces.end(); it != end; ++it) {
328 space::ContinuousSpace* space = *it;
329 if (space->GetGcRetentionPolicy() == space::kGcRetentionPolicyAlwaysCollect) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700330 current_mark_bitmap_ = (*it)->GetMarkBitmap();
331 CHECK(current_mark_bitmap_ != NULL);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700332 timings_.EndSplit();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700333 return;
334 }
335 }
336 GetHeap()->DumpSpaces();
337 LOG(FATAL) << "Could not find a default mark bitmap";
338}
339
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800340void MarkSweep::ExpandMarkStack() {
341 // Rare case, no need to have Thread::Current be a parameter.
342 MutexLock mu(Thread::Current(), mark_stack_expand_lock_);
343 if (UNLIKELY(mark_stack_->Size() < mark_stack_->Capacity())) {
344 // Someone else acquired the lock and expanded the mark stack before us.
345 return;
346 }
347 std::vector<Object*> temp;
348 temp.insert(temp.begin(), mark_stack_->Begin(), mark_stack_->End());
349 mark_stack_->Resize(mark_stack_->Capacity() * 2);
350 for (size_t i = 0; i < temp.size(); ++i) {
351 mark_stack_->PushBack(temp[i]);
352 }
353}
354
Mathieu Chartier9642c962013-08-05 17:40:36 -0700355inline void MarkSweep::MarkObjectNonNullParallel(const Object* obj) {
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800356 DCHECK(obj != NULL);
357 if (MarkObjectParallel(obj)) {
Mathieu Chartier184e3222013-08-03 14:02:57 -0700358 while (UNLIKELY(!mark_stack_->AtomicPushBack(const_cast<Object*>(obj)))) {
359 // Only reason a push can fail is that the mark stack is full.
360 ExpandMarkStack();
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800361 }
362 }
363}
364
Mathieu Chartier9642c962013-08-05 17:40:36 -0700365inline void MarkSweep::UnMarkObjectNonNull(const Object* obj) {
366 DCHECK(!IsImmune(obj));
367 // Try to take advantage of locality of references within a space, failing this find the space
368 // the hard way.
369 accounting::SpaceBitmap* object_bitmap = current_mark_bitmap_;
370 if (UNLIKELY(!object_bitmap->HasAddress(obj))) {
371 accounting::SpaceBitmap* new_bitmap = heap_->GetMarkBitmap()->GetContinuousSpaceBitmap(obj);
372 if (LIKELY(new_bitmap != NULL)) {
373 object_bitmap = new_bitmap;
374 } else {
375 MarkLargeObject(obj, false);
376 return;
377 }
378 }
379
380 DCHECK(object_bitmap->HasAddress(obj));
381 object_bitmap->Clear(obj);
382}
383
384inline void MarkSweep::MarkObjectNonNull(const Object* obj) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700385 DCHECK(obj != NULL);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700386
Mathieu Chartier9642c962013-08-05 17:40:36 -0700387 if (IsImmune(obj)) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700388 DCHECK(IsMarked(obj));
Carl Shapiro69759ea2011-07-21 18:13:35 -0700389 return;
390 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700391
392 // Try to take advantage of locality of references within a space, failing this find the space
393 // the hard way.
Ian Rogers1d54e732013-05-02 21:10:01 -0700394 accounting::SpaceBitmap* object_bitmap = current_mark_bitmap_;
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700395 if (UNLIKELY(!object_bitmap->HasAddress(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700396 accounting::SpaceBitmap* new_bitmap = heap_->GetMarkBitmap()->GetContinuousSpaceBitmap(obj);
397 if (LIKELY(new_bitmap != NULL)) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700398 object_bitmap = new_bitmap;
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700399 } else {
Mathieu Chartier9642c962013-08-05 17:40:36 -0700400 MarkLargeObject(obj, true);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700401 return;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700402 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700403 }
404
Carl Shapiro69759ea2011-07-21 18:13:35 -0700405 // This object was not previously marked.
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700406 if (!object_bitmap->Test(obj)) {
407 object_bitmap->Set(obj);
Mathieu Chartier184e3222013-08-03 14:02:57 -0700408 // Do we need to expand the mark stack?
409 if (UNLIKELY(mark_stack_->Size() >= mark_stack_->Capacity())) {
410 ExpandMarkStack();
Carl Shapiro69759ea2011-07-21 18:13:35 -0700411 }
Mathieu Chartier184e3222013-08-03 14:02:57 -0700412 // The object must be pushed on to the mark stack.
413 mark_stack_->PushBack(const_cast<Object*>(obj));
Carl Shapiro69759ea2011-07-21 18:13:35 -0700414 }
415}
416
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700417// Rare case, probably not worth inlining since it will increase instruction cache miss rate.
Mathieu Chartier9642c962013-08-05 17:40:36 -0700418bool MarkSweep::MarkLargeObject(const Object* obj, bool set) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700419 // TODO: support >1 discontinuous space.
420 space::LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
421 accounting::SpaceSetMap* large_objects = large_object_space->GetMarkObjects();
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700422 if (kProfileLargeObjects) {
423 ++large_object_test_;
424 }
425 if (UNLIKELY(!large_objects->Test(obj))) {
Mathieu Chartier4fcb8d32013-07-15 12:43:36 -0700426 if (!large_object_space->Contains(obj)) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700427 LOG(ERROR) << "Tried to mark " << obj << " not contained by any spaces";
428 LOG(ERROR) << "Attempting see if it's a bad root";
429 VerifyRoots();
430 LOG(FATAL) << "Can't mark bad root";
431 }
432 if (kProfileLargeObjects) {
433 ++large_object_mark_;
434 }
Mathieu Chartier9642c962013-08-05 17:40:36 -0700435 if (set) {
436 large_objects->Set(obj);
437 } else {
438 large_objects->Clear(obj);
439 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700440 return true;
441 }
442 return false;
443}
444
445inline bool MarkSweep::MarkObjectParallel(const Object* obj) {
446 DCHECK(obj != NULL);
447
Mathieu Chartier9642c962013-08-05 17:40:36 -0700448 if (IsImmune(obj)) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700449 DCHECK(IsMarked(obj));
450 return false;
451 }
452
453 // Try to take advantage of locality of references within a space, failing this find the space
454 // the hard way.
Ian Rogers1d54e732013-05-02 21:10:01 -0700455 accounting::SpaceBitmap* object_bitmap = current_mark_bitmap_;
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700456 if (UNLIKELY(!object_bitmap->HasAddress(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700457 accounting::SpaceBitmap* new_bitmap = heap_->GetMarkBitmap()->GetContinuousSpaceBitmap(obj);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700458 if (new_bitmap != NULL) {
459 object_bitmap = new_bitmap;
460 } else {
461 // TODO: Remove the Thread::Current here?
462 // TODO: Convert this to some kind of atomic marking?
463 MutexLock mu(Thread::Current(), large_object_lock_);
Mathieu Chartier9642c962013-08-05 17:40:36 -0700464 return MarkLargeObject(obj, true);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700465 }
466 }
467
468 // Return true if the object was not previously marked.
469 return !object_bitmap->AtomicTestAndSet(obj);
470}
471
Carl Shapiro69759ea2011-07-21 18:13:35 -0700472// Used to mark objects when recursing. Recursion is done by moving
473// the finger across the bitmaps in address order and marking child
474// objects. Any newly-marked objects whose addresses are lower than
475// the finger won't be visited by the bitmap scan, so those objects
476// need to be added to the mark stack.
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700477void MarkSweep::MarkObject(const Object* obj) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700478 if (obj != NULL) {
Mathieu Chartier9642c962013-08-05 17:40:36 -0700479 MarkObjectNonNull(obj);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700480 }
481}
482
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800483void MarkSweep::MarkRoot(const Object* obj) {
484 if (obj != NULL) {
Mathieu Chartier9642c962013-08-05 17:40:36 -0700485 MarkObjectNonNull(obj);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800486 }
487}
488
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800489void MarkSweep::MarkRootParallelCallback(const Object* root, void* arg) {
490 DCHECK(root != NULL);
491 DCHECK(arg != NULL);
492 MarkSweep* mark_sweep = reinterpret_cast<MarkSweep*>(arg);
Mathieu Chartier9642c962013-08-05 17:40:36 -0700493 mark_sweep->MarkObjectNonNullParallel(root);
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800494}
495
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700496void MarkSweep::MarkObjectCallback(const Object* root, void* arg) {
Brian Carlstrom1f870082011-08-23 16:02:11 -0700497 DCHECK(root != NULL);
498 DCHECK(arg != NULL);
499 MarkSweep* mark_sweep = reinterpret_cast<MarkSweep*>(arg);
Mathieu Chartier9642c962013-08-05 17:40:36 -0700500 mark_sweep->MarkObjectNonNull(root);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700501}
502
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700503void MarkSweep::ReMarkObjectVisitor(const Object* root, void* arg) {
504 DCHECK(root != NULL);
505 DCHECK(arg != NULL);
506 MarkSweep* mark_sweep = reinterpret_cast<MarkSweep*>(arg);
Mathieu Chartier9642c962013-08-05 17:40:36 -0700507 mark_sweep->MarkObjectNonNull(root);
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700508}
509
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700510void MarkSweep::VerifyRootCallback(const Object* root, void* arg, size_t vreg,
Ian Rogers40e3bac2012-11-20 00:09:14 -0800511 const StackVisitor* visitor) {
512 reinterpret_cast<MarkSweep*>(arg)->VerifyRoot(root, vreg, visitor);
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700513}
514
Ian Rogers40e3bac2012-11-20 00:09:14 -0800515void MarkSweep::VerifyRoot(const Object* root, size_t vreg, const StackVisitor* visitor) {
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700516 // See if the root is on any space bitmap.
Ian Rogers1d54e732013-05-02 21:10:01 -0700517 if (GetHeap()->GetLiveBitmap()->GetContinuousSpaceBitmap(root) == NULL) {
518 space::LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
Mathieu Chartier4202b742012-10-17 17:51:25 -0700519 if (!large_object_space->Contains(root)) {
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700520 LOG(ERROR) << "Found invalid root: " << root;
Ian Rogers40e3bac2012-11-20 00:09:14 -0800521 if (visitor != NULL) {
522 LOG(ERROR) << visitor->DescribeLocation() << " in VReg: " << vreg;
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700523 }
524 }
525 }
526}
527
528void MarkSweep::VerifyRoots() {
529 Runtime::Current()->GetThreadList()->VerifyRoots(VerifyRootCallback, this);
530}
531
Carl Shapiro69759ea2011-07-21 18:13:35 -0700532// Marks all objects in the root set.
533void MarkSweep::MarkRoots() {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700534 timings_.StartSplit("MarkRoots");
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700535 Runtime::Current()->VisitNonConcurrentRoots(MarkObjectCallback, this);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700536 timings_.EndSplit();
Mathieu Chartier9ebae1f2012-10-15 17:38:16 -0700537}
538
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700539void MarkSweep::MarkNonThreadRoots() {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700540 timings_.StartSplit("MarkNonThreadRoots");
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700541 Runtime::Current()->VisitNonThreadRoots(MarkObjectCallback, this);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700542 timings_.EndSplit();
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700543}
544
Mathieu Chartier9ebae1f2012-10-15 17:38:16 -0700545void MarkSweep::MarkConcurrentRoots() {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700546 timings_.StartSplit("MarkConcurrentRoots");
Ian Rogers1d54e732013-05-02 21:10:01 -0700547 // Visit all runtime roots and clear dirty flags.
548 Runtime::Current()->VisitConcurrentRoots(MarkObjectCallback, this, false, true);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700549 timings_.EndSplit();
Carl Shapiro69759ea2011-07-21 18:13:35 -0700550}
551
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700552class CheckObjectVisitor {
553 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -0700554 explicit CheckObjectVisitor(MarkSweep* const mark_sweep) : mark_sweep_(mark_sweep) {}
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700555
Brian Carlstromdf629502013-07-17 22:39:56 -0700556 void operator()(const Object* obj, const Object* ref, MemberOffset offset, bool is_static) const
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800557 NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800558 if (kDebugLocking) {
559 Locks::heap_bitmap_lock_->AssertSharedHeld(Thread::Current());
560 }
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700561 mark_sweep_->CheckReference(obj, ref, offset, is_static);
562 }
563
564 private:
565 MarkSweep* const mark_sweep_;
566};
567
568void MarkSweep::CheckObject(const Object* obj) {
569 DCHECK(obj != NULL);
570 CheckObjectVisitor visitor(this);
571 VisitObjectReferences(obj, visitor);
572}
573
574void MarkSweep::VerifyImageRootVisitor(Object* root, void* arg) {
575 DCHECK(root != NULL);
576 DCHECK(arg != NULL);
577 MarkSweep* mark_sweep = reinterpret_cast<MarkSweep*>(arg);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700578 DCHECK(mark_sweep->heap_->GetMarkBitmap()->Test(root));
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700579 mark_sweep->CheckObject(root);
580}
581
Ian Rogers1d54e732013-05-02 21:10:01 -0700582void MarkSweep::BindLiveToMarkBitmap(space::ContinuousSpace* space) {
583 CHECK(space->IsDlMallocSpace());
584 space::DlMallocSpace* alloc_space = space->AsDlMallocSpace();
585 accounting::SpaceBitmap* live_bitmap = space->GetLiveBitmap();
586 accounting::SpaceBitmap* mark_bitmap = alloc_space->mark_bitmap_.release();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700587 GetHeap()->GetMarkBitmap()->ReplaceBitmap(mark_bitmap, live_bitmap);
588 alloc_space->temp_bitmap_.reset(mark_bitmap);
589 alloc_space->mark_bitmap_.reset(live_bitmap);
590}
591
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700592class ScanObjectVisitor {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700593 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -0700594 explicit ScanObjectVisitor(MarkSweep* const mark_sweep) : mark_sweep_(mark_sweep) {}
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700595
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800596 // TODO: Fixme when anotatalysis works with visitors.
Brian Carlstromdf629502013-07-17 22:39:56 -0700597 void operator()(const Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800598 if (kDebugLocking) {
599 Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
600 Locks::heap_bitmap_lock_->AssertExclusiveHeld(Thread::Current());
601 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700602 mark_sweep_->ScanObject(obj);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700603 }
604
605 private:
606 MarkSweep* const mark_sweep_;
607};
608
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800609void MarkSweep::ScanGrayObjects(byte minimum_age) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700610 accounting::CardTable* card_table = GetHeap()->GetCardTable();
611 const std::vector<space::ContinuousSpace*>& spaces = GetHeap()->GetContinuousSpaces();
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700612 ScanObjectVisitor visitor(this);
Ian Rogers1d54e732013-05-02 21:10:01 -0700613 // TODO: C++0x
614 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
615 for (It it = spaces.begin(), space_end = spaces.end(); it != space_end; ++it) {
616 space::ContinuousSpace* space = *it;
617 switch (space->GetGcRetentionPolicy()) {
618 case space::kGcRetentionPolicyNeverCollect:
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700619 timings_.StartSplit("ScanGrayImageSpaceObjects");
Ian Rogers1d54e732013-05-02 21:10:01 -0700620 break;
621 case space::kGcRetentionPolicyFullCollect:
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700622 timings_.StartSplit("ScanGrayZygoteSpaceObjects");
Ian Rogers1d54e732013-05-02 21:10:01 -0700623 break;
624 case space::kGcRetentionPolicyAlwaysCollect:
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700625 timings_.StartSplit("ScanGrayAllocSpaceObjects");
Ian Rogers1d54e732013-05-02 21:10:01 -0700626 break;
627 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700628 byte* begin = space->Begin();
629 byte* end = space->End();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700630 // Image spaces are handled properly since live == marked for them.
Ian Rogers1d54e732013-05-02 21:10:01 -0700631 accounting::SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
Mathieu Chartier184e3222013-08-03 14:02:57 -0700632 card_table->Scan(mark_bitmap, begin, end, visitor, minimum_age);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700633 timings_.EndSplit();
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700634 }
635}
636
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700637class CheckBitmapVisitor {
638 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -0700639 explicit CheckBitmapVisitor(MarkSweep* mark_sweep) : mark_sweep_(mark_sweep) {}
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700640
Brian Carlstromdf629502013-07-17 22:39:56 -0700641 void operator()(const Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800642 if (kDebugLocking) {
643 Locks::heap_bitmap_lock_->AssertSharedHeld(Thread::Current());
644 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700645 DCHECK(obj != NULL);
646 mark_sweep_->CheckObject(obj);
647 }
648
649 private:
650 MarkSweep* mark_sweep_;
651};
652
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700653void MarkSweep::VerifyImageRoots() {
654 // Verify roots ensures that all the references inside the image space point
655 // objects which are either in the image space or marked objects in the alloc
656 // space
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700657 timings_.StartSplit("VerifyImageRoots");
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700658 CheckBitmapVisitor visitor(this);
Ian Rogers1d54e732013-05-02 21:10:01 -0700659 const std::vector<space::ContinuousSpace*>& spaces = GetHeap()->GetContinuousSpaces();
660 // TODO: C++0x
661 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
662 for (It it = spaces.begin(), end = spaces.end(); it != end; ++it) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700663 if ((*it)->IsImageSpace()) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700664 space::ImageSpace* space = (*it)->AsImageSpace();
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700665 uintptr_t begin = reinterpret_cast<uintptr_t>(space->Begin());
666 uintptr_t end = reinterpret_cast<uintptr_t>(space->End());
Ian Rogers1d54e732013-05-02 21:10:01 -0700667 accounting::SpaceBitmap* live_bitmap = space->GetLiveBitmap();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700668 DCHECK(live_bitmap != NULL);
Mathieu Chartier184e3222013-08-03 14:02:57 -0700669 live_bitmap->VisitMarkedRange(begin, end, visitor);
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700670 }
671 }
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700672 timings_.EndSplit();
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700673}
674
Carl Shapiro58551df2011-07-24 03:09:51 -0700675// Populates the mark stack based on the set of marked objects and
676// recursively marks until the mark stack is emptied.
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800677void MarkSweep::RecursiveMark() {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700678 base::TimingLogger::ScopedSplit("RecursiveMark", &timings_);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700679 // RecursiveMark will build the lists of known instances of the Reference classes.
680 // See DelayReferenceReferent for details.
681 CHECK(soft_reference_list_ == NULL);
682 CHECK(weak_reference_list_ == NULL);
683 CHECK(finalizer_reference_list_ == NULL);
684 CHECK(phantom_reference_list_ == NULL);
685 CHECK(cleared_reference_list_ == NULL);
686
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800687 const bool partial = GetGcType() == kGcTypePartial;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700688 ScanObjectVisitor scan_visitor(this);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800689 if (!kDisableFinger) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700690 const std::vector<space::ContinuousSpace*>& spaces = GetHeap()->GetContinuousSpaces();
691 // TODO: C++0x
692 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
693 for (It it = spaces.begin(), end = spaces.end(); it != end; ++it) {
694 space::ContinuousSpace* space = *it;
695 if ((space->GetGcRetentionPolicy() == space::kGcRetentionPolicyAlwaysCollect) ||
696 (!partial && space->GetGcRetentionPolicy() == space::kGcRetentionPolicyFullCollect)) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800697 current_mark_bitmap_ = space->GetMarkBitmap();
698 if (current_mark_bitmap_ == NULL) {
699 GetHeap()->DumpSpaces();
700 LOG(FATAL) << "invalid bitmap";
701 }
702 // This function does not handle heap end increasing, so we must use the space end.
703 uintptr_t begin = reinterpret_cast<uintptr_t>(space->Begin());
704 uintptr_t end = reinterpret_cast<uintptr_t>(space->End());
Mathieu Chartier184e3222013-08-03 14:02:57 -0700705 current_mark_bitmap_->VisitMarkedRange(begin, end, scan_visitor);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700706 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700707 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700708 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700709 ProcessMarkStack();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700710}
711
712bool MarkSweep::IsMarkedCallback(const Object* object, void* arg) {
713 return
714 reinterpret_cast<MarkSweep*>(arg)->IsMarked(object) ||
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700715 !reinterpret_cast<MarkSweep*>(arg)->GetHeap()->GetLiveBitmap()->Test(object);
716}
717
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800718void MarkSweep::RecursiveMarkDirtyObjects(byte minimum_age) {
719 ScanGrayObjects(minimum_age);
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700720 ProcessMarkStack();
721}
722
Carl Shapiro58551df2011-07-24 03:09:51 -0700723void MarkSweep::ReMarkRoots() {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700724 timings_.StartSplit("ReMarkRoots");
Ian Rogers1d54e732013-05-02 21:10:01 -0700725 Runtime::Current()->VisitRoots(ReMarkObjectVisitor, this, true, true);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700726 timings_.EndSplit();
Carl Shapiro69759ea2011-07-21 18:13:35 -0700727}
728
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800729void MarkSweep::SweepJniWeakGlobals(IsMarkedTester is_marked, void* arg) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700730 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
Ian Rogers50b35e22012-10-04 10:09:15 -0700731 MutexLock mu(Thread::Current(), vm->weak_globals_lock);
Elliott Hughes410c0c82011-09-01 17:58:25 -0700732 IndirectReferenceTable* table = &vm->weak_globals;
Mathieu Chartier654d3a22012-07-11 17:54:18 -0700733 typedef IndirectReferenceTable::iterator It; // TODO: C++0x auto
Elliott Hughes410c0c82011-09-01 17:58:25 -0700734 for (It it = table->begin(), end = table->end(); it != end; ++it) {
735 const Object** entry = *it;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700736 if (!is_marked(*entry, arg)) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700737 *entry = kClearedJniWeakGlobal;
738 }
739 }
740}
741
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700742struct ArrayMarkedCheck {
Ian Rogers1d54e732013-05-02 21:10:01 -0700743 accounting::ObjectStack* live_stack;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700744 MarkSweep* mark_sweep;
745};
746
747// Either marked or not live.
748bool MarkSweep::IsMarkedArrayCallback(const Object* object, void* arg) {
749 ArrayMarkedCheck* array_check = reinterpret_cast<ArrayMarkedCheck*>(arg);
750 if (array_check->mark_sweep->IsMarked(object)) {
751 return true;
752 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700753 accounting::ObjectStack* live_stack = array_check->live_stack;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700754 return std::find(live_stack->Begin(), live_stack->End(), object) == live_stack->End();
755}
756
Ian Rogers1d54e732013-05-02 21:10:01 -0700757void MarkSweep::SweepSystemWeaksArray(accounting::ObjectStack* allocations) {
Mathieu Chartier46a23632012-08-07 18:44:40 -0700758 Runtime* runtime = Runtime::Current();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700759 // The callbacks check
760 // !is_marked where is_marked is the callback but we want
761 // !IsMarked && IsLive
762 // So compute !(!IsMarked && IsLive) which is equal to (IsMarked || !IsLive).
763 // Or for swapped (IsLive || !IsMarked).
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700764
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700765 timings_.StartSplit("SweepSystemWeaksArray");
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700766 ArrayMarkedCheck visitor;
767 visitor.live_stack = allocations;
768 visitor.mark_sweep = this;
769 runtime->GetInternTable()->SweepInternTableWeaks(IsMarkedArrayCallback, &visitor);
770 runtime->GetMonitorList()->SweepMonitorList(IsMarkedArrayCallback, &visitor);
771 SweepJniWeakGlobals(IsMarkedArrayCallback, &visitor);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700772 timings_.EndSplit();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700773}
774
775void MarkSweep::SweepSystemWeaks() {
776 Runtime* runtime = Runtime::Current();
777 // The callbacks check
778 // !is_marked where is_marked is the callback but we want
779 // !IsMarked && IsLive
780 // So compute !(!IsMarked && IsLive) which is equal to (IsMarked || !IsLive).
781 // Or for swapped (IsLive || !IsMarked).
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700782 timings_.StartSplit("SweepSystemWeaks");
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700783 runtime->GetInternTable()->SweepInternTableWeaks(IsMarkedCallback, this);
784 runtime->GetMonitorList()->SweepMonitorList(IsMarkedCallback, this);
785 SweepJniWeakGlobals(IsMarkedCallback, this);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700786 timings_.EndSplit();
Carl Shapiro58551df2011-07-24 03:09:51 -0700787}
788
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700789bool MarkSweep::VerifyIsLiveCallback(const Object* obj, void* arg) {
790 reinterpret_cast<MarkSweep*>(arg)->VerifyIsLive(obj);
791 // We don't actually want to sweep the object, so lets return "marked"
792 return true;
793}
794
795void MarkSweep::VerifyIsLive(const Object* obj) {
796 Heap* heap = GetHeap();
797 if (!heap->GetLiveBitmap()->Test(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700798 space::LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700799 if (!large_object_space->GetLiveObjects()->Test(obj)) {
800 if (std::find(heap->allocation_stack_->Begin(), heap->allocation_stack_->End(), obj) ==
801 heap->allocation_stack_->End()) {
802 // Object not found!
803 heap->DumpSpaces();
804 LOG(FATAL) << "Found dead object " << obj;
805 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700806 }
807 }
808}
809
810void MarkSweep::VerifySystemWeaks() {
811 Runtime* runtime = Runtime::Current();
812 // Verify system weaks, uses a special IsMarked callback which always returns true.
813 runtime->GetInternTable()->SweepInternTableWeaks(VerifyIsLiveCallback, this);
814 runtime->GetMonitorList()->SweepMonitorList(VerifyIsLiveCallback, this);
815
816 JavaVMExt* vm = runtime->GetJavaVM();
Ian Rogers50b35e22012-10-04 10:09:15 -0700817 MutexLock mu(Thread::Current(), vm->weak_globals_lock);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700818 IndirectReferenceTable* table = &vm->weak_globals;
819 typedef IndirectReferenceTable::iterator It; // TODO: C++0x auto
820 for (It it = table->begin(), end = table->end(); it != end; ++it) {
821 const Object** entry = *it;
822 VerifyIsLive(*entry);
823 }
824}
825
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800826struct SweepCallbackContext {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700827 MarkSweep* mark_sweep;
Ian Rogers1d54e732013-05-02 21:10:01 -0700828 space::AllocSpace* space;
Ian Rogers50b35e22012-10-04 10:09:15 -0700829 Thread* self;
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800830};
831
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700832class CheckpointMarkThreadRoots : public Closure {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700833 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -0700834 explicit CheckpointMarkThreadRoots(MarkSweep* mark_sweep) : mark_sweep_(mark_sweep) {}
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700835
836 virtual void Run(Thread* thread) NO_THREAD_SAFETY_ANALYSIS {
837 // Note: self is not necessarily equal to thread since thread may be suspended.
838 Thread* self = Thread::Current();
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800839 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
840 << thread->GetState() << " thread " << thread << " self " << self;
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800841 thread->VisitRoots(MarkSweep::MarkRootParallelCallback, mark_sweep_);
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700842 mark_sweep_->GetBarrier().Pass(self);
843 }
844
845 private:
846 MarkSweep* mark_sweep_;
847};
848
Ian Rogers1d54e732013-05-02 21:10:01 -0700849void MarkSweep::MarkRootsCheckpoint(Thread* self) {
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800850 CheckpointMarkThreadRoots check_point(this);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700851 timings_.StartSplit("MarkRootsCheckpoint");
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700852 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Ian Rogers1d54e732013-05-02 21:10:01 -0700853 // Request the check point is run on all threads returning a count of the threads that must
854 // run through the barrier including self.
855 size_t barrier_count = thread_list->RunCheckpoint(&check_point);
856 // Release locks then wait for all mutator threads to pass the barrier.
857 // TODO: optimize to not release locks when there are no threads to wait for.
858 Locks::heap_bitmap_lock_->ExclusiveUnlock(self);
859 Locks::mutator_lock_->SharedUnlock(self);
860 ThreadState old_state = self->SetState(kWaitingForCheckPointsToRun);
861 CHECK_EQ(old_state, kWaitingPerformingGc);
862 gc_barrier_->Increment(self, barrier_count);
863 self->SetState(kWaitingPerformingGc);
864 Locks::mutator_lock_->SharedLock(self);
865 Locks::heap_bitmap_lock_->ExclusiveLock(self);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700866 timings_.EndSplit();
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700867}
868
Ian Rogers30fab402012-01-23 15:43:46 -0800869void MarkSweep::SweepCallback(size_t num_ptrs, Object** ptrs, void* arg) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800870 SweepCallbackContext* context = static_cast<SweepCallbackContext*>(arg);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700871 MarkSweep* mark_sweep = context->mark_sweep;
872 Heap* heap = mark_sweep->GetHeap();
Ian Rogers1d54e732013-05-02 21:10:01 -0700873 space::AllocSpace* space = context->space;
Ian Rogers50b35e22012-10-04 10:09:15 -0700874 Thread* self = context->self;
875 Locks::heap_bitmap_lock_->AssertExclusiveHeld(self);
Ian Rogers5d76c432011-10-31 21:42:49 -0700876 // Use a bulk free, that merges consecutive objects before freeing or free per object?
877 // Documentation suggests better free performance with merging, but this may be at the expensive
878 // of allocation.
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700879 size_t freed_objects = num_ptrs;
880 // AllocSpace::FreeList clears the value in ptrs, so perform after clearing the live bit
881 size_t freed_bytes = space->FreeList(self, num_ptrs, ptrs);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700882 heap->RecordFree(freed_objects, freed_bytes);
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -0700883 mark_sweep->freed_objects_.fetch_add(freed_objects);
884 mark_sweep->freed_bytes_.fetch_add(freed_bytes);
Carl Shapiro58551df2011-07-24 03:09:51 -0700885}
886
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700887void MarkSweep::ZygoteSweepCallback(size_t num_ptrs, Object** ptrs, void* arg) {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700888 SweepCallbackContext* context = static_cast<SweepCallbackContext*>(arg);
Ian Rogers50b35e22012-10-04 10:09:15 -0700889 Locks::heap_bitmap_lock_->AssertExclusiveHeld(context->self);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700890 Heap* heap = context->mark_sweep->GetHeap();
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700891 // We don't free any actual memory to avoid dirtying the shared zygote pages.
892 for (size_t i = 0; i < num_ptrs; ++i) {
893 Object* obj = static_cast<Object*>(ptrs[i]);
894 heap->GetLiveBitmap()->Clear(obj);
895 heap->GetCardTable()->MarkCard(obj);
896 }
897}
898
Ian Rogers1d54e732013-05-02 21:10:01 -0700899void MarkSweep::SweepArray(accounting::ObjectStack* allocations, bool swap_bitmaps) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700900 size_t freed_bytes = 0;
Ian Rogers1d54e732013-05-02 21:10:01 -0700901 space::DlMallocSpace* space = heap_->GetAllocSpace();
Elliott Hughes2da50362011-10-10 16:57:08 -0700902
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700903 // If we don't swap bitmaps then newly allocated Weaks go into the live bitmap but not mark
904 // bitmap, resulting in occasional frees of Weaks which are still in use.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700905 SweepSystemWeaksArray(allocations);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700906
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700907 timings_.StartSplit("Process allocation stack");
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700908 // Newly allocated objects MUST be in the alloc space and those are the only objects which we are
909 // going to free.
Ian Rogers1d54e732013-05-02 21:10:01 -0700910 accounting::SpaceBitmap* live_bitmap = space->GetLiveBitmap();
911 accounting::SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
912 space::LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
913 accounting::SpaceSetMap* large_live_objects = large_object_space->GetLiveObjects();
914 accounting::SpaceSetMap* large_mark_objects = large_object_space->GetMarkObjects();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700915 if (swap_bitmaps) {
916 std::swap(live_bitmap, mark_bitmap);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700917 std::swap(large_live_objects, large_mark_objects);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700918 }
919
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700920 size_t freed_large_objects = 0;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700921 size_t count = allocations->Size();
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700922 Object** objects = const_cast<Object**>(allocations->Begin());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700923 Object** out = objects;
924
925 // Empty the allocation stack.
Ian Rogers50b35e22012-10-04 10:09:15 -0700926 Thread* self = Thread::Current();
Brian Carlstrom02c8cc62013-07-18 15:54:44 -0700927 for (size_t i = 0; i < count; ++i) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700928 Object* obj = objects[i];
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700929 // There should only be objects in the AllocSpace/LargeObjectSpace in the allocation stack.
930 if (LIKELY(mark_bitmap->HasAddress(obj))) {
931 if (!mark_bitmap->Test(obj)) {
932 // Don't bother un-marking since we clear the mark bitmap anyways.
933 *(out++) = obj;
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700934 }
935 } else if (!large_mark_objects->Test(obj)) {
936 ++freed_large_objects;
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700937 freed_bytes += large_object_space->Free(self, obj);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700938 }
939 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700940 CHECK_EQ(count, allocations->Size());
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700941 timings_.EndSplit();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700942
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700943 timings_.StartSplit("FreeList");
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700944 size_t freed_objects = out - objects;
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700945 freed_bytes += space->FreeList(self, freed_objects, objects);
Mathieu Chartier40e978b2012-09-07 11:38:36 -0700946 VLOG(heap) << "Freed " << freed_objects << "/" << count
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700947 << " objects with size " << PrettySize(freed_bytes);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700948 heap_->RecordFree(freed_objects + freed_large_objects, freed_bytes);
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -0700949 freed_objects_.fetch_add(freed_objects);
950 freed_bytes_.fetch_add(freed_bytes);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700951 timings_.EndSplit();
Ian Rogers1d54e732013-05-02 21:10:01 -0700952
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700953 timings_.StartSplit("ResetStack");
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700954 allocations->Reset();
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700955 timings_.EndSplit();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700956}
957
Ian Rogers1d54e732013-05-02 21:10:01 -0700958void MarkSweep::Sweep(bool swap_bitmaps) {
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700959 DCHECK(mark_stack_->IsEmpty());
960
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700961 // If we don't swap bitmaps then newly allocated Weaks go into the live bitmap but not mark
962 // bitmap, resulting in occasional frees of Weaks which are still in use.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700963 SweepSystemWeaks();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700964
Ian Rogers1d54e732013-05-02 21:10:01 -0700965 const bool partial = (GetGcType() == kGcTypePartial);
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800966 SweepCallbackContext scc;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700967 scc.mark_sweep = this;
Ian Rogers50b35e22012-10-04 10:09:15 -0700968 scc.self = Thread::Current();
Ian Rogers1d54e732013-05-02 21:10:01 -0700969 const std::vector<space::ContinuousSpace*>& spaces = GetHeap()->GetContinuousSpaces();
970 // TODO: C++0x
971 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
972 for (It it = spaces.begin(), end = spaces.end(); it != end; ++it) {
973 space::ContinuousSpace* space = *it;
974 // We always sweep always collect spaces.
975 bool sweep_space = (space->GetGcRetentionPolicy() == space::kGcRetentionPolicyAlwaysCollect);
976 if (!partial && !sweep_space) {
977 // We sweep full collect spaces when the GC isn't a partial GC (ie its full).
978 sweep_space = (space->GetGcRetentionPolicy() == space::kGcRetentionPolicyFullCollect);
979 }
980 if (sweep_space) {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700981 uintptr_t begin = reinterpret_cast<uintptr_t>(space->Begin());
982 uintptr_t end = reinterpret_cast<uintptr_t>(space->End());
Ian Rogers1d54e732013-05-02 21:10:01 -0700983 scc.space = space->AsDlMallocSpace();
984 accounting::SpaceBitmap* live_bitmap = space->GetLiveBitmap();
985 accounting::SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700986 if (swap_bitmaps) {
987 std::swap(live_bitmap, mark_bitmap);
988 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700989 if (!space->IsZygoteSpace()) {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700990 timings_.StartSplit("SweepAllocSpace");
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700991 // Bitmaps are pre-swapped for optimization which enables sweeping with the heap unlocked.
Ian Rogers1d54e732013-05-02 21:10:01 -0700992 accounting::SpaceBitmap::SweepWalk(*live_bitmap, *mark_bitmap, begin, end,
993 &SweepCallback, reinterpret_cast<void*>(&scc));
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700994 timings_.EndSplit();
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700995 } else {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700996 timings_.StartSplit("SweepZygote");
Ian Rogers1d54e732013-05-02 21:10:01 -0700997 // Zygote sweep takes care of dirtying cards and clearing live bits, does not free actual
998 // memory.
999 accounting::SpaceBitmap::SweepWalk(*live_bitmap, *mark_bitmap, begin, end,
1000 &ZygoteSweepCallback, reinterpret_cast<void*>(&scc));
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001001 timings_.EndSplit();
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001002 }
Carl Shapiro58551df2011-07-24 03:09:51 -07001003 }
1004 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001005
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001006 timings_.StartSplit("SweepLargeObjects");
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001007 SweepLargeObjects(swap_bitmaps);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001008 timings_.EndSplit();
Carl Shapiro58551df2011-07-24 03:09:51 -07001009}
1010
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001011void MarkSweep::SweepLargeObjects(bool swap_bitmaps) {
1012 // Sweep large objects
Ian Rogers1d54e732013-05-02 21:10:01 -07001013 space::LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
1014 accounting::SpaceSetMap* large_live_objects = large_object_space->GetLiveObjects();
1015 accounting::SpaceSetMap* large_mark_objects = large_object_space->GetMarkObjects();
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001016 if (swap_bitmaps) {
1017 std::swap(large_live_objects, large_mark_objects);
1018 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001019 accounting::SpaceSetMap::Objects& live_objects = large_live_objects->GetObjects();
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001020 // O(n*log(n)) but hopefully there are not too many large objects.
1021 size_t freed_objects = 0;
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001022 size_t freed_bytes = 0;
Ian Rogers50b35e22012-10-04 10:09:15 -07001023 Thread* self = Thread::Current();
Ian Rogers1d54e732013-05-02 21:10:01 -07001024 // TODO: C++0x
1025 typedef accounting::SpaceSetMap::Objects::iterator It;
1026 for (It it = live_objects.begin(), end = live_objects.end(); it != end; ++it) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001027 if (!large_mark_objects->Test(*it)) {
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -07001028 freed_bytes += large_object_space->Free(self, const_cast<Object*>(*it));
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001029 ++freed_objects;
1030 }
1031 }
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -07001032 freed_objects_.fetch_add(freed_objects);
1033 freed_bytes_.fetch_add(freed_bytes);
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001034 GetHeap()->RecordFree(freed_objects, freed_bytes);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001035}
1036
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001037void MarkSweep::CheckReference(const Object* obj, const Object* ref, MemberOffset offset, bool is_static) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001038 const std::vector<space::ContinuousSpace*>& spaces = GetHeap()->GetContinuousSpaces();
1039 // TODO: C++0x
1040 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
1041 for (It it = spaces.begin(), end = spaces.end(); it != end; ++it) {
1042 space::ContinuousSpace* space = *it;
1043 if (space->IsDlMallocSpace() && space->Contains(ref)) {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001044 DCHECK(IsMarked(obj));
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001045
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001046 bool is_marked = IsMarked(ref);
1047 if (!is_marked) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001048 LOG(INFO) << *space;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001049 LOG(WARNING) << (is_static ? "Static ref'" : "Instance ref'") << PrettyTypeOf(ref)
1050 << "' (" << reinterpret_cast<const void*>(ref) << ") in '" << PrettyTypeOf(obj)
1051 << "' (" << reinterpret_cast<const void*>(obj) << ") at offset "
1052 << reinterpret_cast<void*>(offset.Int32Value()) << " wasn't marked";
Mathieu Chartier262e5ff2012-06-01 17:35:38 -07001053
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001054 const Class* klass = is_static ? obj->AsClass() : obj->GetClass();
1055 DCHECK(klass != NULL);
1056 const ObjectArray<Field>* fields = is_static ? klass->GetSFields() : klass->GetIFields();
1057 DCHECK(fields != NULL);
1058 bool found = false;
1059 for (int32_t i = 0; i < fields->GetLength(); ++i) {
1060 const Field* cur = fields->Get(i);
1061 if (cur->GetOffset().Int32Value() == offset.Int32Value()) {
1062 LOG(WARNING) << "Field referencing the alloc space was " << PrettyField(cur);
1063 found = true;
1064 break;
1065 }
1066 }
1067 if (!found) {
1068 LOG(WARNING) << "Could not find field in object alloc space with offset " << offset.Int32Value();
1069 }
Mathieu Chartier262e5ff2012-06-01 17:35:38 -07001070
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001071 bool obj_marked = heap_->GetCardTable()->IsDirty(obj);
1072 if (!obj_marked) {
1073 LOG(WARNING) << "Object '" << PrettyTypeOf(obj) << "' "
1074 << "(" << reinterpret_cast<const void*>(obj) << ") contains references to "
1075 << "the alloc space, but wasn't card marked";
Mathieu Chartier262e5ff2012-06-01 17:35:38 -07001076 }
1077 }
Ian Rogers5d76c432011-10-31 21:42:49 -07001078 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001079 break;
Ian Rogers5d76c432011-10-31 21:42:49 -07001080 }
1081}
1082
Carl Shapiro69759ea2011-07-21 18:13:35 -07001083// Process the "referent" field in a java.lang.ref.Reference. If the
1084// referent has not yet been marked, put it on the appropriate list in
1085// the gcHeap for later processing.
1086void MarkSweep::DelayReferenceReferent(Object* obj) {
1087 DCHECK(obj != NULL);
Brian Carlstrom1f870082011-08-23 16:02:11 -07001088 Class* klass = obj->GetClass();
1089 DCHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001090 DCHECK(klass->IsReferenceClass());
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001091 Object* pending = obj->GetFieldObject<Object*>(heap_->GetReferencePendingNextOffset(), false);
1092 Object* referent = heap_->GetReferenceReferent(obj);
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001093 if (kCountJavaLangRefs) {
1094 ++reference_count_;
1095 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001096 if (pending == NULL && referent != NULL && !IsMarked(referent)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07001097 Object** list = NULL;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001098 if (klass->IsSoftReferenceClass()) {
Carl Shapiro69759ea2011-07-21 18:13:35 -07001099 list = &soft_reference_list_;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001100 } else if (klass->IsWeakReferenceClass()) {
Carl Shapiro69759ea2011-07-21 18:13:35 -07001101 list = &weak_reference_list_;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001102 } else if (klass->IsFinalizerReferenceClass()) {
Carl Shapiro69759ea2011-07-21 18:13:35 -07001103 list = &finalizer_reference_list_;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001104 } else if (klass->IsPhantomReferenceClass()) {
Carl Shapiro69759ea2011-07-21 18:13:35 -07001105 list = &phantom_reference_list_;
1106 }
Brian Carlstrom0796af02011-10-12 14:31:45 -07001107 DCHECK(list != NULL) << PrettyClass(klass) << " " << std::hex << klass->GetAccessFlags();
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001108 // TODO: One lock per list?
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001109 heap_->EnqueuePendingReference(obj, list);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001110 }
1111}
1112
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001113void MarkSweep::ScanRoot(const Object* obj) {
1114 ScanObject(obj);
1115}
1116
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001117class MarkObjectVisitor {
1118 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001119 explicit MarkObjectVisitor(MarkSweep* const mark_sweep) : mark_sweep_(mark_sweep) {}
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001120
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001121 // TODO: Fixme when anotatalysis works with visitors.
Brian Carlstromdf629502013-07-17 22:39:56 -07001122 void operator()(const Object* /* obj */, const Object* ref, const MemberOffset& /* offset */,
1123 bool /* is_static */) const
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001124 NO_THREAD_SAFETY_ANALYSIS {
1125 if (kDebugLocking) {
1126 Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
1127 Locks::heap_bitmap_lock_->AssertExclusiveHeld(Thread::Current());
1128 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001129 mark_sweep_->MarkObject(ref);
1130 }
1131
1132 private:
1133 MarkSweep* const mark_sweep_;
1134};
1135
Carl Shapiro69759ea2011-07-21 18:13:35 -07001136// Scans an object reference. Determines the type of the reference
1137// and dispatches to a specialized scanning routine.
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001138void MarkSweep::ScanObject(const Object* obj) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001139 MarkObjectVisitor visitor(this);
1140 ScanObjectVisit(obj, visitor);
1141}
1142
1143class MarkStackChunk : public Task {
Ian Rogers1d54e732013-05-02 21:10:01 -07001144 public:
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001145 MarkStackChunk(ThreadPool* thread_pool, MarkSweep* mark_sweep, Object** begin, Object** end)
1146 : mark_sweep_(mark_sweep),
1147 thread_pool_(thread_pool),
1148 index_(0),
1149 length_(0),
1150 output_(NULL) {
1151 length_ = end - begin;
1152 if (begin != end) {
1153 // Cost not significant since we only do this for the initial set of mark stack chunks.
1154 memcpy(data_, begin, length_ * sizeof(*begin));
1155 }
1156 if (kCountTasks) {
1157 ++mark_sweep_->work_chunks_created_;
1158 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001159 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001160
1161 ~MarkStackChunk() {
1162 DCHECK(output_ == NULL || output_->length_ == 0);
1163 DCHECK_GE(index_, length_);
1164 delete output_;
1165 if (kCountTasks) {
1166 ++mark_sweep_->work_chunks_deleted_;
1167 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001168 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001169
1170 MarkSweep* const mark_sweep_;
1171 ThreadPool* const thread_pool_;
1172 static const size_t max_size = 1 * KB;
1173 // Index of which object we are scanning. Only needs to be atomic if we are doing work stealing.
1174 size_t index_;
1175 // Input / output mark stack. We add newly marked references to data_ until length reaches
1176 // max_size. This is an optimization so that less tasks are created.
1177 // TODO: Investigate using a bounded buffer FIFO.
1178 Object* data_[max_size];
1179 // How many elements in data_ we need to scan.
1180 size_t length_;
1181 // Output block, newly marked references get added to the ouput block so that another thread can
1182 // scan them.
1183 MarkStackChunk* output_;
1184
1185 class MarkObjectParallelVisitor {
1186 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001187 explicit MarkObjectParallelVisitor(MarkStackChunk* chunk_task) : chunk_task_(chunk_task) {}
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001188
Brian Carlstromdf629502013-07-17 22:39:56 -07001189 void operator()(const Object* /* obj */, const Object* ref,
1190 const MemberOffset& /* offset */, bool /* is_static */) const {
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001191 if (ref != NULL && chunk_task_->mark_sweep_->MarkObjectParallel(ref)) {
1192 chunk_task_->MarkStackPush(ref);
1193 }
1194 }
1195
1196 private:
1197 MarkStackChunk* const chunk_task_;
1198 };
1199
1200 // Push an object into the block.
1201 // Don't need to use atomic ++ since we only one thread is writing to an output block at any
1202 // given time.
1203 void Push(Object* obj) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001204 CHECK(obj != NULL);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001205 data_[length_++] = obj;
1206 }
1207
1208 void MarkStackPush(const Object* obj) {
1209 if (static_cast<size_t>(length_) < max_size) {
1210 Push(const_cast<Object*>(obj));
1211 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -07001212 // Internal (thread-local) buffer is full, push to a new buffer instead.
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001213 if (UNLIKELY(output_ == NULL)) {
1214 AllocateOutputChunk();
1215 } else if (UNLIKELY(static_cast<size_t>(output_->length_) == max_size)) {
1216 // Output block is full, queue it up for processing and obtain a new block.
1217 EnqueueOutput();
1218 AllocateOutputChunk();
1219 }
1220 output_->Push(const_cast<Object*>(obj));
1221 }
1222 }
1223
1224 void ScanObject(Object* obj) {
1225 mark_sweep_->ScanObjectVisit(obj, MarkObjectParallelVisitor(this));
1226 }
1227
1228 void EnqueueOutput() {
1229 if (output_ != NULL) {
1230 uint64_t start = 0;
1231 if (kMeasureOverhead) {
1232 start = NanoTime();
1233 }
1234 thread_pool_->AddTask(Thread::Current(), output_);
1235 output_ = NULL;
1236 if (kMeasureOverhead) {
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -07001237 mark_sweep_->overhead_time_.fetch_add(NanoTime() - start);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001238 }
1239 }
1240 }
1241
1242 void AllocateOutputChunk() {
1243 uint64_t start = 0;
1244 if (kMeasureOverhead) {
1245 start = NanoTime();
1246 }
1247 output_ = new MarkStackChunk(thread_pool_, mark_sweep_, NULL, NULL);
1248 if (kMeasureOverhead) {
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -07001249 mark_sweep_->overhead_time_.fetch_add(NanoTime() - start);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001250 }
1251 }
1252
1253 void Finalize() {
1254 EnqueueOutput();
1255 delete this;
1256 }
1257
1258 // Scans all of the objects
1259 virtual void Run(Thread* self) {
Brian Carlstromd74e41b2013-03-24 23:47:01 -07001260 size_t index;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001261 while ((index = index_++) < length_) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001262 if (kUseMarkStackPrefetch) {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001263 static const size_t prefetch_look_ahead = 1;
1264 __builtin_prefetch(data_[std::min(index + prefetch_look_ahead, length_ - 1)]);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001265 }
1266 Object* obj = data_[index];
1267 DCHECK(obj != NULL);
1268 ScanObject(obj);
1269 }
1270 }
1271};
1272
1273void MarkSweep::ProcessMarkStackParallel() {
1274 CHECK(kDisableFinger) << "parallel mark stack processing cannot work when finger is enabled";
1275 Thread* self = Thread::Current();
1276 ThreadPool* thread_pool = GetHeap()->GetThreadPool();
1277 // Split the current mark stack up into work tasks.
1278 const size_t num_threads = thread_pool->GetThreadCount();
1279 const size_t stack_size = mark_stack_->Size();
1280 const size_t chunk_size =
1281 std::min((stack_size + num_threads - 1) / num_threads,
1282 static_cast<size_t>(MarkStackChunk::max_size));
1283 size_t index = 0;
1284 for (size_t i = 0; i < num_threads || index < stack_size; ++i) {
1285 Object** begin = &mark_stack_->Begin()[std::min(stack_size, index)];
1286 Object** end = &mark_stack_->Begin()[std::min(stack_size, index + chunk_size)];
1287 index += chunk_size;
1288 thread_pool->AddTask(self, new MarkStackChunk(thread_pool, this, begin, end));
1289 }
1290 thread_pool->StartWorkers(self);
Ian Rogers1d54e732013-05-02 21:10:01 -07001291 thread_pool->Wait(self, true, true);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001292 mark_stack_->Reset();
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001293 // LOG(INFO) << "Idle wait time " << PrettyDuration(thread_pool->GetWaitTime());
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001294 CHECK_EQ(work_chunks_created_, work_chunks_deleted_) << " some of the work chunks were leaked";
Carl Shapiro69759ea2011-07-21 18:13:35 -07001295}
1296
Ian Rogers5d76c432011-10-31 21:42:49 -07001297// Scan anything that's on the mark stack.
Carl Shapiro69759ea2011-07-21 18:13:35 -07001298void MarkSweep::ProcessMarkStack() {
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001299 ThreadPool* thread_pool = GetHeap()->GetThreadPool();
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001300 timings_.StartSplit("ProcessMarkStack");
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001301 if (kParallelMarkStack && thread_pool != NULL && thread_pool->GetThreadCount() > 0) {
1302 ProcessMarkStackParallel();
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001303 timings_.EndSplit();
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001304 return;
1305 }
1306
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001307 if (kUseMarkStackPrefetch) {
1308 const size_t fifo_size = 4;
1309 const size_t fifo_mask = fifo_size - 1;
1310 const Object* fifo[fifo_size];
Brian Carlstrom02c8cc62013-07-18 15:54:44 -07001311 for (size_t i = 0; i < fifo_size; ++i) {
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001312 fifo[i] = NULL;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001313 }
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001314 size_t fifo_pos = 0;
1315 size_t fifo_count = 0;
1316 for (;;) {
1317 const Object* obj = fifo[fifo_pos & fifo_mask];
1318 if (obj != NULL) {
1319 ScanObject(obj);
1320 fifo[fifo_pos & fifo_mask] = NULL;
1321 --fifo_count;
1322 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001323
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001324 if (!mark_stack_->IsEmpty()) {
1325 const Object* obj = mark_stack_->PopBack();
1326 DCHECK(obj != NULL);
1327 fifo[fifo_pos & fifo_mask] = obj;
1328 __builtin_prefetch(obj);
1329 fifo_count++;
1330 }
1331 fifo_pos++;
1332
1333 if (!fifo_count) {
1334 CHECK(mark_stack_->IsEmpty()) << mark_stack_->Size();
1335 break;
1336 }
1337 }
1338 } else {
1339 while (!mark_stack_->IsEmpty()) {
1340 const Object* obj = mark_stack_->PopBack();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001341 DCHECK(obj != NULL);
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001342 ScanObject(obj);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001343 }
1344 }
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001345 timings_.EndSplit();
Carl Shapiro69759ea2011-07-21 18:13:35 -07001346}
1347
Carl Shapiro69759ea2011-07-21 18:13:35 -07001348// Walks the reference list marking any references subject to the
1349// reference clearing policy. References with a black referent are
1350// removed from the list. References with white referents biased
1351// toward saving are blackened and also removed from the list.
1352void MarkSweep::PreserveSomeSoftReferences(Object** list) {
1353 DCHECK(list != NULL);
1354 Object* clear = NULL;
1355 size_t counter = 0;
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001356
1357 DCHECK(mark_stack_->IsEmpty());
1358
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001359 timings_.StartSplit("PreserveSomeSoftReferences");
Carl Shapiro69759ea2011-07-21 18:13:35 -07001360 while (*list != NULL) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001361 Object* ref = heap_->DequeuePendingReference(list);
1362 Object* referent = heap_->GetReferenceReferent(ref);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001363 if (referent == NULL) {
1364 // Referent was cleared by the user during marking.
1365 continue;
1366 }
1367 bool is_marked = IsMarked(referent);
1368 if (!is_marked && ((++counter) & 1)) {
1369 // Referent is white and biased toward saving, mark it.
1370 MarkObject(referent);
1371 is_marked = true;
1372 }
1373 if (!is_marked) {
1374 // Referent is white, queue it for clearing.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001375 heap_->EnqueuePendingReference(ref, &clear);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001376 }
1377 }
1378 *list = clear;
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001379 timings_.EndSplit();
1380
Carl Shapiro69759ea2011-07-21 18:13:35 -07001381 // Restart the mark with the newly black references added to the
1382 // root set.
1383 ProcessMarkStack();
1384}
1385
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001386inline bool MarkSweep::IsMarked(const Object* object) const
1387 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
Mathieu Chartier9642c962013-08-05 17:40:36 -07001388 if (IsImmune(object)) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001389 return true;
1390 }
1391 DCHECK(current_mark_bitmap_ != NULL);
1392 if (current_mark_bitmap_->HasAddress(object)) {
1393 return current_mark_bitmap_->Test(object);
1394 }
1395 return heap_->GetMarkBitmap()->Test(object);
1396}
1397
1398
Carl Shapiro69759ea2011-07-21 18:13:35 -07001399// Unlink the reference list clearing references objects with white
1400// referents. Cleared references registered to a reference queue are
1401// scheduled for appending by the heap worker thread.
1402void MarkSweep::ClearWhiteReferences(Object** list) {
1403 DCHECK(list != NULL);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001404 while (*list != NULL) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001405 Object* ref = heap_->DequeuePendingReference(list);
1406 Object* referent = heap_->GetReferenceReferent(ref);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001407 if (referent != NULL && !IsMarked(referent)) {
1408 // Referent is white, clear it.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001409 heap_->ClearReferenceReferent(ref);
1410 if (heap_->IsEnqueuable(ref)) {
1411 heap_->EnqueueReference(ref, &cleared_reference_list_);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001412 }
1413 }
1414 }
1415 DCHECK(*list == NULL);
1416}
1417
1418// Enqueues finalizer references with white referents. White
1419// referents are blackened, moved to the zombie field, and the
1420// referent field is cleared.
1421void MarkSweep::EnqueueFinalizerReferences(Object** list) {
1422 DCHECK(list != NULL);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001423 timings_.StartSplit("EnqueueFinalizerReferences");
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001424 MemberOffset zombie_offset = heap_->GetFinalizerReferenceZombieOffset();
Carl Shapiro69759ea2011-07-21 18:13:35 -07001425 bool has_enqueued = false;
1426 while (*list != NULL) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001427 Object* ref = heap_->DequeuePendingReference(list);
1428 Object* referent = heap_->GetReferenceReferent(ref);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001429 if (referent != NULL && !IsMarked(referent)) {
1430 MarkObject(referent);
1431 // If the referent is non-null the reference must queuable.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001432 DCHECK(heap_->IsEnqueuable(ref));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001433 ref->SetFieldObject(zombie_offset, referent, false);
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001434 heap_->ClearReferenceReferent(ref);
1435 heap_->EnqueueReference(ref, &cleared_reference_list_);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001436 has_enqueued = true;
1437 }
1438 }
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001439 timings_.EndSplit();
Carl Shapiro69759ea2011-07-21 18:13:35 -07001440 if (has_enqueued) {
1441 ProcessMarkStack();
1442 }
1443 DCHECK(*list == NULL);
1444}
1445
Carl Shapiro58551df2011-07-24 03:09:51 -07001446// Process reference class instances and schedule finalizations.
Carl Shapiro69759ea2011-07-21 18:13:35 -07001447void MarkSweep::ProcessReferences(Object** soft_references, bool clear_soft,
1448 Object** weak_references,
1449 Object** finalizer_references,
1450 Object** phantom_references) {
1451 DCHECK(soft_references != NULL);
1452 DCHECK(weak_references != NULL);
1453 DCHECK(finalizer_references != NULL);
1454 DCHECK(phantom_references != NULL);
1455
1456 // Unless we are in the zygote or required to clear soft references
1457 // with white references, preserve some white referents.
Ian Rogers2945e242012-06-03 14:45:16 -07001458 if (!clear_soft && !Runtime::Current()->IsZygote()) {
Carl Shapiro69759ea2011-07-21 18:13:35 -07001459 PreserveSomeSoftReferences(soft_references);
1460 }
1461
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001462 timings_.StartSplit("ProcessReferences");
Carl Shapiro69759ea2011-07-21 18:13:35 -07001463 // Clear all remaining soft and weak references with white
1464 // referents.
1465 ClearWhiteReferences(soft_references);
1466 ClearWhiteReferences(weak_references);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001467 timings_.EndSplit();
Carl Shapiro69759ea2011-07-21 18:13:35 -07001468
1469 // Preserve all white objects with finalize methods and schedule
1470 // them for finalization.
1471 EnqueueFinalizerReferences(finalizer_references);
1472
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001473 timings_.StartSplit("ProcessReferences");
Carl Shapiro69759ea2011-07-21 18:13:35 -07001474 // Clear all f-reachable soft and weak references with white
1475 // referents.
1476 ClearWhiteReferences(soft_references);
1477 ClearWhiteReferences(weak_references);
1478
1479 // Clear all phantom references with white referents.
1480 ClearWhiteReferences(phantom_references);
1481
1482 // At this point all reference lists should be empty.
1483 DCHECK(*soft_references == NULL);
1484 DCHECK(*weak_references == NULL);
1485 DCHECK(*finalizer_references == NULL);
1486 DCHECK(*phantom_references == NULL);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001487 timings_.EndSplit();
Carl Shapiro69759ea2011-07-21 18:13:35 -07001488}
1489
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001490void MarkSweep::UnBindBitmaps() {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001491 timings_.StartSplit("UnBindBitmaps");
Ian Rogers1d54e732013-05-02 21:10:01 -07001492 const std::vector<space::ContinuousSpace*>& spaces = GetHeap()->GetContinuousSpaces();
1493 // TODO: C++0x
1494 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
1495 for (It it = spaces.begin(), end = spaces.end(); it != end; ++it) {
1496 space::ContinuousSpace* space = *it;
1497 if (space->IsDlMallocSpace()) {
1498 space::DlMallocSpace* alloc_space = space->AsDlMallocSpace();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001499 if (alloc_space->temp_bitmap_.get() != NULL) {
1500 // At this point, the temp_bitmap holds our old mark bitmap.
Ian Rogers1d54e732013-05-02 21:10:01 -07001501 accounting::SpaceBitmap* new_bitmap = alloc_space->temp_bitmap_.release();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001502 GetHeap()->GetMarkBitmap()->ReplaceBitmap(alloc_space->mark_bitmap_.get(), new_bitmap);
1503 CHECK_EQ(alloc_space->mark_bitmap_.release(), alloc_space->live_bitmap_.get());
1504 alloc_space->mark_bitmap_.reset(new_bitmap);
1505 DCHECK(alloc_space->temp_bitmap_.get() == NULL);
1506 }
1507 }
1508 }
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001509 timings_.EndSplit();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001510}
1511
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001512void MarkSweep::FinishPhase() {
1513 // Can't enqueue referneces if we hold the mutator lock.
1514 Object* cleared_references = GetClearedReferences();
Ian Rogers1d54e732013-05-02 21:10:01 -07001515 Heap* heap = GetHeap();
1516 heap->EnqueueClearedReferences(&cleared_references);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001517
Ian Rogers1d54e732013-05-02 21:10:01 -07001518 heap->PostGcVerification(this);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001519
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001520 timings_.StartSplit("GrowForUtilization");
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001521 heap->GrowForUtilization(GetGcType(), GetDurationNs());
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001522 timings_.EndSplit();
Mathieu Chartier65db8802012-11-20 12:36:46 -08001523
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001524 timings_.StartSplit("RequestHeapTrim");
Ian Rogers1d54e732013-05-02 21:10:01 -07001525 heap->RequestHeapTrim();
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001526 timings_.EndSplit();
Mathieu Chartier65db8802012-11-20 12:36:46 -08001527
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001528 // Update the cumulative statistics
Ian Rogers1d54e732013-05-02 21:10:01 -07001529 total_time_ns_ += GetDurationNs();
1530 total_paused_time_ns_ += std::accumulate(GetPauseTimes().begin(), GetPauseTimes().end(), 0,
1531 std::plus<uint64_t>());
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001532 total_freed_objects_ += GetFreedObjects();
1533 total_freed_bytes_ += GetFreedBytes();
1534
1535 // Ensure that the mark stack is empty.
1536 CHECK(mark_stack_->IsEmpty());
1537
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001538 if (kCountScannedTypes) {
1539 VLOG(gc) << "MarkSweep scanned classes=" << class_count_ << " arrays=" << array_count_
1540 << " other=" << other_count_;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001541 }
1542
1543 if (kCountTasks) {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001544 VLOG(gc) << "Total number of work chunks allocated: " << work_chunks_created_;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001545 }
1546
1547 if (kMeasureOverhead) {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001548 VLOG(gc) << "Overhead time " << PrettyDuration(overhead_time_);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001549 }
1550
1551 if (kProfileLargeObjects) {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001552 VLOG(gc) << "Large objects tested " << large_object_test_ << " marked " << large_object_mark_;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001553 }
1554
1555 if (kCountClassesMarked) {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001556 VLOG(gc) << "Classes marked " << classes_marked_;
1557 }
1558
1559 if (kCountJavaLangRefs) {
1560 VLOG(gc) << "References scanned " << reference_count_;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001561 }
1562
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001563 // Update the cumulative loggers.
1564 cumulative_timings_.Start();
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001565 cumulative_timings_.AddLogger(timings_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001566 cumulative_timings_.End();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001567
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001568 // Clear all of the spaces' mark bitmaps.
Ian Rogers1d54e732013-05-02 21:10:01 -07001569 const std::vector<space::ContinuousSpace*>& spaces = GetHeap()->GetContinuousSpaces();
1570 // TODO: C++0x
1571 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
1572 for (It it = spaces.begin(), end = spaces.end(); it != end; ++it) {
1573 space::ContinuousSpace* space = *it;
1574 if (space->GetGcRetentionPolicy() != space::kGcRetentionPolicyNeverCollect) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001575 space->GetMarkBitmap()->Clear();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001576 }
1577 }
Mathieu Chartier5301cd22012-05-31 12:11:36 -07001578 mark_stack_->Reset();
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001579
1580 // Reset the marked large objects.
Ian Rogers1d54e732013-05-02 21:10:01 -07001581 space::LargeObjectSpace* large_objects = GetHeap()->GetLargeObjectsSpace();
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001582 large_objects->GetMarkObjects()->Clear();
Carl Shapiro69759ea2011-07-21 18:13:35 -07001583}
1584
Ian Rogers1d54e732013-05-02 21:10:01 -07001585} // namespace collector
1586} // namespace gc
Carl Shapiro69759ea2011-07-21 18:13:35 -07001587} // namespace art