blob: 25b4b7835697a9f4bf3d50d153439dcbad017145 [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"
Mathieu Chartier357e9be2012-08-01 11:00:14 -070028#include "card_table.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080029#include "card_table-inl.h"
Carl Shapiro58551df2011-07-24 03:09:51 -070030#include "heap.h"
Elliott Hughes410c0c82011-09-01 17:58:25 -070031#include "indirect_reference_table.h"
32#include "intern_table.h"
Ian Rogers81d425b2012-09-27 16:03:43 -070033#include "jni_internal.h"
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -070034#include "large_object_space.h"
Elliott Hughesc33a32b2011-10-11 18:18:07 -070035#include "monitor.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080036#include "mark_sweep-inl.h"
37#include "mirror/class-inl.h"
38#include "mirror/class_loader.h"
39#include "mirror/dex_cache.h"
40#include "mirror/field.h"
41#include "mirror/field-inl.h"
42#include "mirror/object-inl.h"
43#include "mirror/object_array.h"
44#include "mirror/object_array-inl.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070045#include "runtime.h"
Carl Shapiro58551df2011-07-24 03:09:51 -070046#include "space.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080047#include "space_bitmap-inl.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070048#include "thread.h"
Mathieu Chartier6f1c9492012-10-15 12:08:41 -070049#include "thread_list.h"
Ian Rogers08254272012-10-23 17:49:23 -070050#include "verifier/method_verifier.h"
Carl Shapiro69759ea2011-07-21 18:13:35 -070051
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080052using namespace art::mirror;
53
Carl Shapiro69759ea2011-07-21 18:13:35 -070054namespace art {
55
Mathieu Chartier02b6a782012-10-26 13:51:26 -070056// Performance options.
57static const bool kParallelMarkStack = true;
Mathieu Chartier2b82db42012-11-14 17:29:05 -080058static const bool kDisableFinger = kParallelMarkStack;
Mathieu Chartier858f1c52012-10-17 17:45:55 -070059static const bool kUseMarkStackPrefetch = true;
60
Mathieu Chartier02b6a782012-10-26 13:51:26 -070061// Profiling and information flags.
62static const bool kCountClassesMarked = false;
63static const bool kProfileLargeObjects = false;
64static const bool kMeasureOverhead = false;
65static const bool kCountTasks = false;
Mathieu Chartierd22d5482012-11-06 17:14:12 -080066static const bool kCountJavaLangRefs = false;
Mathieu Chartier02b6a782012-10-26 13:51:26 -070067
Mathieu Chartier357e9be2012-08-01 11:00:14 -070068class SetFingerVisitor {
69 public:
70 SetFingerVisitor(MarkSweep* const mark_sweep) : mark_sweep_(mark_sweep) {
71
72 }
73
74 void operator ()(void* finger) const {
75 mark_sweep_->SetFinger(reinterpret_cast<Object*>(finger));
76 }
77
78 private:
79 MarkSweep* const mark_sweep_;
80};
81
Mathieu Chartier2b82db42012-11-14 17:29:05 -080082std::string MarkSweep::GetName() const {
83 std::ostringstream ss;
84 ss << (IsConcurrent() ? "Concurrent" : "") << GetGcType();
85 return ss.str();
Mathieu Chartier5301cd22012-05-31 12:11:36 -070086}
Elliott Hughesb3bd5f02012-03-08 21:05:27 -080087
Mathieu Chartier2b82db42012-11-14 17:29:05 -080088void MarkSweep::ImmuneSpace(ContinuousSpace* space) {
89 // Bind live to mark bitmap if necessary.
90 if (space->GetLiveBitmap() != space->GetMarkBitmap()) {
91 BindLiveToMarkBitmap(space);
92 }
93
94 // Add the space to the immune region.
95 if (immune_begin_ == NULL) {
96 DCHECK(immune_end_ == NULL);
97 SetImmuneRange(reinterpret_cast<Object*>(space->Begin()),
98 reinterpret_cast<Object*>(space->End()));
99 } else {
100 const Spaces& spaces = GetHeap()->GetSpaces();
101 const ContinuousSpace* prev_space = NULL;
102 // Find out if the previous space is immune.
103 // TODO: C++0x
104 for (Spaces::const_iterator it = spaces.begin(); it != spaces.end(); ++it) {
105 if (*it == space) {
106 break;
107 }
108 prev_space = *it;
109 }
110
111 // If previous space was immune, then extend the immune region.
112 if (prev_space != NULL &&
113 immune_begin_ <= reinterpret_cast<Object*>(prev_space->Begin()) &&
114 immune_end_ >= reinterpret_cast<Object*>(prev_space->End())) {
115 immune_begin_ = std::min(reinterpret_cast<Object*>(space->Begin()), immune_begin_);
116 immune_end_ = std::max(reinterpret_cast<Object*>(space->End()), immune_end_);
117 }
118 }
119}
120
121// Bind the live bits to the mark bits of bitmaps based on the gc type.
122void MarkSweep::BindBitmaps() {
123 Spaces& spaces = GetHeap()->GetSpaces();
124 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
125
126 // Mark all of the spaces we never collect as immune.
127 for (Spaces::iterator it = spaces.begin(); it != spaces.end(); ++it) {
128 ContinuousSpace* space = *it;
129 if (space->GetGcRetentionPolicy() == kGcRetentionPolicyNeverCollect) {
130 ImmuneSpace(space);
131 }
132 }
133}
134
135MarkSweep::MarkSweep(Heap* heap, bool is_concurrent)
136 : GarbageCollector(heap),
137 gc_barrier_(new Barrier(0)),
Ian Rogers62d6c772013-02-27 08:32:07 -0800138 large_object_lock_("mark sweep large object lock", kMarkSweepLargeObjectLock),
139 mark_stack_expand_lock_("mark sweep mark stack expand lock"),
Ian Rogers1bd4b4c2013-04-18 17:47:42 -0700140 is_concurrent_(is_concurrent),
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800141 timings_(GetName(), true),
Ian Rogers1bd4b4c2013-04-18 17:47:42 -0700142 cumulative_timings_(GetName()) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800143 cumulative_timings_.SetName(GetName());
144 ResetCumulativeStatistics();
145}
146
147void MarkSweep::InitializePhase() {
148 mark_stack_ = GetHeap()->mark_stack_.get();
149 DCHECK(mark_stack_ != NULL);
150 finger_ = NULL;
151 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);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700171 FindDefaultMarkBitmap();
Mathieu Chartier9ebae1f2012-10-15 17:38:16 -0700172 // Mark any concurrent roots as dirty since we need to scan them at least once during this GC.
173 Runtime::Current()->DirtyRoots();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800174 timings_.Reset();
175 // Do any pre GC verification.
176 heap_->PreGcVerification(this);
177}
178
179void MarkSweep::ProcessReferences(Thread* self) {
Mathieu Chartier8e56c7e2012-11-20 13:25:50 -0800180 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800181 ProcessReferences(&soft_reference_list_, clear_soft_references_, &weak_reference_list_,
182 &finalizer_reference_list_, &phantom_reference_list_);
183 timings_.AddSplit("ProcessReferences");
184}
185
186bool MarkSweep::HandleDirtyObjectsPhase() {
187 Thread* self = Thread::Current();
188 ObjectStack* allocation_stack = GetHeap()->allocation_stack_.get();
189 Locks::mutator_lock_->AssertExclusiveHeld(self);
190
191 {
192 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
193
194 // Re-mark root set.
195 ReMarkRoots();
196 timings_.AddSplit("ReMarkRoots");
197
198 // Scan dirty objects, this is only required if we are not doing concurrent GC.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800199 RecursiveMarkDirtyObjects(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.
209 SweepArray(timings_, allocation_stack, false);
210 } else {
211 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
212 // We only sweep over the live stack, and the live stack should not intersect with the
213 // allocation stack, so it should be safe to UnMark anything in the allocation stack as live.
214 heap_->UnMarkAllocStack(GetHeap()->alloc_space_->GetMarkBitmap(),
215 GetHeap()->large_object_space_->GetMarkObjects(),
216 allocation_stack);
217 timings_.AddSplit("UnMarkAllocStack");
218 }
219 return true;
220}
221
222bool MarkSweep::IsConcurrent() const {
223 return is_concurrent_;
224}
225
226void MarkSweep::MarkingPhase() {
227 Heap* heap = GetHeap();
228 Thread* self = Thread::Current();
229
230 BindBitmaps();
231 FindDefaultMarkBitmap();
232 timings_.AddSplit("BindBitmaps");
233
234 // Process dirty cards and add dirty cards to mod union tables.
235 heap->ProcessCards(timings_);
236
237 // Need to do this before the checkpoint since we don't want any threads to add references to
238 // the live stack during the recursive mark.
239 heap->SwapStacks();
240 timings_.AddSplit("SwapStacks");
241
242 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
243 if (Locks::mutator_lock_->IsExclusiveHeld(self)) {
244 // If we exclusively hold the mutator lock, all threads must be suspended.
245 MarkRoots();
246 timings_.AddSplit("MarkConcurrentRoots");
247 } else {
248 MarkRootsCheckpoint();
249 timings_.AddSplit("MarkRootsCheckpoint");
250 MarkNonThreadRoots();
251 timings_.AddSplit("MarkNonThreadRoots");
252 }
253 MarkConcurrentRoots();
254 timings_.AddSplit("MarkConcurrentRoots");
255
256 heap->UpdateAndMarkModUnion(this, timings_, GetGcType());
257 MarkReachableObjects();
258}
259
260void MarkSweep::MarkReachableObjects() {
261 // Mark everything allocated since the last as GC live so that we can sweep concurrently,
262 // knowing that new allocations won't be marked as live.
263 ObjectStack* live_stack = heap_->GetLiveStack();
264 heap_->MarkAllocStack(heap_->alloc_space_->GetLiveBitmap(),
265 heap_->large_object_space_->GetLiveObjects(),
266 live_stack);
267 live_stack->Reset();
268 timings_.AddSplit("MarkStackAsLive");
269 // Recursively mark all the non-image bits set in the mark bitmap.
270 RecursiveMark();
271 DisableFinger();
272}
273
274void MarkSweep::ReclaimPhase() {
275 Thread* self = Thread::Current();
276
277 if (!IsConcurrent()) {
278 ProcessReferences(self);
279 }
280
281 // Before freeing anything, lets verify the heap.
282 if (kIsDebugBuild) {
283 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
284 VerifyImageRoots();
285 }
286 heap_->PreSweepingGcVerification(this);
287
288 {
289 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
290
291 // Reclaim unmarked objects.
292 Sweep(timings_, false);
293
294 // Swap the live and mark bitmaps for each space which we modified space. This is an
295 // optimization that enables us to not clear live bits inside of the sweep. Only swaps unbound
296 // bitmaps.
297 SwapBitmaps();
298 timings_.AddSplit("SwapBitmaps");
299
300 // Unbind the live and mark bitmaps.
301 UnBindBitmaps();
302 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800303}
304
305void MarkSweep::SwapBitmaps() {
306 // Swap the live and mark bitmaps for each alloc space. This is needed since sweep re-swaps
307 // these bitmaps. The bitmap swapping is an optimization so that we do not need to clear the live
308 // bits of dead objects in the live bitmap.
309 const GcType gc_type = GetGcType();
310 // TODO: C++0x
311 Spaces& spaces = heap_->GetSpaces();
312 for (Spaces::iterator it = spaces.begin(); it != spaces.end(); ++it) {
313 ContinuousSpace* space = *it;
314 // We never allocate into zygote spaces.
315 if (space->GetGcRetentionPolicy() == kGcRetentionPolicyAlwaysCollect ||
316 (gc_type == kGcTypeFull &&
317 space->GetGcRetentionPolicy() == kGcRetentionPolicyFullCollect)) {
318 SpaceBitmap* live_bitmap = space->GetLiveBitmap();
319 SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
320 if (live_bitmap != mark_bitmap) {
321 heap_->GetLiveBitmap()->ReplaceBitmap(live_bitmap, mark_bitmap);
322 heap_->GetMarkBitmap()->ReplaceBitmap(mark_bitmap, live_bitmap);
323 space->AsAllocSpace()->SwapBitmaps();
324 }
325 }
326 }
327 SwapLargeObjects();
328}
329
330void MarkSweep::SwapLargeObjects() {
331 LargeObjectSpace* large_object_space = heap_->GetLargeObjectsSpace();
332 large_object_space->SwapBitmaps();
333 heap_->GetLiveBitmap()->SetLargeObjects(large_object_space->GetLiveObjects());
334 heap_->GetMarkBitmap()->SetLargeObjects(large_object_space->GetMarkObjects());
335}
336
337void MarkSweep::SetImmuneRange(Object* begin, Object* end) {
338 immune_begin_ = begin;
339 immune_end_ = end;
Carl Shapiro58551df2011-07-24 03:09:51 -0700340}
341
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700342void MarkSweep::FindDefaultMarkBitmap() {
343 const Spaces& spaces = heap_->GetSpaces();
344 for (Spaces::const_iterator it = spaces.begin(); it != spaces.end(); ++it) {
345 if ((*it)->GetGcRetentionPolicy() == kGcRetentionPolicyAlwaysCollect) {
346 current_mark_bitmap_ = (*it)->GetMarkBitmap();
347 CHECK(current_mark_bitmap_ != NULL);
348 return;
349 }
350 }
351 GetHeap()->DumpSpaces();
352 LOG(FATAL) << "Could not find a default mark bitmap";
353}
354
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800355void MarkSweep::ExpandMarkStack() {
356 // Rare case, no need to have Thread::Current be a parameter.
357 MutexLock mu(Thread::Current(), mark_stack_expand_lock_);
358 if (UNLIKELY(mark_stack_->Size() < mark_stack_->Capacity())) {
359 // Someone else acquired the lock and expanded the mark stack before us.
360 return;
361 }
362 std::vector<Object*> temp;
363 temp.insert(temp.begin(), mark_stack_->Begin(), mark_stack_->End());
364 mark_stack_->Resize(mark_stack_->Capacity() * 2);
365 for (size_t i = 0; i < temp.size(); ++i) {
366 mark_stack_->PushBack(temp[i]);
367 }
368}
369
370inline void MarkSweep::MarkObjectNonNullParallel(const Object* obj, bool check_finger) {
371 DCHECK(obj != NULL);
372 if (MarkObjectParallel(obj)) {
373 if (kDisableFinger || (check_finger && obj < finger_)) {
374 while (UNLIKELY(!mark_stack_->AtomicPushBack(const_cast<Object*>(obj)))) {
375 // Only reason a push can fail is that the mark stack is full.
376 ExpandMarkStack();
377 }
378 }
379 }
380}
381
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700382inline void MarkSweep::MarkObjectNonNull(const Object* obj, bool check_finger) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700383 DCHECK(obj != NULL);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700384
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700385 if (obj >= immune_begin_ && obj < immune_end_) {
386 DCHECK(IsMarked(obj));
Carl Shapiro69759ea2011-07-21 18:13:35 -0700387 return;
388 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700389
390 // Try to take advantage of locality of references within a space, failing this find the space
391 // the hard way.
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700392 SpaceBitmap* object_bitmap = current_mark_bitmap_;
393 if (UNLIKELY(!object_bitmap->HasAddress(obj))) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700394 SpaceBitmap* new_bitmap = heap_->GetMarkBitmap()->GetSpaceBitmap(obj);
395 if (new_bitmap != NULL) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700396 object_bitmap = new_bitmap;
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700397 } else {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700398 MarkLargeObject(obj);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700399 return;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700400 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700401 }
402
Carl Shapiro69759ea2011-07-21 18:13:35 -0700403 // This object was not previously marked.
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700404 if (!object_bitmap->Test(obj)) {
405 object_bitmap->Set(obj);
406 if (kDisableFinger || (check_finger && obj < finger_)) {
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700407 // Do we need to expand the mark stack?
408 if (UNLIKELY(mark_stack_->Size() >= mark_stack_->Capacity())) {
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800409 ExpandMarkStack();
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700410 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700411 // The object must be pushed on to the mark stack.
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700412 mark_stack_->PushBack(const_cast<Object*>(obj));
Carl Shapiro69759ea2011-07-21 18:13:35 -0700413 }
414 }
415}
416
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700417// Rare case, probably not worth inlining since it will increase instruction cache miss rate.
418bool MarkSweep::MarkLargeObject(const Object* obj) {
419 LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
420 SpaceSetMap* large_objects = large_object_space->GetMarkObjects();
421 if (kProfileLargeObjects) {
422 ++large_object_test_;
423 }
424 if (UNLIKELY(!large_objects->Test(obj))) {
425 if (!large_object_space->Contains(obj)) {
426 LOG(ERROR) << "Tried to mark " << obj << " not contained by any spaces";
427 LOG(ERROR) << "Attempting see if it's a bad root";
428 VerifyRoots();
429 LOG(FATAL) << "Can't mark bad root";
430 }
431 if (kProfileLargeObjects) {
432 ++large_object_mark_;
433 }
434 large_objects->Set(obj);
435 // Don't need to check finger since large objects never have any object references.
436 return true;
437 }
438 return false;
439}
440
441inline bool MarkSweep::MarkObjectParallel(const Object* obj) {
442 DCHECK(obj != NULL);
443
444 if (obj >= immune_begin_ && obj < immune_end_) {
445 DCHECK(IsMarked(obj));
446 return false;
447 }
448
449 // Try to take advantage of locality of references within a space, failing this find the space
450 // the hard way.
451 SpaceBitmap* object_bitmap = current_mark_bitmap_;
452 if (UNLIKELY(!object_bitmap->HasAddress(obj))) {
453 SpaceBitmap* new_bitmap = heap_->GetMarkBitmap()->GetSpaceBitmap(obj);
454 if (new_bitmap != NULL) {
455 object_bitmap = new_bitmap;
456 } else {
457 // TODO: Remove the Thread::Current here?
458 // TODO: Convert this to some kind of atomic marking?
459 MutexLock mu(Thread::Current(), large_object_lock_);
460 return MarkLargeObject(obj);
461 }
462 }
463
464 // Return true if the object was not previously marked.
465 return !object_bitmap->AtomicTestAndSet(obj);
466}
467
Carl Shapiro69759ea2011-07-21 18:13:35 -0700468// Used to mark objects when recursing. Recursion is done by moving
469// the finger across the bitmaps in address order and marking child
470// objects. Any newly-marked objects whose addresses are lower than
471// the finger won't be visited by the bitmap scan, so those objects
472// need to be added to the mark stack.
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700473void MarkSweep::MarkObject(const Object* obj) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700474 if (obj != NULL) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700475 MarkObjectNonNull(obj, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700476 }
477}
478
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800479void MarkSweep::MarkRoot(const Object* obj) {
480 if (obj != NULL) {
481 MarkObjectNonNull(obj, false);
482 }
483}
484
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800485void MarkSweep::MarkRootParallelCallback(const Object* root, void* arg) {
486 DCHECK(root != NULL);
487 DCHECK(arg != NULL);
488 MarkSweep* mark_sweep = reinterpret_cast<MarkSweep*>(arg);
489 mark_sweep->MarkObjectNonNullParallel(root, false);
490}
491
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700492void MarkSweep::MarkObjectCallback(const Object* root, void* arg) {
Brian Carlstrom1f870082011-08-23 16:02:11 -0700493 DCHECK(root != NULL);
494 DCHECK(arg != NULL);
495 MarkSweep* mark_sweep = reinterpret_cast<MarkSweep*>(arg);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700496 mark_sweep->MarkObjectNonNull(root, false);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700497}
498
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700499void MarkSweep::ReMarkObjectVisitor(const Object* root, void* arg) {
500 DCHECK(root != NULL);
501 DCHECK(arg != NULL);
502 MarkSweep* mark_sweep = reinterpret_cast<MarkSweep*>(arg);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700503 mark_sweep->MarkObjectNonNull(root, true);
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700504}
505
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700506void MarkSweep::VerifyRootCallback(const Object* root, void* arg, size_t vreg,
Ian Rogers40e3bac2012-11-20 00:09:14 -0800507 const StackVisitor* visitor) {
508 reinterpret_cast<MarkSweep*>(arg)->VerifyRoot(root, vreg, visitor);
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700509}
510
Ian Rogers40e3bac2012-11-20 00:09:14 -0800511void MarkSweep::VerifyRoot(const Object* root, size_t vreg, const StackVisitor* visitor) {
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700512 // See if the root is on any space bitmap.
Mathieu Chartier128c52c2012-10-16 14:12:41 -0700513 if (GetHeap()->GetLiveBitmap()->GetSpaceBitmap(root) == NULL) {
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700514 LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
Mathieu Chartier4202b742012-10-17 17:51:25 -0700515 if (!large_object_space->Contains(root)) {
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700516 LOG(ERROR) << "Found invalid root: " << root;
Ian Rogers40e3bac2012-11-20 00:09:14 -0800517 if (visitor != NULL) {
518 LOG(ERROR) << visitor->DescribeLocation() << " in VReg: " << vreg;
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700519 }
520 }
521 }
522}
523
524void MarkSweep::VerifyRoots() {
525 Runtime::Current()->GetThreadList()->VerifyRoots(VerifyRootCallback, this);
526}
527
Carl Shapiro69759ea2011-07-21 18:13:35 -0700528// Marks all objects in the root set.
529void MarkSweep::MarkRoots() {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700530 Runtime::Current()->VisitNonConcurrentRoots(MarkObjectCallback, this);
Mathieu Chartier9ebae1f2012-10-15 17:38:16 -0700531}
532
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700533void MarkSweep::MarkNonThreadRoots() {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700534 Runtime::Current()->VisitNonThreadRoots(MarkObjectCallback, this);
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700535}
536
Mathieu Chartier9ebae1f2012-10-15 17:38:16 -0700537void MarkSweep::MarkConcurrentRoots() {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700538 Runtime::Current()->VisitConcurrentRoots(MarkObjectCallback, this);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700539}
540
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700541class CheckObjectVisitor {
542 public:
543 CheckObjectVisitor(MarkSweep* const mark_sweep)
544 : mark_sweep_(mark_sweep) {
545
546 }
547
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700548 void operator ()(const Object* obj, const Object* ref, MemberOffset offset, bool is_static) const
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800549 NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800550 if (kDebugLocking) {
551 Locks::heap_bitmap_lock_->AssertSharedHeld(Thread::Current());
552 }
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700553 mark_sweep_->CheckReference(obj, ref, offset, is_static);
554 }
555
556 private:
557 MarkSweep* const mark_sweep_;
558};
559
560void MarkSweep::CheckObject(const Object* obj) {
561 DCHECK(obj != NULL);
562 CheckObjectVisitor visitor(this);
563 VisitObjectReferences(obj, visitor);
564}
565
566void MarkSweep::VerifyImageRootVisitor(Object* root, void* arg) {
567 DCHECK(root != NULL);
568 DCHECK(arg != NULL);
569 MarkSweep* mark_sweep = reinterpret_cast<MarkSweep*>(arg);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700570 DCHECK(mark_sweep->heap_->GetMarkBitmap()->Test(root));
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700571 mark_sweep->CheckObject(root);
572}
573
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700574void MarkSweep::BindLiveToMarkBitmap(ContinuousSpace* space) {
575 CHECK(space->IsAllocSpace());
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700576 DlMallocSpace* alloc_space = space->AsAllocSpace();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700577 SpaceBitmap* live_bitmap = space->GetLiveBitmap();
578 SpaceBitmap* mark_bitmap = alloc_space->mark_bitmap_.release();
579 GetHeap()->GetMarkBitmap()->ReplaceBitmap(mark_bitmap, live_bitmap);
580 alloc_space->temp_bitmap_.reset(mark_bitmap);
581 alloc_space->mark_bitmap_.reset(live_bitmap);
582}
583
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700584class ScanObjectVisitor {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700585 public:
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700586 ScanObjectVisitor(MarkSweep* const mark_sweep) : mark_sweep_(mark_sweep) {
587
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700588 }
589
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800590 // TODO: Fixme when anotatalysis works with visitors.
591 void operator ()(const Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
592 if (kDebugLocking) {
593 Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
594 Locks::heap_bitmap_lock_->AssertExclusiveHeld(Thread::Current());
595 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700596 mark_sweep_->ScanObject(obj);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700597 }
598
599 private:
600 MarkSweep* const mark_sweep_;
601};
602
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800603void MarkSweep::ScanGrayObjects(byte minimum_age) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700604 const Spaces& spaces = heap_->GetSpaces();
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700605 CardTable* card_table = heap_->GetCardTable();
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700606 ScanObjectVisitor visitor(this);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700607 SetFingerVisitor finger_visitor(this);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700608 // TODO: C++ 0x auto
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700609 for (Spaces::const_iterator it = spaces.begin(); it != spaces.end(); ++it) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700610 ContinuousSpace* space = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700611 byte* begin = space->Begin();
612 byte* end = space->End();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700613 // Image spaces are handled properly since live == marked for them.
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700614 SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800615 card_table->Scan(mark_bitmap, begin, end, visitor, VoidFunctor(), minimum_age);
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700616 }
617}
618
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700619class CheckBitmapVisitor {
620 public:
621 CheckBitmapVisitor(MarkSweep* mark_sweep) : mark_sweep_(mark_sweep) {
622
623 }
624
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700625 void operator ()(const Object* obj) const
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800626 NO_THREAD_SAFETY_ANALYSIS {
627 if (kDebugLocking) {
628 Locks::heap_bitmap_lock_->AssertSharedHeld(Thread::Current());
629 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700630 DCHECK(obj != NULL);
631 mark_sweep_->CheckObject(obj);
632 }
633
634 private:
635 MarkSweep* mark_sweep_;
636};
637
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700638void MarkSweep::VerifyImageRoots() {
639 // Verify roots ensures that all the references inside the image space point
640 // objects which are either in the image space or marked objects in the alloc
641 // space
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700642 CheckBitmapVisitor visitor(this);
643 const Spaces& spaces = heap_->GetSpaces();
644 for (Spaces::const_iterator it = spaces.begin(); it != spaces.end(); ++it) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700645 if ((*it)->IsImageSpace()) {
646 ImageSpace* space = (*it)->AsImageSpace();
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700647 uintptr_t begin = reinterpret_cast<uintptr_t>(space->Begin());
648 uintptr_t end = reinterpret_cast<uintptr_t>(space->End());
649 SpaceBitmap* live_bitmap = space->GetLiveBitmap();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700650 DCHECK(live_bitmap != NULL);
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800651 live_bitmap->VisitMarkedRange(begin, end, visitor, VoidFunctor());
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700652 }
653 }
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700654}
655
Carl Shapiro58551df2011-07-24 03:09:51 -0700656// Populates the mark stack based on the set of marked objects and
657// recursively marks until the mark stack is emptied.
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800658void MarkSweep::RecursiveMark() {
Brian Carlstrom1f870082011-08-23 16:02:11 -0700659 // RecursiveMark will build the lists of known instances of the Reference classes.
660 // See DelayReferenceReferent for details.
661 CHECK(soft_reference_list_ == NULL);
662 CHECK(weak_reference_list_ == NULL);
663 CHECK(finalizer_reference_list_ == NULL);
664 CHECK(phantom_reference_list_ == NULL);
665 CHECK(cleared_reference_list_ == NULL);
666
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800667 const bool partial = GetGcType() == kGcTypePartial;
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700668 const Spaces& spaces = heap_->GetSpaces();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700669 SetFingerVisitor set_finger_visitor(this);
670 ScanObjectVisitor scan_visitor(this);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800671 if (!kDisableFinger) {
672 finger_ = NULL;
673 for (Spaces::const_iterator it = spaces.begin(); it != spaces.end(); ++it) {
674 ContinuousSpace* space = *it;
675 if ((space->GetGcRetentionPolicy() == kGcRetentionPolicyAlwaysCollect) ||
676 (!partial && space->GetGcRetentionPolicy() == kGcRetentionPolicyFullCollect)
677 ) {
678 current_mark_bitmap_ = space->GetMarkBitmap();
679 if (current_mark_bitmap_ == NULL) {
680 GetHeap()->DumpSpaces();
681 LOG(FATAL) << "invalid bitmap";
682 }
683 // This function does not handle heap end increasing, so we must use the space end.
684 uintptr_t begin = reinterpret_cast<uintptr_t>(space->Begin());
685 uintptr_t end = reinterpret_cast<uintptr_t>(space->End());
686 current_mark_bitmap_->VisitMarkedRange(begin, end, scan_visitor, set_finger_visitor);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700687 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700688 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700689 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800690 DisableFinger();
691 timings_.AddSplit("RecursiveMark");
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700692 ProcessMarkStack();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800693 timings_.AddSplit("ProcessMarkStack");
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700694}
695
696bool MarkSweep::IsMarkedCallback(const Object* object, void* arg) {
697 return
698 reinterpret_cast<MarkSweep*>(arg)->IsMarked(object) ||
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700699 !reinterpret_cast<MarkSweep*>(arg)->GetHeap()->GetLiveBitmap()->Test(object);
700}
701
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800702void MarkSweep::RecursiveMarkDirtyObjects(byte minimum_age) {
703 ScanGrayObjects(minimum_age);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800704 timings_.AddSplit("ScanGrayObjects");
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700705 ProcessMarkStack();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800706 timings_.AddSplit("ProcessMarkStack");
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700707}
708
Carl Shapiro58551df2011-07-24 03:09:51 -0700709void MarkSweep::ReMarkRoots() {
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700710 Runtime::Current()->VisitRoots(ReMarkObjectVisitor, this);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700711}
712
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800713void MarkSweep::SweepJniWeakGlobals(IsMarkedTester is_marked, void* arg) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700714 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
Ian Rogers50b35e22012-10-04 10:09:15 -0700715 MutexLock mu(Thread::Current(), vm->weak_globals_lock);
Elliott Hughes410c0c82011-09-01 17:58:25 -0700716 IndirectReferenceTable* table = &vm->weak_globals;
Mathieu Chartier654d3a22012-07-11 17:54:18 -0700717 typedef IndirectReferenceTable::iterator It; // TODO: C++0x auto
Elliott Hughes410c0c82011-09-01 17:58:25 -0700718 for (It it = table->begin(), end = table->end(); it != end; ++it) {
719 const Object** entry = *it;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700720 if (!is_marked(*entry, arg)) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700721 *entry = kClearedJniWeakGlobal;
722 }
723 }
724}
725
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700726struct ArrayMarkedCheck {
727 ObjectStack* live_stack;
728 MarkSweep* mark_sweep;
729};
730
731// Either marked or not live.
732bool MarkSweep::IsMarkedArrayCallback(const Object* object, void* arg) {
733 ArrayMarkedCheck* array_check = reinterpret_cast<ArrayMarkedCheck*>(arg);
734 if (array_check->mark_sweep->IsMarked(object)) {
735 return true;
736 }
737 ObjectStack* live_stack = array_check->live_stack;
738 return std::find(live_stack->Begin(), live_stack->End(), object) == live_stack->End();
739}
740
741void MarkSweep::SweepSystemWeaksArray(ObjectStack* allocations) {
Mathieu Chartier46a23632012-08-07 18:44:40 -0700742 Runtime* runtime = Runtime::Current();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700743 // The callbacks check
744 // !is_marked where is_marked is the callback but we want
745 // !IsMarked && IsLive
746 // So compute !(!IsMarked && IsLive) which is equal to (IsMarked || !IsLive).
747 // Or for swapped (IsLive || !IsMarked).
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700748
749 ArrayMarkedCheck visitor;
750 visitor.live_stack = allocations;
751 visitor.mark_sweep = this;
752 runtime->GetInternTable()->SweepInternTableWeaks(IsMarkedArrayCallback, &visitor);
753 runtime->GetMonitorList()->SweepMonitorList(IsMarkedArrayCallback, &visitor);
754 SweepJniWeakGlobals(IsMarkedArrayCallback, &visitor);
755}
756
757void MarkSweep::SweepSystemWeaks() {
758 Runtime* runtime = Runtime::Current();
759 // 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).
764 runtime->GetInternTable()->SweepInternTableWeaks(IsMarkedCallback, this);
765 runtime->GetMonitorList()->SweepMonitorList(IsMarkedCallback, this);
766 SweepJniWeakGlobals(IsMarkedCallback, this);
Carl Shapiro58551df2011-07-24 03:09:51 -0700767}
768
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700769bool MarkSweep::VerifyIsLiveCallback(const Object* obj, void* arg) {
770 reinterpret_cast<MarkSweep*>(arg)->VerifyIsLive(obj);
771 // We don't actually want to sweep the object, so lets return "marked"
772 return true;
773}
774
775void MarkSweep::VerifyIsLive(const Object* obj) {
776 Heap* heap = GetHeap();
777 if (!heap->GetLiveBitmap()->Test(obj)) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700778 LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
779 if (!large_object_space->GetLiveObjects()->Test(obj)) {
780 if (std::find(heap->allocation_stack_->Begin(), heap->allocation_stack_->End(), obj) ==
781 heap->allocation_stack_->End()) {
782 // Object not found!
783 heap->DumpSpaces();
784 LOG(FATAL) << "Found dead object " << obj;
785 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700786 }
787 }
788}
789
790void MarkSweep::VerifySystemWeaks() {
791 Runtime* runtime = Runtime::Current();
792 // Verify system weaks, uses a special IsMarked callback which always returns true.
793 runtime->GetInternTable()->SweepInternTableWeaks(VerifyIsLiveCallback, this);
794 runtime->GetMonitorList()->SweepMonitorList(VerifyIsLiveCallback, this);
795
796 JavaVMExt* vm = runtime->GetJavaVM();
Ian Rogers50b35e22012-10-04 10:09:15 -0700797 MutexLock mu(Thread::Current(), vm->weak_globals_lock);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700798 IndirectReferenceTable* table = &vm->weak_globals;
799 typedef IndirectReferenceTable::iterator It; // TODO: C++0x auto
800 for (It it = table->begin(), end = table->end(); it != end; ++it) {
801 const Object** entry = *it;
802 VerifyIsLive(*entry);
803 }
804}
805
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800806struct SweepCallbackContext {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700807 MarkSweep* mark_sweep;
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800808 AllocSpace* space;
Ian Rogers50b35e22012-10-04 10:09:15 -0700809 Thread* self;
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800810};
811
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700812class CheckpointMarkThreadRoots : public Closure {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700813 public:
814 CheckpointMarkThreadRoots(MarkSweep* mark_sweep) : mark_sweep_(mark_sweep) {
815
816 }
817
818 virtual void Run(Thread* thread) NO_THREAD_SAFETY_ANALYSIS {
819 // Note: self is not necessarily equal to thread since thread may be suspended.
820 Thread* self = Thread::Current();
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800821 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
822 << thread->GetState() << " thread " << thread << " self " << self;
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800823 thread->VisitRoots(MarkSweep::MarkRootParallelCallback, mark_sweep_);
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700824 mark_sweep_->GetBarrier().Pass(self);
825 }
826
827 private:
828 MarkSweep* mark_sweep_;
829};
830
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800831void MarkSweep::ResetCumulativeStatistics() {
832 cumulative_timings_.Reset();
833 total_time_ = 0;
834 total_paused_time_ = 0;
835 total_freed_objects_ = 0;
836 total_freed_bytes_ = 0;
837}
838
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700839void MarkSweep::MarkRootsCheckpoint() {
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800840 CheckpointMarkThreadRoots check_point(this);
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700841 ThreadList* thread_list = Runtime::Current()->GetThreadList();
842 // Increment the count of the barrier. If all of the checkpoints have already been finished then
843 // will hit 0 and continue. Otherwise we are still waiting for some checkpoints, so the counter
844 // will go positive and we will unblock when it hits zero.
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800845 gc_barrier_->Increment(Thread::Current(), thread_list->RunCheckpoint(&check_point));
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700846}
847
Ian Rogers30fab402012-01-23 15:43:46 -0800848void MarkSweep::SweepCallback(size_t num_ptrs, Object** ptrs, void* arg) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800849 SweepCallbackContext* context = static_cast<SweepCallbackContext*>(arg);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700850 MarkSweep* mark_sweep = context->mark_sweep;
851 Heap* heap = mark_sweep->GetHeap();
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800852 AllocSpace* space = context->space;
Ian Rogers50b35e22012-10-04 10:09:15 -0700853 Thread* self = context->self;
854 Locks::heap_bitmap_lock_->AssertExclusiveHeld(self);
Ian Rogers5d76c432011-10-31 21:42:49 -0700855 // Use a bulk free, that merges consecutive objects before freeing or free per object?
856 // Documentation suggests better free performance with merging, but this may be at the expensive
857 // of allocation.
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700858 size_t freed_objects = num_ptrs;
859 // AllocSpace::FreeList clears the value in ptrs, so perform after clearing the live bit
860 size_t freed_bytes = space->FreeList(self, num_ptrs, ptrs);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700861 heap->RecordFree(freed_objects, freed_bytes);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700862 mark_sweep->freed_objects_ += freed_objects;
863 mark_sweep->freed_bytes_ += freed_bytes;
Carl Shapiro58551df2011-07-24 03:09:51 -0700864}
865
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700866void MarkSweep::ZygoteSweepCallback(size_t num_ptrs, Object** ptrs, void* arg) {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700867 SweepCallbackContext* context = static_cast<SweepCallbackContext*>(arg);
Ian Rogers50b35e22012-10-04 10:09:15 -0700868 Locks::heap_bitmap_lock_->AssertExclusiveHeld(context->self);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700869 Heap* heap = context->mark_sweep->GetHeap();
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700870 // We don't free any actual memory to avoid dirtying the shared zygote pages.
871 for (size_t i = 0; i < num_ptrs; ++i) {
872 Object* obj = static_cast<Object*>(ptrs[i]);
873 heap->GetLiveBitmap()->Clear(obj);
874 heap->GetCardTable()->MarkCard(obj);
875 }
876}
877
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700878void MarkSweep::SweepArray(TimingLogger& logger, ObjectStack* allocations, bool swap_bitmaps) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700879 size_t freed_bytes = 0;
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700880 DlMallocSpace* space = heap_->GetAllocSpace();
Elliott Hughes2da50362011-10-10 16:57:08 -0700881
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700882 // If we don't swap bitmaps then newly allocated Weaks go into the live bitmap but not mark
883 // bitmap, resulting in occasional frees of Weaks which are still in use.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700884 SweepSystemWeaksArray(allocations);
885 logger.AddSplit("SweepSystemWeaks");
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700886
887 // Newly allocated objects MUST be in the alloc space and those are the only objects which we are
888 // going to free.
889 SpaceBitmap* live_bitmap = space->GetLiveBitmap();
890 SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700891 LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
892 SpaceSetMap* large_live_objects = large_object_space->GetLiveObjects();
893 SpaceSetMap* large_mark_objects = large_object_space->GetMarkObjects();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700894 if (swap_bitmaps) {
895 std::swap(live_bitmap, mark_bitmap);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700896 std::swap(large_live_objects, large_mark_objects);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700897 }
898
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700899 size_t freed_large_objects = 0;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700900 size_t count = allocations->Size();
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700901 Object** objects = const_cast<Object**>(allocations->Begin());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700902 Object** out = objects;
903
904 // Empty the allocation stack.
Ian Rogers50b35e22012-10-04 10:09:15 -0700905 Thread* self = Thread::Current();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700906 for (size_t i = 0;i < count;++i) {
907 Object* obj = objects[i];
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700908 // There should only be objects in the AllocSpace/LargeObjectSpace in the allocation stack.
909 if (LIKELY(mark_bitmap->HasAddress(obj))) {
910 if (!mark_bitmap->Test(obj)) {
911 // Don't bother un-marking since we clear the mark bitmap anyways.
912 *(out++) = obj;
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700913 }
914 } else if (!large_mark_objects->Test(obj)) {
915 ++freed_large_objects;
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700916 freed_bytes += large_object_space->Free(self, obj);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700917 }
918 }
919 logger.AddSplit("Process allocation stack");
920
921 size_t freed_objects = out - objects;
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700922 freed_bytes += space->FreeList(self, freed_objects, objects);
Mathieu Chartier40e978b2012-09-07 11:38:36 -0700923 VLOG(heap) << "Freed " << freed_objects << "/" << count
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700924 << " objects with size " << PrettySize(freed_bytes);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700925 heap_->RecordFree(freed_objects + freed_large_objects, freed_bytes);
Mathieu Chartier40e978b2012-09-07 11:38:36 -0700926 freed_objects_ += freed_objects;
927 freed_bytes_ += freed_bytes;
928 logger.AddSplit("FreeList");
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700929 allocations->Reset();
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800930 logger.AddSplit("ResetStack");
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700931}
932
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800933void MarkSweep::Sweep(TimingLogger& timings, bool swap_bitmaps) {
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700934 DCHECK(mark_stack_->IsEmpty());
935
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700936 // If we don't swap bitmaps then newly allocated Weaks go into the live bitmap but not mark
937 // bitmap, resulting in occasional frees of Weaks which are still in use.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700938 SweepSystemWeaks();
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700939 timings.AddSplit("SweepSystemWeaks");
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700940
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800941 const bool partial = GetGcType() == kGcTypePartial;
Mathieu Chartier46a23632012-08-07 18:44:40 -0700942 const Spaces& spaces = heap_->GetSpaces();
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800943 SweepCallbackContext scc;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700944 scc.mark_sweep = this;
Ian Rogers50b35e22012-10-04 10:09:15 -0700945 scc.self = Thread::Current();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700946 // TODO: C++0x auto
947 for (Spaces::const_iterator it = spaces.begin(); it != spaces.end(); ++it) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700948 ContinuousSpace* space = *it;
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700949 if (
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700950 space->GetGcRetentionPolicy() == kGcRetentionPolicyAlwaysCollect ||
951 (!partial && space->GetGcRetentionPolicy() == kGcRetentionPolicyFullCollect)
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700952 ) {
953 uintptr_t begin = reinterpret_cast<uintptr_t>(space->Begin());
954 uintptr_t end = reinterpret_cast<uintptr_t>(space->End());
955 scc.space = space->AsAllocSpace();
956 SpaceBitmap* live_bitmap = space->GetLiveBitmap();
957 SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700958 if (swap_bitmaps) {
959 std::swap(live_bitmap, mark_bitmap);
960 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700961 if (space->GetGcRetentionPolicy() == kGcRetentionPolicyAlwaysCollect) {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700962 // Bitmaps are pre-swapped for optimization which enables sweeping with the heap unlocked.
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700963 SpaceBitmap::SweepWalk(*live_bitmap, *mark_bitmap, begin, end,
964 &SweepCallback, reinterpret_cast<void*>(&scc));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700965 } else {
966 // Zygote sweep takes care of dirtying cards and clearing live bits, does not free actual memory.
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700967 SpaceBitmap::SweepWalk(*live_bitmap, *mark_bitmap, begin, end,
968 &ZygoteSweepCallback, reinterpret_cast<void*>(&scc));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700969 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700970 }
971 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700972 timings.AddSplit("Sweep");
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800973
974 SweepLargeObjects(swap_bitmaps);
975 timings.AddSplit("SweepLargeObjects");
Carl Shapiro58551df2011-07-24 03:09:51 -0700976}
977
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700978void MarkSweep::SweepLargeObjects(bool swap_bitmaps) {
979 // Sweep large objects
980 LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700981 SpaceSetMap* large_live_objects = large_object_space->GetLiveObjects();
982 SpaceSetMap* large_mark_objects = large_object_space->GetMarkObjects();
983 if (swap_bitmaps) {
984 std::swap(large_live_objects, large_mark_objects);
985 }
986 SpaceSetMap::Objects& live_objects = large_live_objects->GetObjects();
987 // O(n*log(n)) but hopefully there are not too many large objects.
988 size_t freed_objects = 0;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700989 size_t freed_bytes = 0;
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700990 // TODO: C++0x
Ian Rogers50b35e22012-10-04 10:09:15 -0700991 Thread* self = Thread::Current();
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700992 for (SpaceSetMap::Objects::iterator it = live_objects.begin(); it != live_objects.end(); ++it) {
993 if (!large_mark_objects->Test(*it)) {
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700994 freed_bytes += large_object_space->Free(self, const_cast<Object*>(*it));
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700995 ++freed_objects;
996 }
997 }
998 freed_objects_ += freed_objects;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700999 freed_bytes_ += freed_bytes;
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001000 // Large objects don't count towards bytes_allocated.
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001001 GetHeap()->RecordFree(freed_objects, freed_bytes);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001002}
1003
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001004void MarkSweep::CheckReference(const Object* obj, const Object* ref, MemberOffset offset, bool is_static) {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001005 const Spaces& spaces = heap_->GetSpaces();
1006 // TODO: C++0x auto
1007 for (Spaces::const_iterator cur = spaces.begin(); cur != spaces.end(); ++cur) {
1008 if ((*cur)->IsAllocSpace() && (*cur)->Contains(ref)) {
1009 DCHECK(IsMarked(obj));
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001010
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001011 bool is_marked = IsMarked(ref);
1012 if (!is_marked) {
1013 LOG(INFO) << **cur;
1014 LOG(WARNING) << (is_static ? "Static ref'" : "Instance ref'") << PrettyTypeOf(ref)
1015 << "' (" << reinterpret_cast<const void*>(ref) << ") in '" << PrettyTypeOf(obj)
1016 << "' (" << reinterpret_cast<const void*>(obj) << ") at offset "
1017 << reinterpret_cast<void*>(offset.Int32Value()) << " wasn't marked";
Mathieu Chartier262e5ff2012-06-01 17:35:38 -07001018
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001019 const Class* klass = is_static ? obj->AsClass() : obj->GetClass();
1020 DCHECK(klass != NULL);
1021 const ObjectArray<Field>* fields = is_static ? klass->GetSFields() : klass->GetIFields();
1022 DCHECK(fields != NULL);
1023 bool found = false;
1024 for (int32_t i = 0; i < fields->GetLength(); ++i) {
1025 const Field* cur = fields->Get(i);
1026 if (cur->GetOffset().Int32Value() == offset.Int32Value()) {
1027 LOG(WARNING) << "Field referencing the alloc space was " << PrettyField(cur);
1028 found = true;
1029 break;
1030 }
1031 }
1032 if (!found) {
1033 LOG(WARNING) << "Could not find field in object alloc space with offset " << offset.Int32Value();
1034 }
Mathieu Chartier262e5ff2012-06-01 17:35:38 -07001035
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001036 bool obj_marked = heap_->GetCardTable()->IsDirty(obj);
1037 if (!obj_marked) {
1038 LOG(WARNING) << "Object '" << PrettyTypeOf(obj) << "' "
1039 << "(" << reinterpret_cast<const void*>(obj) << ") contains references to "
1040 << "the alloc space, but wasn't card marked";
Mathieu Chartier262e5ff2012-06-01 17:35:38 -07001041 }
1042 }
Ian Rogers5d76c432011-10-31 21:42:49 -07001043 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001044 break;
Ian Rogers5d76c432011-10-31 21:42:49 -07001045 }
1046}
1047
Carl Shapiro69759ea2011-07-21 18:13:35 -07001048// Process the "referent" field in a java.lang.ref.Reference. If the
1049// referent has not yet been marked, put it on the appropriate list in
1050// the gcHeap for later processing.
1051void MarkSweep::DelayReferenceReferent(Object* obj) {
1052 DCHECK(obj != NULL);
Brian Carlstrom1f870082011-08-23 16:02:11 -07001053 Class* klass = obj->GetClass();
1054 DCHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001055 DCHECK(klass->IsReferenceClass());
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001056 Object* pending = obj->GetFieldObject<Object*>(heap_->GetReferencePendingNextOffset(), false);
1057 Object* referent = heap_->GetReferenceReferent(obj);
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001058 if (kCountJavaLangRefs) {
1059 ++reference_count_;
1060 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001061 if (pending == NULL && referent != NULL && !IsMarked(referent)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07001062 Object** list = NULL;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001063 if (klass->IsSoftReferenceClass()) {
Carl Shapiro69759ea2011-07-21 18:13:35 -07001064 list = &soft_reference_list_;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001065 } else if (klass->IsWeakReferenceClass()) {
Carl Shapiro69759ea2011-07-21 18:13:35 -07001066 list = &weak_reference_list_;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001067 } else if (klass->IsFinalizerReferenceClass()) {
Carl Shapiro69759ea2011-07-21 18:13:35 -07001068 list = &finalizer_reference_list_;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001069 } else if (klass->IsPhantomReferenceClass()) {
Carl Shapiro69759ea2011-07-21 18:13:35 -07001070 list = &phantom_reference_list_;
1071 }
Brian Carlstrom0796af02011-10-12 14:31:45 -07001072 DCHECK(list != NULL) << PrettyClass(klass) << " " << std::hex << klass->GetAccessFlags();
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001073 // TODO: One lock per list?
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001074 heap_->EnqueuePendingReference(obj, list);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001075 }
1076}
1077
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001078void MarkSweep::ScanRoot(const Object* obj) {
1079 ScanObject(obj);
1080}
1081
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001082class MarkObjectVisitor {
1083 public:
1084 MarkObjectVisitor(MarkSweep* const mark_sweep) : mark_sweep_(mark_sweep) {
1085 }
1086
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001087 // TODO: Fixme when anotatalysis works with visitors.
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001088 void operator ()(const Object* /* obj */, const Object* ref, const MemberOffset& /* offset */,
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001089 bool /* is_static */) const
1090 NO_THREAD_SAFETY_ANALYSIS {
1091 if (kDebugLocking) {
1092 Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
1093 Locks::heap_bitmap_lock_->AssertExclusiveHeld(Thread::Current());
1094 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001095 mark_sweep_->MarkObject(ref);
1096 }
1097
1098 private:
1099 MarkSweep* const mark_sweep_;
1100};
1101
Carl Shapiro69759ea2011-07-21 18:13:35 -07001102// Scans an object reference. Determines the type of the reference
1103// and dispatches to a specialized scanning routine.
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001104void MarkSweep::ScanObject(const Object* obj) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001105 MarkObjectVisitor visitor(this);
1106 ScanObjectVisit(obj, visitor);
1107}
1108
1109class MarkStackChunk : public Task {
1110public:
1111 MarkStackChunk(ThreadPool* thread_pool, MarkSweep* mark_sweep, Object** begin, Object** end)
1112 : mark_sweep_(mark_sweep),
1113 thread_pool_(thread_pool),
1114 index_(0),
1115 length_(0),
1116 output_(NULL) {
1117 length_ = end - begin;
1118 if (begin != end) {
1119 // Cost not significant since we only do this for the initial set of mark stack chunks.
1120 memcpy(data_, begin, length_ * sizeof(*begin));
1121 }
1122 if (kCountTasks) {
1123 ++mark_sweep_->work_chunks_created_;
1124 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001125 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001126
1127 ~MarkStackChunk() {
1128 DCHECK(output_ == NULL || output_->length_ == 0);
1129 DCHECK_GE(index_, length_);
1130 delete output_;
1131 if (kCountTasks) {
1132 ++mark_sweep_->work_chunks_deleted_;
1133 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001134 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001135
1136 MarkSweep* const mark_sweep_;
1137 ThreadPool* const thread_pool_;
1138 static const size_t max_size = 1 * KB;
1139 // Index of which object we are scanning. Only needs to be atomic if we are doing work stealing.
1140 size_t index_;
1141 // Input / output mark stack. We add newly marked references to data_ until length reaches
1142 // max_size. This is an optimization so that less tasks are created.
1143 // TODO: Investigate using a bounded buffer FIFO.
1144 Object* data_[max_size];
1145 // How many elements in data_ we need to scan.
1146 size_t length_;
1147 // Output block, newly marked references get added to the ouput block so that another thread can
1148 // scan them.
1149 MarkStackChunk* output_;
1150
1151 class MarkObjectParallelVisitor {
1152 public:
1153 MarkObjectParallelVisitor(MarkStackChunk* chunk_task) : chunk_task_(chunk_task) {
1154
1155 }
1156
1157 void operator ()(const Object* /* obj */, const Object* ref,
1158 const MemberOffset& /* offset */, bool /* is_static */) const {
1159 if (ref != NULL && chunk_task_->mark_sweep_->MarkObjectParallel(ref)) {
1160 chunk_task_->MarkStackPush(ref);
1161 }
1162 }
1163
1164 private:
1165 MarkStackChunk* const chunk_task_;
1166 };
1167
1168 // Push an object into the block.
1169 // Don't need to use atomic ++ since we only one thread is writing to an output block at any
1170 // given time.
1171 void Push(Object* obj) {
1172 data_[length_++] = obj;
1173 }
1174
1175 void MarkStackPush(const Object* obj) {
1176 if (static_cast<size_t>(length_) < max_size) {
1177 Push(const_cast<Object*>(obj));
1178 } else {
1179 // Internal buffer is full, push to a new buffer instead.
1180 if (UNLIKELY(output_ == NULL)) {
1181 AllocateOutputChunk();
1182 } else if (UNLIKELY(static_cast<size_t>(output_->length_) == max_size)) {
1183 // Output block is full, queue it up for processing and obtain a new block.
1184 EnqueueOutput();
1185 AllocateOutputChunk();
1186 }
1187 output_->Push(const_cast<Object*>(obj));
1188 }
1189 }
1190
1191 void ScanObject(Object* obj) {
1192 mark_sweep_->ScanObjectVisit(obj, MarkObjectParallelVisitor(this));
1193 }
1194
1195 void EnqueueOutput() {
1196 if (output_ != NULL) {
1197 uint64_t start = 0;
1198 if (kMeasureOverhead) {
1199 start = NanoTime();
1200 }
1201 thread_pool_->AddTask(Thread::Current(), output_);
1202 output_ = NULL;
1203 if (kMeasureOverhead) {
1204 mark_sweep_->overhead_time_ += NanoTime() - start;
1205 }
1206 }
1207 }
1208
1209 void AllocateOutputChunk() {
1210 uint64_t start = 0;
1211 if (kMeasureOverhead) {
1212 start = NanoTime();
1213 }
1214 output_ = new MarkStackChunk(thread_pool_, mark_sweep_, NULL, NULL);
1215 if (kMeasureOverhead) {
1216 mark_sweep_->overhead_time_ += NanoTime() - start;
1217 }
1218 }
1219
1220 void Finalize() {
1221 EnqueueOutput();
1222 delete this;
1223 }
1224
1225 // Scans all of the objects
1226 virtual void Run(Thread* self) {
Brian Carlstromd74e41b2013-03-24 23:47:01 -07001227 size_t index;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001228 while ((index = index_++) < length_) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001229 if (kUseMarkStackPrefetch) {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001230 static const size_t prefetch_look_ahead = 1;
1231 __builtin_prefetch(data_[std::min(index + prefetch_look_ahead, length_ - 1)]);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001232 }
1233 Object* obj = data_[index];
1234 DCHECK(obj != NULL);
1235 ScanObject(obj);
1236 }
1237 }
1238};
1239
1240void MarkSweep::ProcessMarkStackParallel() {
1241 CHECK(kDisableFinger) << "parallel mark stack processing cannot work when finger is enabled";
1242 Thread* self = Thread::Current();
1243 ThreadPool* thread_pool = GetHeap()->GetThreadPool();
1244 // Split the current mark stack up into work tasks.
1245 const size_t num_threads = thread_pool->GetThreadCount();
1246 const size_t stack_size = mark_stack_->Size();
1247 const size_t chunk_size =
1248 std::min((stack_size + num_threads - 1) / num_threads,
1249 static_cast<size_t>(MarkStackChunk::max_size));
1250 size_t index = 0;
1251 for (size_t i = 0; i < num_threads || index < stack_size; ++i) {
1252 Object** begin = &mark_stack_->Begin()[std::min(stack_size, index)];
1253 Object** end = &mark_stack_->Begin()[std::min(stack_size, index + chunk_size)];
1254 index += chunk_size;
1255 thread_pool->AddTask(self, new MarkStackChunk(thread_pool, this, begin, end));
1256 }
1257 thread_pool->StartWorkers(self);
1258 mark_stack_->Reset();
1259 thread_pool->Wait(self, true);
1260 //LOG(INFO) << "Idle wait time " << PrettyDuration(thread_pool->GetWaitTime());
1261 CHECK_EQ(work_chunks_created_, work_chunks_deleted_) << " some of the work chunks were leaked";
Carl Shapiro69759ea2011-07-21 18:13:35 -07001262}
1263
Ian Rogers5d76c432011-10-31 21:42:49 -07001264// Scan anything that's on the mark stack.
Carl Shapiro69759ea2011-07-21 18:13:35 -07001265void MarkSweep::ProcessMarkStack() {
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001266 ThreadPool* thread_pool = GetHeap()->GetThreadPool();
1267 if (kParallelMarkStack && thread_pool != NULL && thread_pool->GetThreadCount() > 0) {
1268 ProcessMarkStackParallel();
1269 return;
1270 }
1271
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001272 if (kUseMarkStackPrefetch) {
1273 const size_t fifo_size = 4;
1274 const size_t fifo_mask = fifo_size - 1;
1275 const Object* fifo[fifo_size];
1276 for (size_t i = 0;i < fifo_size;++i) {
1277 fifo[i] = NULL;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001278 }
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001279 size_t fifo_pos = 0;
1280 size_t fifo_count = 0;
1281 for (;;) {
1282 const Object* obj = fifo[fifo_pos & fifo_mask];
1283 if (obj != NULL) {
1284 ScanObject(obj);
1285 fifo[fifo_pos & fifo_mask] = NULL;
1286 --fifo_count;
1287 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001288
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001289 if (!mark_stack_->IsEmpty()) {
1290 const Object* obj = mark_stack_->PopBack();
1291 DCHECK(obj != NULL);
1292 fifo[fifo_pos & fifo_mask] = obj;
1293 __builtin_prefetch(obj);
1294 fifo_count++;
1295 }
1296 fifo_pos++;
1297
1298 if (!fifo_count) {
1299 CHECK(mark_stack_->IsEmpty()) << mark_stack_->Size();
1300 break;
1301 }
1302 }
1303 } else {
1304 while (!mark_stack_->IsEmpty()) {
1305 const Object* obj = mark_stack_->PopBack();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001306 DCHECK(obj != NULL);
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001307 ScanObject(obj);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001308 }
1309 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001310}
1311
Carl Shapiro69759ea2011-07-21 18:13:35 -07001312// Walks the reference list marking any references subject to the
1313// reference clearing policy. References with a black referent are
1314// removed from the list. References with white referents biased
1315// toward saving are blackened and also removed from the list.
1316void MarkSweep::PreserveSomeSoftReferences(Object** list) {
1317 DCHECK(list != NULL);
1318 Object* clear = NULL;
1319 size_t counter = 0;
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001320
1321 DCHECK(mark_stack_->IsEmpty());
1322
Carl Shapiro69759ea2011-07-21 18:13:35 -07001323 while (*list != NULL) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001324 Object* ref = heap_->DequeuePendingReference(list);
1325 Object* referent = heap_->GetReferenceReferent(ref);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001326 if (referent == NULL) {
1327 // Referent was cleared by the user during marking.
1328 continue;
1329 }
1330 bool is_marked = IsMarked(referent);
1331 if (!is_marked && ((++counter) & 1)) {
1332 // Referent is white and biased toward saving, mark it.
1333 MarkObject(referent);
1334 is_marked = true;
1335 }
1336 if (!is_marked) {
1337 // Referent is white, queue it for clearing.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001338 heap_->EnqueuePendingReference(ref, &clear);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001339 }
1340 }
1341 *list = clear;
1342 // Restart the mark with the newly black references added to the
1343 // root set.
1344 ProcessMarkStack();
1345}
1346
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001347inline bool MarkSweep::IsMarked(const Object* object) const
1348 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
1349 if (object >= immune_begin_ && object < immune_end_) {
1350 return true;
1351 }
1352 DCHECK(current_mark_bitmap_ != NULL);
1353 if (current_mark_bitmap_->HasAddress(object)) {
1354 return current_mark_bitmap_->Test(object);
1355 }
1356 return heap_->GetMarkBitmap()->Test(object);
1357}
1358
1359
Carl Shapiro69759ea2011-07-21 18:13:35 -07001360// Unlink the reference list clearing references objects with white
1361// referents. Cleared references registered to a reference queue are
1362// scheduled for appending by the heap worker thread.
1363void MarkSweep::ClearWhiteReferences(Object** list) {
1364 DCHECK(list != NULL);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001365 while (*list != NULL) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001366 Object* ref = heap_->DequeuePendingReference(list);
1367 Object* referent = heap_->GetReferenceReferent(ref);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001368 if (referent != NULL && !IsMarked(referent)) {
1369 // Referent is white, clear it.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001370 heap_->ClearReferenceReferent(ref);
1371 if (heap_->IsEnqueuable(ref)) {
1372 heap_->EnqueueReference(ref, &cleared_reference_list_);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001373 }
1374 }
1375 }
1376 DCHECK(*list == NULL);
1377}
1378
1379// Enqueues finalizer references with white referents. White
1380// referents are blackened, moved to the zombie field, and the
1381// referent field is cleared.
1382void MarkSweep::EnqueueFinalizerReferences(Object** list) {
1383 DCHECK(list != NULL);
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001384 MemberOffset zombie_offset = heap_->GetFinalizerReferenceZombieOffset();
Carl Shapiro69759ea2011-07-21 18:13:35 -07001385 bool has_enqueued = false;
1386 while (*list != NULL) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001387 Object* ref = heap_->DequeuePendingReference(list);
1388 Object* referent = heap_->GetReferenceReferent(ref);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001389 if (referent != NULL && !IsMarked(referent)) {
1390 MarkObject(referent);
1391 // If the referent is non-null the reference must queuable.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001392 DCHECK(heap_->IsEnqueuable(ref));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001393 ref->SetFieldObject(zombie_offset, referent, false);
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001394 heap_->ClearReferenceReferent(ref);
1395 heap_->EnqueueReference(ref, &cleared_reference_list_);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001396 has_enqueued = true;
1397 }
1398 }
1399 if (has_enqueued) {
1400 ProcessMarkStack();
1401 }
1402 DCHECK(*list == NULL);
1403}
1404
Carl Shapiro58551df2011-07-24 03:09:51 -07001405// Process reference class instances and schedule finalizations.
Carl Shapiro69759ea2011-07-21 18:13:35 -07001406void MarkSweep::ProcessReferences(Object** soft_references, bool clear_soft,
1407 Object** weak_references,
1408 Object** finalizer_references,
1409 Object** phantom_references) {
1410 DCHECK(soft_references != NULL);
1411 DCHECK(weak_references != NULL);
1412 DCHECK(finalizer_references != NULL);
1413 DCHECK(phantom_references != NULL);
1414
1415 // Unless we are in the zygote or required to clear soft references
1416 // with white references, preserve some white referents.
Ian Rogers2945e242012-06-03 14:45:16 -07001417 if (!clear_soft && !Runtime::Current()->IsZygote()) {
Carl Shapiro69759ea2011-07-21 18:13:35 -07001418 PreserveSomeSoftReferences(soft_references);
1419 }
1420
1421 // Clear all remaining soft and weak references with white
1422 // referents.
1423 ClearWhiteReferences(soft_references);
1424 ClearWhiteReferences(weak_references);
1425
1426 // Preserve all white objects with finalize methods and schedule
1427 // them for finalization.
1428 EnqueueFinalizerReferences(finalizer_references);
1429
1430 // Clear all f-reachable soft and weak references with white
1431 // referents.
1432 ClearWhiteReferences(soft_references);
1433 ClearWhiteReferences(weak_references);
1434
1435 // Clear all phantom references with white referents.
1436 ClearWhiteReferences(phantom_references);
1437
1438 // At this point all reference lists should be empty.
1439 DCHECK(*soft_references == NULL);
1440 DCHECK(*weak_references == NULL);
1441 DCHECK(*finalizer_references == NULL);
1442 DCHECK(*phantom_references == NULL);
1443}
1444
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001445void MarkSweep::UnBindBitmaps() {
1446 const Spaces& spaces = heap_->GetSpaces();
1447 // TODO: C++0x auto
1448 for (Spaces::const_iterator it = spaces.begin(); it != spaces.end(); ++it) {
1449 Space* space = *it;
1450 if (space->IsAllocSpace()) {
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -07001451 DlMallocSpace* alloc_space = space->AsAllocSpace();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001452 if (alloc_space->temp_bitmap_.get() != NULL) {
1453 // At this point, the temp_bitmap holds our old mark bitmap.
1454 SpaceBitmap* new_bitmap = alloc_space->temp_bitmap_.release();
1455 GetHeap()->GetMarkBitmap()->ReplaceBitmap(alloc_space->mark_bitmap_.get(), new_bitmap);
1456 CHECK_EQ(alloc_space->mark_bitmap_.release(), alloc_space->live_bitmap_.get());
1457 alloc_space->mark_bitmap_.reset(new_bitmap);
1458 DCHECK(alloc_space->temp_bitmap_.get() == NULL);
1459 }
1460 }
1461 }
1462}
1463
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001464void MarkSweep::FinishPhase() {
1465 // Can't enqueue referneces if we hold the mutator lock.
1466 Object* cleared_references = GetClearedReferences();
1467 heap_->EnqueueClearedReferences(&cleared_references);
1468
1469 heap_->PostGcVerification(this);
1470
Mathieu Chartier65db8802012-11-20 12:36:46 -08001471 heap_->GrowForUtilization(GetDuration());
1472 timings_.AddSplit("GrowForUtilization");
1473
1474 heap_->RequestHeapTrim();
1475 timings_.AddSplit("RequestHeapTrim");
1476
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001477 // Update the cumulative statistics
1478 total_time_ += GetDuration();
1479 total_paused_time_ += std::accumulate(GetPauseTimes().begin(), GetPauseTimes().end(), 0,
1480 std::plus<uint64_t>());
1481 total_freed_objects_ += GetFreedObjects();
1482 total_freed_bytes_ += GetFreedBytes();
1483
1484 // Ensure that the mark stack is empty.
1485 CHECK(mark_stack_->IsEmpty());
1486
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001487 if (kCountScannedTypes) {
1488 VLOG(gc) << "MarkSweep scanned classes=" << class_count_ << " arrays=" << array_count_
1489 << " other=" << other_count_;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001490 }
1491
1492 if (kCountTasks) {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001493 VLOG(gc) << "Total number of work chunks allocated: " << work_chunks_created_;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001494 }
1495
1496 if (kMeasureOverhead) {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001497 VLOG(gc) << "Overhead time " << PrettyDuration(overhead_time_);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001498 }
1499
1500 if (kProfileLargeObjects) {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001501 VLOG(gc) << "Large objects tested " << large_object_test_ << " marked " << large_object_mark_;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001502 }
1503
1504 if (kCountClassesMarked) {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001505 VLOG(gc) << "Classes marked " << classes_marked_;
1506 }
1507
1508 if (kCountJavaLangRefs) {
1509 VLOG(gc) << "References scanned " << reference_count_;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001510 }
1511
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001512 // Update the cumulative loggers.
1513 cumulative_timings_.Start();
1514 cumulative_timings_.AddLogger(timings_);
1515 cumulative_timings_.End();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001516
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001517 // Clear all of the spaces' mark bitmaps.
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001518 const Spaces& spaces = heap_->GetSpaces();
1519 // TODO: C++0x auto
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001520 for (Spaces::const_iterator it = spaces.begin(); it != spaces.end(); ++it) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001521 ContinuousSpace* space = *it;
1522 if (space->GetGcRetentionPolicy() != kGcRetentionPolicyNeverCollect) {
1523 space->GetMarkBitmap()->Clear();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001524 }
1525 }
Mathieu Chartier5301cd22012-05-31 12:11:36 -07001526 mark_stack_->Reset();
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001527
1528 // Reset the marked large objects.
1529 LargeObjectSpace* large_objects = GetHeap()->GetLargeObjectsSpace();
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001530 large_objects->GetMarkObjects()->Clear();
Carl Shapiro69759ea2011-07-21 18:13:35 -07001531}
1532
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001533MarkSweep::~MarkSweep() {
1534
1535}
1536
Carl Shapiro69759ea2011-07-21 18:13:35 -07001537} // namespace art