blob: 61570ae3936d44cc5d9366e18590323132e9cb80 [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"
Brian Carlstromea46f952013-07-30 01:26:50 -070040#include "mirror/art_field.h"
41#include "mirror/art_field-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080042#include "mirror/class-inl.h"
43#include "mirror/class_loader.h"
44#include "mirror/dex_cache.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080045#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 Carlstromea46f952013-07-30 01:26:50 -070053using ::art::mirror::ArtField;
Brian Carlstrom3e3d5912013-07-18 00:19:45 -070054using ::art::mirror::Class;
Brian Carlstrom3e3d5912013-07-18 00:19:45 -070055using ::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;
Hiroshi Yamauchib22a4512013-08-13 15:03:22 -070066static const size_t kSweepArrayChunkFreeSize = 1024;
Mathieu Chartier858f1c52012-10-17 17:45:55 -070067
Mathieu Chartier02b6a782012-10-26 13:51:26 -070068// Profiling and information flags.
69static const bool kCountClassesMarked = false;
70static const bool kProfileLargeObjects = false;
71static const bool kMeasureOverhead = false;
72static const bool kCountTasks = false;
Mathieu Chartierd22d5482012-11-06 17:14:12 -080073static const bool kCountJavaLangRefs = false;
Mathieu Chartier02b6a782012-10-26 13:51:26 -070074
Ian Rogers1d54e732013-05-02 21:10:01 -070075void MarkSweep::ImmuneSpace(space::ContinuousSpace* space) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -080076 // Bind live to mark bitmap if necessary.
77 if (space->GetLiveBitmap() != space->GetMarkBitmap()) {
78 BindLiveToMarkBitmap(space);
79 }
80
81 // Add the space to the immune region.
82 if (immune_begin_ == NULL) {
83 DCHECK(immune_end_ == NULL);
84 SetImmuneRange(reinterpret_cast<Object*>(space->Begin()),
85 reinterpret_cast<Object*>(space->End()));
86 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -070087 const std::vector<space::ContinuousSpace*>& spaces = GetHeap()->GetContinuousSpaces();
88 const space::ContinuousSpace* prev_space = NULL;
89 // Find out if the previous space is immune.
90 // TODO: C++0x
91 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
92 for (It it = spaces.begin(), end = spaces.end(); it != end; ++it) {
93 if (*it == space) {
94 break;
Mathieu Chartier2b82db42012-11-14 17:29:05 -080095 }
Ian Rogers1d54e732013-05-02 21:10:01 -070096 prev_space = *it;
97 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -080098
Ian Rogers1d54e732013-05-02 21:10:01 -070099 // If previous space was immune, then extend the immune region. Relies on continuous spaces
100 // being sorted by Heap::AddContinuousSpace.
101 if (prev_space != NULL &&
102 immune_begin_ <= reinterpret_cast<Object*>(prev_space->Begin()) &&
103 immune_end_ >= reinterpret_cast<Object*>(prev_space->End())) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800104 immune_begin_ = std::min(reinterpret_cast<Object*>(space->Begin()), immune_begin_);
105 immune_end_ = std::max(reinterpret_cast<Object*>(space->End()), immune_end_);
106 }
107 }
108}
109
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800110void MarkSweep::BindBitmaps() {
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700111 timings_.StartSplit("BindBitmaps");
Ian Rogers1d54e732013-05-02 21:10:01 -0700112 const std::vector<space::ContinuousSpace*>& spaces = GetHeap()->GetContinuousSpaces();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800113 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
114
115 // Mark all of the spaces we never collect as immune.
Ian Rogers1d54e732013-05-02 21:10:01 -0700116 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
117 for (It it = spaces.begin(), end = spaces.end(); it != end; ++it) {
118 space::ContinuousSpace* space = *it;
119 if (space->GetGcRetentionPolicy() == space::kGcRetentionPolicyNeverCollect) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800120 ImmuneSpace(space);
121 }
122 }
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700123 timings_.EndSplit();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800124}
125
Ian Rogers1d54e732013-05-02 21:10:01 -0700126MarkSweep::MarkSweep(Heap* heap, bool is_concurrent, const std::string& name_prefix)
127 : GarbageCollector(heap,
128 name_prefix + (name_prefix.empty() ? "" : " ") +
129 (is_concurrent ? "concurrent mark sweep": "mark sweep")),
130 current_mark_bitmap_(NULL),
131 java_lang_Class_(NULL),
132 mark_stack_(NULL),
Ian Rogers1d54e732013-05-02 21:10:01 -0700133 immune_begin_(NULL),
134 immune_end_(NULL),
135 soft_reference_list_(NULL),
136 weak_reference_list_(NULL),
137 finalizer_reference_list_(NULL),
138 phantom_reference_list_(NULL),
139 cleared_reference_list_(NULL),
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800140 gc_barrier_(new Barrier(0)),
Ian Rogers62d6c772013-02-27 08:32:07 -0800141 large_object_lock_("mark sweep large object lock", kMarkSweepLargeObjectLock),
142 mark_stack_expand_lock_("mark sweep mark stack expand lock"),
Ian Rogers1bd4b4c2013-04-18 17:47:42 -0700143 is_concurrent_(is_concurrent),
Ian Rogers1d54e732013-05-02 21:10:01 -0700144 clear_soft_references_(false) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800145}
146
147void MarkSweep::InitializePhase() {
Ian Rogers1d54e732013-05-02 21:10:01 -0700148 timings_.Reset();
Anwar Ghuloum46543222013-08-12 09:28:42 -0700149 base::TimingLogger::ScopedSplit split("InitializePhase", &timings_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800150 mark_stack_ = GetHeap()->mark_stack_.get();
151 DCHECK(mark_stack_ != NULL);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800152 SetImmuneRange(NULL, NULL);
153 soft_reference_list_ = NULL;
154 weak_reference_list_ = NULL;
155 finalizer_reference_list_ = NULL;
156 phantom_reference_list_ = NULL;
157 cleared_reference_list_ = NULL;
158 freed_bytes_ = 0;
159 freed_objects_ = 0;
160 class_count_ = 0;
161 array_count_ = 0;
162 other_count_ = 0;
163 large_object_test_ = 0;
164 large_object_mark_ = 0;
165 classes_marked_ = 0;
166 overhead_time_ = 0;
167 work_chunks_created_ = 0;
168 work_chunks_deleted_ = 0;
169 reference_count_ = 0;
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700170 java_lang_Class_ = Class::GetJavaLangClass();
171 CHECK(java_lang_Class_ != NULL);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700172
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700173 FindDefaultMarkBitmap();
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700174
175// Do any pre GC verification.
Anwar Ghuloum46543222013-08-12 09:28:42 -0700176 timings_.NewSplit("PreGcVerification");
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800177 heap_->PreGcVerification(this);
178}
179
180void MarkSweep::ProcessReferences(Thread* self) {
Mathieu Chartier8e56c7e2012-11-20 13:25:50 -0800181 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800182 ProcessReferences(&soft_reference_list_, clear_soft_references_, &weak_reference_list_,
183 &finalizer_reference_list_, &phantom_reference_list_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800184}
185
186bool MarkSweep::HandleDirtyObjectsPhase() {
Anwar Ghuloum46543222013-08-12 09:28:42 -0700187 base::TimingLogger::ScopedSplit split("HandleDirtyObjectsPhase", &timings_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800188 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() {
Anwar Ghuloum46543222013-08-12 09:28:42 -0700219 base::TimingLogger::ScopedSplit split("MarkingPhase", &timings_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800220 Heap* heap = GetHeap();
221 Thread* self = Thread::Current();
222
223 BindBitmaps();
224 FindDefaultMarkBitmap();
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700225
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800226 // Process dirty cards and add dirty cards to mod union tables.
227 heap->ProcessCards(timings_);
228
229 // Need to do this before the checkpoint since we don't want any threads to add references to
230 // the live stack during the recursive mark.
Anwar Ghuloum46543222013-08-12 09:28:42 -0700231 timings_.NewSplit("SwapStacks");
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800232 heap->SwapStacks();
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() {
Anwar Ghuloum46543222013-08-12 09:28:42 -0700263 base::TimingLogger::ScopedSplit split("ReclaimPhase", &timings_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800264 Thread* self = Thread::Current();
265
266 if (!IsConcurrent()) {
Anwar Ghulouma9a50922013-08-09 21:34:20 -0700267 base::TimingLogger::ScopedSplit split("ProcessReferences", &timings_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800268 ProcessReferences(self);
Mathieu Chartier9642c962013-08-05 17:40:36 -0700269 } else {
Anwar Ghulouma9a50922013-08-09 21:34:20 -0700270 base::TimingLogger::ScopedSplit split("UnMarkAllocStack", &timings_);
Mathieu Chartier9642c962013-08-05 17:40:36 -0700271 accounting::ObjectStack* allocation_stack = GetHeap()->allocation_stack_.get();
272 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
273 // The allocation stack contains things allocated since the start of the GC. These may have been
274 // marked during this GC meaning they won't be eligible for reclaiming in the next sticky GC.
275 // Remove these objects from the mark bitmaps so that they will be eligible for sticky
276 // collection.
277 // There is a race here which is safely handled. Another thread such as the hprof could
278 // have flushed the alloc stack after we resumed the threads. This is safe however, since
279 // reseting the allocation stack zeros it out with madvise. This means that we will either
280 // read NULLs or attempt to unmark a newly allocated object which will not be marked in the
281 // first place.
282 mirror::Object** end = allocation_stack->End();
283 for (mirror::Object** it = allocation_stack->Begin(); it != end; ++it) {
284 Object* obj = *it;
285 if (obj != NULL) {
286 UnMarkObjectNonNull(obj);
287 }
288 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800289 }
290
291 // Before freeing anything, lets verify the heap.
292 if (kIsDebugBuild) {
293 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
294 VerifyImageRoots();
295 }
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700296 timings_.StartSplit("PreSweepingGcVerification");
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800297 heap_->PreSweepingGcVerification(this);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700298 timings_.EndSplit();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800299
300 {
301 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
302
303 // Reclaim unmarked objects.
Ian Rogers1d54e732013-05-02 21:10:01 -0700304 Sweep(false);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800305
306 // Swap the live and mark bitmaps for each space which we modified space. This is an
307 // optimization that enables us to not clear live bits inside of the sweep. Only swaps unbound
308 // bitmaps.
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700309 timings_.StartSplit("SwapBitmaps");
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800310 SwapBitmaps();
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700311 timings_.EndSplit();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800312
313 // Unbind the live and mark bitmaps.
314 UnBindBitmaps();
315 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800316}
317
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800318void MarkSweep::SetImmuneRange(Object* begin, Object* end) {
319 immune_begin_ = begin;
320 immune_end_ = end;
Carl Shapiro58551df2011-07-24 03:09:51 -0700321}
322
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700323void MarkSweep::FindDefaultMarkBitmap() {
Anwar Ghuloum46543222013-08-12 09:28:42 -0700324 base::TimingLogger::ScopedSplit split("FindDefaultMarkBitmap", &timings_);
Ian Rogers1d54e732013-05-02 21:10:01 -0700325 const std::vector<space::ContinuousSpace*>& spaces = GetHeap()->GetContinuousSpaces();
326 // TODO: C++0x
327 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
328 for (It it = spaces.begin(), end = spaces.end(); it != end; ++it) {
329 space::ContinuousSpace* space = *it;
330 if (space->GetGcRetentionPolicy() == space::kGcRetentionPolicyAlwaysCollect) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700331 current_mark_bitmap_ = (*it)->GetMarkBitmap();
332 CHECK(current_mark_bitmap_ != NULL);
333 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 Ghuloum46543222013-08-12 09:28:42 -0700678 base::TimingLogger::ScopedSplit split("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
Hiroshi Yamauchib22a4512013-08-13 15:03:22 -0700920 size_t freed_objects = 0;
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700921 size_t freed_large_objects = 0;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700922 size_t count = allocations->Size();
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700923 Object** objects = const_cast<Object**>(allocations->Begin());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700924 Object** out = objects;
Hiroshi Yamauchib22a4512013-08-13 15:03:22 -0700925 Object** objects_to_chunk_free = out;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700926
927 // Empty the allocation stack.
Ian Rogers50b35e22012-10-04 10:09:15 -0700928 Thread* self = Thread::Current();
Brian Carlstrom02c8cc62013-07-18 15:54:44 -0700929 for (size_t i = 0; i < count; ++i) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700930 Object* obj = objects[i];
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700931 // There should only be objects in the AllocSpace/LargeObjectSpace in the allocation stack.
932 if (LIKELY(mark_bitmap->HasAddress(obj))) {
933 if (!mark_bitmap->Test(obj)) {
934 // Don't bother un-marking since we clear the mark bitmap anyways.
935 *(out++) = obj;
Hiroshi Yamauchib22a4512013-08-13 15:03:22 -0700936 // Free objects in chunks.
937 DCHECK_GE(out, objects_to_chunk_free);
938 DCHECK_LE(static_cast<size_t>(out - objects_to_chunk_free), kSweepArrayChunkFreeSize);
939 if (static_cast<size_t>(out - objects_to_chunk_free) == kSweepArrayChunkFreeSize) {
940 timings_.StartSplit("FreeList");
941 size_t chunk_freed_objects = out - objects_to_chunk_free;
942 freed_objects += chunk_freed_objects;
943 freed_bytes += space->FreeList(self, chunk_freed_objects, objects_to_chunk_free);
944 objects_to_chunk_free = out;
945 timings_.EndSplit();
946 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700947 }
948 } else if (!large_mark_objects->Test(obj)) {
949 ++freed_large_objects;
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700950 freed_bytes += large_object_space->Free(self, obj);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700951 }
952 }
Hiroshi Yamauchib22a4512013-08-13 15:03:22 -0700953 // Free the remaining objects in chunks.
954 DCHECK_GE(out, objects_to_chunk_free);
955 DCHECK_LE(static_cast<size_t>(out - objects_to_chunk_free), kSweepArrayChunkFreeSize);
956 if (out - objects_to_chunk_free > 0) {
957 timings_.StartSplit("FreeList");
958 size_t chunk_freed_objects = out - objects_to_chunk_free;
959 freed_objects += chunk_freed_objects;
960 freed_bytes += space->FreeList(self, chunk_freed_objects, objects_to_chunk_free);
961 timings_.EndSplit();
962 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700963 CHECK_EQ(count, allocations->Size());
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700964 timings_.EndSplit();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700965
Hiroshi Yamauchib22a4512013-08-13 15:03:22 -0700966 timings_.StartSplit("RecordFree");
Mathieu Chartier40e978b2012-09-07 11:38:36 -0700967 VLOG(heap) << "Freed " << freed_objects << "/" << count
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700968 << " objects with size " << PrettySize(freed_bytes);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700969 heap_->RecordFree(freed_objects + freed_large_objects, freed_bytes);
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -0700970 freed_objects_.fetch_add(freed_objects);
971 freed_bytes_.fetch_add(freed_bytes);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700972 timings_.EndSplit();
Ian Rogers1d54e732013-05-02 21:10:01 -0700973
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700974 timings_.StartSplit("ResetStack");
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700975 allocations->Reset();
Anwar Ghuloum4446ab92013-08-09 21:17:25 -0700976 timings_.EndSplit();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700977}
978
Ian Rogers1d54e732013-05-02 21:10:01 -0700979void MarkSweep::Sweep(bool swap_bitmaps) {
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700980 DCHECK(mark_stack_->IsEmpty());
Anwar Ghuloum46543222013-08-12 09:28:42 -0700981 base::TimingLogger::ScopedSplit("Sweep", &timings_);
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700982
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700983 // If we don't swap bitmaps then newly allocated Weaks go into the live bitmap but not mark
984 // bitmap, resulting in occasional frees of Weaks which are still in use.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700985 SweepSystemWeaks();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700986
Ian Rogers1d54e732013-05-02 21:10:01 -0700987 const bool partial = (GetGcType() == kGcTypePartial);
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800988 SweepCallbackContext scc;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700989 scc.mark_sweep = this;
Ian Rogers50b35e22012-10-04 10:09:15 -0700990 scc.self = Thread::Current();
Ian Rogers1d54e732013-05-02 21:10:01 -0700991 const std::vector<space::ContinuousSpace*>& spaces = GetHeap()->GetContinuousSpaces();
992 // TODO: C++0x
993 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
994 for (It it = spaces.begin(), end = spaces.end(); it != end; ++it) {
995 space::ContinuousSpace* space = *it;
996 // We always sweep always collect spaces.
997 bool sweep_space = (space->GetGcRetentionPolicy() == space::kGcRetentionPolicyAlwaysCollect);
998 if (!partial && !sweep_space) {
999 // We sweep full collect spaces when the GC isn't a partial GC (ie its full).
1000 sweep_space = (space->GetGcRetentionPolicy() == space::kGcRetentionPolicyFullCollect);
1001 }
1002 if (sweep_space) {
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001003 uintptr_t begin = reinterpret_cast<uintptr_t>(space->Begin());
1004 uintptr_t end = reinterpret_cast<uintptr_t>(space->End());
Ian Rogers1d54e732013-05-02 21:10:01 -07001005 scc.space = space->AsDlMallocSpace();
1006 accounting::SpaceBitmap* live_bitmap = space->GetLiveBitmap();
1007 accounting::SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001008 if (swap_bitmaps) {
1009 std::swap(live_bitmap, mark_bitmap);
1010 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001011 if (!space->IsZygoteSpace()) {
Anwar Ghuloum46543222013-08-12 09:28:42 -07001012 base::TimingLogger::ScopedSplit split("SweepAllocSpace", &timings_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001013 // Bitmaps are pre-swapped for optimization which enables sweeping with the heap unlocked.
Ian Rogers1d54e732013-05-02 21:10:01 -07001014 accounting::SpaceBitmap::SweepWalk(*live_bitmap, *mark_bitmap, begin, end,
1015 &SweepCallback, reinterpret_cast<void*>(&scc));
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001016 } else {
Anwar Ghuloum46543222013-08-12 09:28:42 -07001017 base::TimingLogger::ScopedSplit split("SweepZygote", &timings_);
Ian Rogers1d54e732013-05-02 21:10:01 -07001018 // Zygote sweep takes care of dirtying cards and clearing live bits, does not free actual
1019 // memory.
1020 accounting::SpaceBitmap::SweepWalk(*live_bitmap, *mark_bitmap, begin, end,
1021 &ZygoteSweepCallback, reinterpret_cast<void*>(&scc));
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001022 }
Carl Shapiro58551df2011-07-24 03:09:51 -07001023 }
1024 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001025
1026 SweepLargeObjects(swap_bitmaps);
Carl Shapiro58551df2011-07-24 03:09:51 -07001027}
1028
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001029void MarkSweep::SweepLargeObjects(bool swap_bitmaps) {
Anwar Ghuloum46543222013-08-12 09:28:42 -07001030 base::TimingLogger::ScopedSplit("SweepLargeObjects", &timings_);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001031 // Sweep large objects
Ian Rogers1d54e732013-05-02 21:10:01 -07001032 space::LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
1033 accounting::SpaceSetMap* large_live_objects = large_object_space->GetLiveObjects();
1034 accounting::SpaceSetMap* large_mark_objects = large_object_space->GetMarkObjects();
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001035 if (swap_bitmaps) {
1036 std::swap(large_live_objects, large_mark_objects);
1037 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001038 accounting::SpaceSetMap::Objects& live_objects = large_live_objects->GetObjects();
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001039 // O(n*log(n)) but hopefully there are not too many large objects.
1040 size_t freed_objects = 0;
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001041 size_t freed_bytes = 0;
Ian Rogers50b35e22012-10-04 10:09:15 -07001042 Thread* self = Thread::Current();
Ian Rogers1d54e732013-05-02 21:10:01 -07001043 // TODO: C++0x
1044 typedef accounting::SpaceSetMap::Objects::iterator It;
1045 for (It it = live_objects.begin(), end = live_objects.end(); it != end; ++it) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001046 if (!large_mark_objects->Test(*it)) {
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -07001047 freed_bytes += large_object_space->Free(self, const_cast<Object*>(*it));
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001048 ++freed_objects;
1049 }
1050 }
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -07001051 freed_objects_.fetch_add(freed_objects);
1052 freed_bytes_.fetch_add(freed_bytes);
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001053 GetHeap()->RecordFree(freed_objects, freed_bytes);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001054}
1055
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001056void MarkSweep::CheckReference(const Object* obj, const Object* ref, MemberOffset offset, bool is_static) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001057 const std::vector<space::ContinuousSpace*>& spaces = GetHeap()->GetContinuousSpaces();
1058 // TODO: C++0x
1059 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
1060 for (It it = spaces.begin(), end = spaces.end(); it != end; ++it) {
1061 space::ContinuousSpace* space = *it;
1062 if (space->IsDlMallocSpace() && space->Contains(ref)) {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001063 DCHECK(IsMarked(obj));
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001064
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001065 bool is_marked = IsMarked(ref);
1066 if (!is_marked) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001067 LOG(INFO) << *space;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001068 LOG(WARNING) << (is_static ? "Static ref'" : "Instance ref'") << PrettyTypeOf(ref)
1069 << "' (" << reinterpret_cast<const void*>(ref) << ") in '" << PrettyTypeOf(obj)
1070 << "' (" << reinterpret_cast<const void*>(obj) << ") at offset "
1071 << reinterpret_cast<void*>(offset.Int32Value()) << " wasn't marked";
Mathieu Chartier262e5ff2012-06-01 17:35:38 -07001072
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001073 const Class* klass = is_static ? obj->AsClass() : obj->GetClass();
1074 DCHECK(klass != NULL);
Brian Carlstromea46f952013-07-30 01:26:50 -07001075 const ObjectArray<ArtField>* fields = is_static ? klass->GetSFields() : klass->GetIFields();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001076 DCHECK(fields != NULL);
1077 bool found = false;
1078 for (int32_t i = 0; i < fields->GetLength(); ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001079 const ArtField* cur = fields->Get(i);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001080 if (cur->GetOffset().Int32Value() == offset.Int32Value()) {
1081 LOG(WARNING) << "Field referencing the alloc space was " << PrettyField(cur);
1082 found = true;
1083 break;
1084 }
1085 }
1086 if (!found) {
1087 LOG(WARNING) << "Could not find field in object alloc space with offset " << offset.Int32Value();
1088 }
Mathieu Chartier262e5ff2012-06-01 17:35:38 -07001089
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001090 bool obj_marked = heap_->GetCardTable()->IsDirty(obj);
1091 if (!obj_marked) {
1092 LOG(WARNING) << "Object '" << PrettyTypeOf(obj) << "' "
1093 << "(" << reinterpret_cast<const void*>(obj) << ") contains references to "
1094 << "the alloc space, but wasn't card marked";
Mathieu Chartier262e5ff2012-06-01 17:35:38 -07001095 }
1096 }
Ian Rogers5d76c432011-10-31 21:42:49 -07001097 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001098 break;
Ian Rogers5d76c432011-10-31 21:42:49 -07001099 }
1100}
1101
Carl Shapiro69759ea2011-07-21 18:13:35 -07001102// Process the "referent" field in a java.lang.ref.Reference. If the
1103// referent has not yet been marked, put it on the appropriate list in
1104// the gcHeap for later processing.
1105void MarkSweep::DelayReferenceReferent(Object* obj) {
1106 DCHECK(obj != NULL);
Brian Carlstrom1f870082011-08-23 16:02:11 -07001107 Class* klass = obj->GetClass();
1108 DCHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001109 DCHECK(klass->IsReferenceClass());
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001110 Object* pending = obj->GetFieldObject<Object*>(heap_->GetReferencePendingNextOffset(), false);
1111 Object* referent = heap_->GetReferenceReferent(obj);
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001112 if (kCountJavaLangRefs) {
1113 ++reference_count_;
1114 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001115 if (pending == NULL && referent != NULL && !IsMarked(referent)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07001116 Object** list = NULL;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001117 if (klass->IsSoftReferenceClass()) {
Carl Shapiro69759ea2011-07-21 18:13:35 -07001118 list = &soft_reference_list_;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001119 } else if (klass->IsWeakReferenceClass()) {
Carl Shapiro69759ea2011-07-21 18:13:35 -07001120 list = &weak_reference_list_;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001121 } else if (klass->IsFinalizerReferenceClass()) {
Carl Shapiro69759ea2011-07-21 18:13:35 -07001122 list = &finalizer_reference_list_;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001123 } else if (klass->IsPhantomReferenceClass()) {
Carl Shapiro69759ea2011-07-21 18:13:35 -07001124 list = &phantom_reference_list_;
1125 }
Brian Carlstrom0796af02011-10-12 14:31:45 -07001126 DCHECK(list != NULL) << PrettyClass(klass) << " " << std::hex << klass->GetAccessFlags();
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001127 // TODO: One lock per list?
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001128 heap_->EnqueuePendingReference(obj, list);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001129 }
1130}
1131
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001132void MarkSweep::ScanRoot(const Object* obj) {
1133 ScanObject(obj);
1134}
1135
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001136class MarkObjectVisitor {
1137 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001138 explicit MarkObjectVisitor(MarkSweep* const mark_sweep) : mark_sweep_(mark_sweep) {}
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001139
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001140 // TODO: Fixme when anotatalysis works with visitors.
Brian Carlstromdf629502013-07-17 22:39:56 -07001141 void operator()(const Object* /* obj */, const Object* ref, const MemberOffset& /* offset */,
1142 bool /* is_static */) const
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001143 NO_THREAD_SAFETY_ANALYSIS {
1144 if (kDebugLocking) {
1145 Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
1146 Locks::heap_bitmap_lock_->AssertExclusiveHeld(Thread::Current());
1147 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001148 mark_sweep_->MarkObject(ref);
1149 }
1150
1151 private:
1152 MarkSweep* const mark_sweep_;
1153};
1154
Carl Shapiro69759ea2011-07-21 18:13:35 -07001155// Scans an object reference. Determines the type of the reference
1156// and dispatches to a specialized scanning routine.
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001157void MarkSweep::ScanObject(const Object* obj) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001158 MarkObjectVisitor visitor(this);
1159 ScanObjectVisit(obj, visitor);
1160}
1161
1162class MarkStackChunk : public Task {
Ian Rogers1d54e732013-05-02 21:10:01 -07001163 public:
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001164 MarkStackChunk(ThreadPool* thread_pool, MarkSweep* mark_sweep, Object** begin, Object** end)
1165 : mark_sweep_(mark_sweep),
1166 thread_pool_(thread_pool),
1167 index_(0),
1168 length_(0),
1169 output_(NULL) {
1170 length_ = end - begin;
1171 if (begin != end) {
1172 // Cost not significant since we only do this for the initial set of mark stack chunks.
1173 memcpy(data_, begin, length_ * sizeof(*begin));
1174 }
1175 if (kCountTasks) {
1176 ++mark_sweep_->work_chunks_created_;
1177 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001178 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001179
1180 ~MarkStackChunk() {
1181 DCHECK(output_ == NULL || output_->length_ == 0);
1182 DCHECK_GE(index_, length_);
1183 delete output_;
1184 if (kCountTasks) {
1185 ++mark_sweep_->work_chunks_deleted_;
1186 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001187 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001188
1189 MarkSweep* const mark_sweep_;
1190 ThreadPool* const thread_pool_;
1191 static const size_t max_size = 1 * KB;
1192 // Index of which object we are scanning. Only needs to be atomic if we are doing work stealing.
1193 size_t index_;
1194 // Input / output mark stack. We add newly marked references to data_ until length reaches
1195 // max_size. This is an optimization so that less tasks are created.
1196 // TODO: Investigate using a bounded buffer FIFO.
1197 Object* data_[max_size];
1198 // How many elements in data_ we need to scan.
1199 size_t length_;
1200 // Output block, newly marked references get added to the ouput block so that another thread can
1201 // scan them.
1202 MarkStackChunk* output_;
1203
1204 class MarkObjectParallelVisitor {
1205 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001206 explicit MarkObjectParallelVisitor(MarkStackChunk* chunk_task) : chunk_task_(chunk_task) {}
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001207
Brian Carlstromdf629502013-07-17 22:39:56 -07001208 void operator()(const Object* /* obj */, const Object* ref,
1209 const MemberOffset& /* offset */, bool /* is_static */) const {
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001210 if (ref != NULL && chunk_task_->mark_sweep_->MarkObjectParallel(ref)) {
1211 chunk_task_->MarkStackPush(ref);
1212 }
1213 }
1214
1215 private:
1216 MarkStackChunk* const chunk_task_;
1217 };
1218
1219 // Push an object into the block.
1220 // Don't need to use atomic ++ since we only one thread is writing to an output block at any
1221 // given time.
1222 void Push(Object* obj) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001223 CHECK(obj != NULL);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001224 data_[length_++] = obj;
1225 }
1226
1227 void MarkStackPush(const Object* obj) {
1228 if (static_cast<size_t>(length_) < max_size) {
1229 Push(const_cast<Object*>(obj));
1230 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -07001231 // Internal (thread-local) buffer is full, push to a new buffer instead.
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001232 if (UNLIKELY(output_ == NULL)) {
1233 AllocateOutputChunk();
1234 } else if (UNLIKELY(static_cast<size_t>(output_->length_) == max_size)) {
1235 // Output block is full, queue it up for processing and obtain a new block.
1236 EnqueueOutput();
1237 AllocateOutputChunk();
1238 }
1239 output_->Push(const_cast<Object*>(obj));
1240 }
1241 }
1242
1243 void ScanObject(Object* obj) {
1244 mark_sweep_->ScanObjectVisit(obj, MarkObjectParallelVisitor(this));
1245 }
1246
1247 void EnqueueOutput() {
1248 if (output_ != NULL) {
1249 uint64_t start = 0;
1250 if (kMeasureOverhead) {
1251 start = NanoTime();
1252 }
1253 thread_pool_->AddTask(Thread::Current(), output_);
1254 output_ = NULL;
1255 if (kMeasureOverhead) {
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -07001256 mark_sweep_->overhead_time_.fetch_add(NanoTime() - start);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001257 }
1258 }
1259 }
1260
1261 void AllocateOutputChunk() {
1262 uint64_t start = 0;
1263 if (kMeasureOverhead) {
1264 start = NanoTime();
1265 }
1266 output_ = new MarkStackChunk(thread_pool_, mark_sweep_, NULL, NULL);
1267 if (kMeasureOverhead) {
Mathieu Chartier4b95e8f2013-07-15 16:32:50 -07001268 mark_sweep_->overhead_time_.fetch_add(NanoTime() - start);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001269 }
1270 }
1271
1272 void Finalize() {
1273 EnqueueOutput();
1274 delete this;
1275 }
1276
1277 // Scans all of the objects
1278 virtual void Run(Thread* self) {
Brian Carlstromd74e41b2013-03-24 23:47:01 -07001279 size_t index;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001280 while ((index = index_++) < length_) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001281 if (kUseMarkStackPrefetch) {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001282 static const size_t prefetch_look_ahead = 1;
1283 __builtin_prefetch(data_[std::min(index + prefetch_look_ahead, length_ - 1)]);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001284 }
1285 Object* obj = data_[index];
1286 DCHECK(obj != NULL);
1287 ScanObject(obj);
1288 }
1289 }
1290};
1291
1292void MarkSweep::ProcessMarkStackParallel() {
1293 CHECK(kDisableFinger) << "parallel mark stack processing cannot work when finger is enabled";
1294 Thread* self = Thread::Current();
1295 ThreadPool* thread_pool = GetHeap()->GetThreadPool();
1296 // Split the current mark stack up into work tasks.
1297 const size_t num_threads = thread_pool->GetThreadCount();
1298 const size_t stack_size = mark_stack_->Size();
1299 const size_t chunk_size =
1300 std::min((stack_size + num_threads - 1) / num_threads,
1301 static_cast<size_t>(MarkStackChunk::max_size));
1302 size_t index = 0;
1303 for (size_t i = 0; i < num_threads || index < stack_size; ++i) {
1304 Object** begin = &mark_stack_->Begin()[std::min(stack_size, index)];
1305 Object** end = &mark_stack_->Begin()[std::min(stack_size, index + chunk_size)];
1306 index += chunk_size;
1307 thread_pool->AddTask(self, new MarkStackChunk(thread_pool, this, begin, end));
1308 }
1309 thread_pool->StartWorkers(self);
Ian Rogers1d54e732013-05-02 21:10:01 -07001310 thread_pool->Wait(self, true, true);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001311 mark_stack_->Reset();
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001312 // LOG(INFO) << "Idle wait time " << PrettyDuration(thread_pool->GetWaitTime());
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001313 CHECK_EQ(work_chunks_created_, work_chunks_deleted_) << " some of the work chunks were leaked";
Carl Shapiro69759ea2011-07-21 18:13:35 -07001314}
1315
Ian Rogers5d76c432011-10-31 21:42:49 -07001316// Scan anything that's on the mark stack.
Carl Shapiro69759ea2011-07-21 18:13:35 -07001317void MarkSweep::ProcessMarkStack() {
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001318 ThreadPool* thread_pool = GetHeap()->GetThreadPool();
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001319 timings_.StartSplit("ProcessMarkStack");
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001320 if (kParallelMarkStack && thread_pool != NULL && thread_pool->GetThreadCount() > 0) {
1321 ProcessMarkStackParallel();
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001322 timings_.EndSplit();
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001323 return;
1324 }
1325
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001326 if (kUseMarkStackPrefetch) {
1327 const size_t fifo_size = 4;
1328 const size_t fifo_mask = fifo_size - 1;
1329 const Object* fifo[fifo_size];
Brian Carlstrom02c8cc62013-07-18 15:54:44 -07001330 for (size_t i = 0; i < fifo_size; ++i) {
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001331 fifo[i] = NULL;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001332 }
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001333 size_t fifo_pos = 0;
1334 size_t fifo_count = 0;
1335 for (;;) {
1336 const Object* obj = fifo[fifo_pos & fifo_mask];
1337 if (obj != NULL) {
1338 ScanObject(obj);
1339 fifo[fifo_pos & fifo_mask] = NULL;
1340 --fifo_count;
1341 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001342
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001343 if (!mark_stack_->IsEmpty()) {
1344 const Object* obj = mark_stack_->PopBack();
1345 DCHECK(obj != NULL);
1346 fifo[fifo_pos & fifo_mask] = obj;
1347 __builtin_prefetch(obj);
1348 fifo_count++;
1349 }
1350 fifo_pos++;
1351
1352 if (!fifo_count) {
1353 CHECK(mark_stack_->IsEmpty()) << mark_stack_->Size();
1354 break;
1355 }
1356 }
1357 } else {
1358 while (!mark_stack_->IsEmpty()) {
1359 const Object* obj = mark_stack_->PopBack();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001360 DCHECK(obj != NULL);
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001361 ScanObject(obj);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001362 }
1363 }
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001364 timings_.EndSplit();
Carl Shapiro69759ea2011-07-21 18:13:35 -07001365}
1366
Carl Shapiro69759ea2011-07-21 18:13:35 -07001367// Walks the reference list marking any references subject to the
1368// reference clearing policy. References with a black referent are
1369// removed from the list. References with white referents biased
1370// toward saving are blackened and also removed from the list.
1371void MarkSweep::PreserveSomeSoftReferences(Object** list) {
1372 DCHECK(list != NULL);
1373 Object* clear = NULL;
1374 size_t counter = 0;
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001375
1376 DCHECK(mark_stack_->IsEmpty());
1377
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001378 timings_.StartSplit("PreserveSomeSoftReferences");
Carl Shapiro69759ea2011-07-21 18:13:35 -07001379 while (*list != NULL) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001380 Object* ref = heap_->DequeuePendingReference(list);
1381 Object* referent = heap_->GetReferenceReferent(ref);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001382 if (referent == NULL) {
1383 // Referent was cleared by the user during marking.
1384 continue;
1385 }
1386 bool is_marked = IsMarked(referent);
1387 if (!is_marked && ((++counter) & 1)) {
1388 // Referent is white and biased toward saving, mark it.
1389 MarkObject(referent);
1390 is_marked = true;
1391 }
1392 if (!is_marked) {
1393 // Referent is white, queue it for clearing.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001394 heap_->EnqueuePendingReference(ref, &clear);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001395 }
1396 }
1397 *list = clear;
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001398 timings_.EndSplit();
1399
Carl Shapiro69759ea2011-07-21 18:13:35 -07001400 // Restart the mark with the newly black references added to the
1401 // root set.
1402 ProcessMarkStack();
1403}
1404
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001405inline bool MarkSweep::IsMarked(const Object* object) const
1406 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
Mathieu Chartier9642c962013-08-05 17:40:36 -07001407 if (IsImmune(object)) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001408 return true;
1409 }
1410 DCHECK(current_mark_bitmap_ != NULL);
1411 if (current_mark_bitmap_->HasAddress(object)) {
1412 return current_mark_bitmap_->Test(object);
1413 }
1414 return heap_->GetMarkBitmap()->Test(object);
1415}
1416
1417
Carl Shapiro69759ea2011-07-21 18:13:35 -07001418// Unlink the reference list clearing references objects with white
1419// referents. Cleared references registered to a reference queue are
1420// scheduled for appending by the heap worker thread.
1421void MarkSweep::ClearWhiteReferences(Object** list) {
1422 DCHECK(list != NULL);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001423 while (*list != NULL) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001424 Object* ref = heap_->DequeuePendingReference(list);
1425 Object* referent = heap_->GetReferenceReferent(ref);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001426 if (referent != NULL && !IsMarked(referent)) {
1427 // Referent is white, clear it.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001428 heap_->ClearReferenceReferent(ref);
1429 if (heap_->IsEnqueuable(ref)) {
1430 heap_->EnqueueReference(ref, &cleared_reference_list_);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001431 }
1432 }
1433 }
1434 DCHECK(*list == NULL);
1435}
1436
1437// Enqueues finalizer references with white referents. White
1438// referents are blackened, moved to the zombie field, and the
1439// referent field is cleared.
1440void MarkSweep::EnqueueFinalizerReferences(Object** list) {
1441 DCHECK(list != NULL);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001442 timings_.StartSplit("EnqueueFinalizerReferences");
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001443 MemberOffset zombie_offset = heap_->GetFinalizerReferenceZombieOffset();
Carl Shapiro69759ea2011-07-21 18:13:35 -07001444 bool has_enqueued = false;
1445 while (*list != NULL) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001446 Object* ref = heap_->DequeuePendingReference(list);
1447 Object* referent = heap_->GetReferenceReferent(ref);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001448 if (referent != NULL && !IsMarked(referent)) {
1449 MarkObject(referent);
1450 // If the referent is non-null the reference must queuable.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001451 DCHECK(heap_->IsEnqueuable(ref));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001452 ref->SetFieldObject(zombie_offset, referent, false);
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001453 heap_->ClearReferenceReferent(ref);
1454 heap_->EnqueueReference(ref, &cleared_reference_list_);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001455 has_enqueued = true;
1456 }
1457 }
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001458 timings_.EndSplit();
Carl Shapiro69759ea2011-07-21 18:13:35 -07001459 if (has_enqueued) {
1460 ProcessMarkStack();
1461 }
1462 DCHECK(*list == NULL);
1463}
1464
Carl Shapiro58551df2011-07-24 03:09:51 -07001465// Process reference class instances and schedule finalizations.
Carl Shapiro69759ea2011-07-21 18:13:35 -07001466void MarkSweep::ProcessReferences(Object** soft_references, bool clear_soft,
1467 Object** weak_references,
1468 Object** finalizer_references,
1469 Object** phantom_references) {
1470 DCHECK(soft_references != NULL);
1471 DCHECK(weak_references != NULL);
1472 DCHECK(finalizer_references != NULL);
1473 DCHECK(phantom_references != NULL);
1474
1475 // Unless we are in the zygote or required to clear soft references
1476 // with white references, preserve some white referents.
Ian Rogers2945e242012-06-03 14:45:16 -07001477 if (!clear_soft && !Runtime::Current()->IsZygote()) {
Carl Shapiro69759ea2011-07-21 18:13:35 -07001478 PreserveSomeSoftReferences(soft_references);
1479 }
1480
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001481 timings_.StartSplit("ProcessReferences");
Carl Shapiro69759ea2011-07-21 18:13:35 -07001482 // Clear all remaining soft and weak references with white
1483 // referents.
1484 ClearWhiteReferences(soft_references);
1485 ClearWhiteReferences(weak_references);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001486 timings_.EndSplit();
Carl Shapiro69759ea2011-07-21 18:13:35 -07001487
1488 // Preserve all white objects with finalize methods and schedule
1489 // them for finalization.
1490 EnqueueFinalizerReferences(finalizer_references);
1491
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001492 timings_.StartSplit("ProcessReferences");
Carl Shapiro69759ea2011-07-21 18:13:35 -07001493 // Clear all f-reachable soft and weak references with white
1494 // referents.
1495 ClearWhiteReferences(soft_references);
1496 ClearWhiteReferences(weak_references);
1497
1498 // Clear all phantom references with white referents.
1499 ClearWhiteReferences(phantom_references);
1500
1501 // At this point all reference lists should be empty.
1502 DCHECK(*soft_references == NULL);
1503 DCHECK(*weak_references == NULL);
1504 DCHECK(*finalizer_references == NULL);
1505 DCHECK(*phantom_references == NULL);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001506 timings_.EndSplit();
Carl Shapiro69759ea2011-07-21 18:13:35 -07001507}
1508
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001509void MarkSweep::UnBindBitmaps() {
Anwar Ghuloum46543222013-08-12 09:28:42 -07001510 base::TimingLogger::ScopedSplit split("UnBindBitmaps", &timings_);
Ian Rogers1d54e732013-05-02 21:10:01 -07001511 const std::vector<space::ContinuousSpace*>& spaces = GetHeap()->GetContinuousSpaces();
1512 // TODO: C++0x
1513 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
1514 for (It it = spaces.begin(), end = spaces.end(); it != end; ++it) {
1515 space::ContinuousSpace* space = *it;
1516 if (space->IsDlMallocSpace()) {
1517 space::DlMallocSpace* alloc_space = space->AsDlMallocSpace();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001518 if (alloc_space->temp_bitmap_.get() != NULL) {
1519 // At this point, the temp_bitmap holds our old mark bitmap.
Ian Rogers1d54e732013-05-02 21:10:01 -07001520 accounting::SpaceBitmap* new_bitmap = alloc_space->temp_bitmap_.release();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001521 GetHeap()->GetMarkBitmap()->ReplaceBitmap(alloc_space->mark_bitmap_.get(), new_bitmap);
1522 CHECK_EQ(alloc_space->mark_bitmap_.release(), alloc_space->live_bitmap_.get());
1523 alloc_space->mark_bitmap_.reset(new_bitmap);
1524 DCHECK(alloc_space->temp_bitmap_.get() == NULL);
1525 }
1526 }
1527 }
1528}
1529
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001530void MarkSweep::FinishPhase() {
Anwar Ghuloum46543222013-08-12 09:28:42 -07001531 base::TimingLogger::ScopedSplit split("FinishPhase", &timings_);
1532 // Can't enqueue references if we hold the mutator lock.
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001533 Object* cleared_references = GetClearedReferences();
Ian Rogers1d54e732013-05-02 21:10:01 -07001534 Heap* heap = GetHeap();
Anwar Ghuloum46543222013-08-12 09:28:42 -07001535 timings_.NewSplit("EnqueueClearedReferences");
Ian Rogers1d54e732013-05-02 21:10:01 -07001536 heap->EnqueueClearedReferences(&cleared_references);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001537
Anwar Ghuloum46543222013-08-12 09:28:42 -07001538 timings_.NewSplit("PostGcVerification");
Ian Rogers1d54e732013-05-02 21:10:01 -07001539 heap->PostGcVerification(this);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001540
Anwar Ghuloum46543222013-08-12 09:28:42 -07001541 timings_.NewSplit("GrowForUtilization");
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07001542 heap->GrowForUtilization(GetGcType(), GetDurationNs());
Mathieu Chartier65db8802012-11-20 12:36:46 -08001543
Anwar Ghuloum46543222013-08-12 09:28:42 -07001544 timings_.NewSplit("RequestHeapTrim");
Ian Rogers1d54e732013-05-02 21:10:01 -07001545 heap->RequestHeapTrim();
Mathieu Chartier65db8802012-11-20 12:36:46 -08001546
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001547 // Update the cumulative statistics
Ian Rogers1d54e732013-05-02 21:10:01 -07001548 total_time_ns_ += GetDurationNs();
1549 total_paused_time_ns_ += std::accumulate(GetPauseTimes().begin(), GetPauseTimes().end(), 0,
1550 std::plus<uint64_t>());
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001551 total_freed_objects_ += GetFreedObjects();
1552 total_freed_bytes_ += GetFreedBytes();
1553
1554 // Ensure that the mark stack is empty.
1555 CHECK(mark_stack_->IsEmpty());
1556
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001557 if (kCountScannedTypes) {
1558 VLOG(gc) << "MarkSweep scanned classes=" << class_count_ << " arrays=" << array_count_
1559 << " other=" << other_count_;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001560 }
1561
1562 if (kCountTasks) {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001563 VLOG(gc) << "Total number of work chunks allocated: " << work_chunks_created_;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001564 }
1565
1566 if (kMeasureOverhead) {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001567 VLOG(gc) << "Overhead time " << PrettyDuration(overhead_time_);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001568 }
1569
1570 if (kProfileLargeObjects) {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001571 VLOG(gc) << "Large objects tested " << large_object_test_ << " marked " << large_object_mark_;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001572 }
1573
1574 if (kCountClassesMarked) {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001575 VLOG(gc) << "Classes marked " << classes_marked_;
1576 }
1577
1578 if (kCountJavaLangRefs) {
1579 VLOG(gc) << "References scanned " << reference_count_;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001580 }
1581
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001582 // Update the cumulative loggers.
1583 cumulative_timings_.Start();
Anwar Ghuloum6f28d912013-07-24 15:02:53 -07001584 cumulative_timings_.AddLogger(timings_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001585 cumulative_timings_.End();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001586
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001587 // Clear all of the spaces' mark bitmaps.
Ian Rogers1d54e732013-05-02 21:10:01 -07001588 const std::vector<space::ContinuousSpace*>& spaces = GetHeap()->GetContinuousSpaces();
1589 // TODO: C++0x
1590 typedef std::vector<space::ContinuousSpace*>::const_iterator It;
1591 for (It it = spaces.begin(), end = spaces.end(); it != end; ++it) {
1592 space::ContinuousSpace* space = *it;
1593 if (space->GetGcRetentionPolicy() != space::kGcRetentionPolicyNeverCollect) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001594 space->GetMarkBitmap()->Clear();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001595 }
1596 }
Mathieu Chartier5301cd22012-05-31 12:11:36 -07001597 mark_stack_->Reset();
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001598
1599 // Reset the marked large objects.
Ian Rogers1d54e732013-05-02 21:10:01 -07001600 space::LargeObjectSpace* large_objects = GetHeap()->GetLargeObjectsSpace();
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001601 large_objects->GetMarkObjects()->Clear();
Carl Shapiro69759ea2011-07-21 18:13:35 -07001602}
1603
Ian Rogers1d54e732013-05-02 21:10:01 -07001604} // namespace collector
1605} // namespace gc
Carl Shapiro69759ea2011-07-21 18:13:35 -07001606} // namespace art