blob: e0ecc99549261a13d6d10b301d273b24f56af1a6 [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
Carl Shapiro58551df2011-07-24 03:09:51 -070019#include <climits>
20#include <vector>
21
Mathieu Chartier858f1c52012-10-17 17:45:55 -070022#include "barrier.h"
Mathieu Chartier357e9be2012-08-01 11:00:14 -070023#include "card_table.h"
Elliott Hughes410c0c82011-09-01 17:58:25 -070024#include "class_loader.h"
Brian Carlstrom693267a2011-09-06 09:25:34 -070025#include "dex_cache.h"
Carl Shapiro58551df2011-07-24 03:09:51 -070026#include "heap.h"
Elliott Hughes410c0c82011-09-01 17:58:25 -070027#include "indirect_reference_table.h"
28#include "intern_table.h"
Ian Rogers81d425b2012-09-27 16:03:43 -070029#include "jni_internal.h"
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -070030#include "large_object_space.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070031#include "logging.h"
32#include "macros.h"
Elliott Hughesc33a32b2011-10-11 18:18:07 -070033#include "monitor.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070034#include "object.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070035#include "runtime.h"
Carl Shapiro58551df2011-07-24 03:09:51 -070036#include "space.h"
Elliott Hughes307f75d2011-10-12 18:04:40 -070037#include "timing_logger.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070038#include "thread.h"
Mathieu Chartier6f1c9492012-10-15 12:08:41 -070039#include "thread_list.h"
Ian Rogers08254272012-10-23 17:49:23 -070040#include "verifier/method_verifier.h"
Carl Shapiro69759ea2011-07-21 18:13:35 -070041
Carl Shapiro69759ea2011-07-21 18:13:35 -070042namespace art {
43
Mathieu Chartier02b6a782012-10-26 13:51:26 -070044// Performance options.
45static const bool kParallelMarkStack = true;
46static const bool kDisableFinger = true;
Mathieu Chartier858f1c52012-10-17 17:45:55 -070047static const bool kUseMarkStackPrefetch = true;
48
Mathieu Chartier02b6a782012-10-26 13:51:26 -070049// Profiling and information flags.
50static const bool kCountClassesMarked = false;
51static const bool kProfileLargeObjects = false;
52static const bool kMeasureOverhead = false;
53static const bool kCountTasks = false;
Mathieu Chartierd22d5482012-11-06 17:14:12 -080054static const bool kCountJavaLangRefs = false;
Mathieu Chartier02b6a782012-10-26 13:51:26 -070055
Mathieu Chartier357e9be2012-08-01 11:00:14 -070056class SetFingerVisitor {
57 public:
58 SetFingerVisitor(MarkSweep* const mark_sweep) : mark_sweep_(mark_sweep) {
59
60 }
61
62 void operator ()(void* finger) const {
63 mark_sweep_->SetFinger(reinterpret_cast<Object*>(finger));
64 }
65
66 private:
67 MarkSweep* const mark_sweep_;
68};
69
Mathieu Chartierd8195f12012-10-05 12:21:28 -070070MarkSweep::MarkSweep(ObjectStack* mark_stack)
Mathieu Chartierb062fdd2012-07-03 09:51:48 -070071 : current_mark_bitmap_(NULL),
72 mark_stack_(mark_stack),
Mathieu Chartier5301cd22012-05-31 12:11:36 -070073 heap_(NULL),
Mathieu Chartier5301cd22012-05-31 12:11:36 -070074 finger_(NULL),
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -070075 immune_begin_(NULL),
76 immune_end_(NULL),
Mathieu Chartier5301cd22012-05-31 12:11:36 -070077 soft_reference_list_(NULL),
78 weak_reference_list_(NULL),
79 finalizer_reference_list_(NULL),
80 phantom_reference_list_(NULL),
81 cleared_reference_list_(NULL),
Mathieu Chartier357e9be2012-08-01 11:00:14 -070082 freed_bytes_(0), freed_objects_(0),
Mathieu Chartier858f1c52012-10-17 17:45:55 -070083 class_count_(0), array_count_(0), other_count_(0),
Mathieu Chartier02b6a782012-10-26 13:51:26 -070084 large_object_test_(0), large_object_mark_(0),
85 classes_marked_(0), overhead_time_(0),
86 work_chunks_created_(0), work_chunks_deleted_(0),
Mathieu Chartierd22d5482012-11-06 17:14:12 -080087 reference_count_(0),
Mathieu Chartier35883cc2012-11-13 14:08:12 -080088 gc_barrier_(new Barrier(0)),
Mathieu Chartierac86a7c2012-11-12 15:03:16 -080089 large_object_lock_("large object lock"),
90 mark_stack_expand_lock_("mark stack expand lock") {
Mathieu Chartier5301cd22012-05-31 12:11:36 -070091 DCHECK(mark_stack_ != NULL);
92}
Elliott Hughesb3bd5f02012-03-08 21:05:27 -080093
Mathieu Chartier5301cd22012-05-31 12:11:36 -070094void MarkSweep::Init() {
Mathieu Chartier02b6a782012-10-26 13:51:26 -070095 java_lang_Class_ = Class::GetJavaLangClass();
96 CHECK(java_lang_Class_ != NULL);
Elliott Hughesb3bd5f02012-03-08 21:05:27 -080097 heap_ = Runtime::Current()->GetHeap();
Mathieu Chartier5301cd22012-05-31 12:11:36 -070098 mark_stack_->Reset();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -070099 FindDefaultMarkBitmap();
Mathieu Chartier9ebae1f2012-10-15 17:38:16 -0700100 // Mark any concurrent roots as dirty since we need to scan them at least once during this GC.
101 Runtime::Current()->DirtyRoots();
Carl Shapiro58551df2011-07-24 03:09:51 -0700102}
103
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700104void MarkSweep::FindDefaultMarkBitmap() {
105 const Spaces& spaces = heap_->GetSpaces();
106 for (Spaces::const_iterator it = spaces.begin(); it != spaces.end(); ++it) {
107 if ((*it)->GetGcRetentionPolicy() == kGcRetentionPolicyAlwaysCollect) {
108 current_mark_bitmap_ = (*it)->GetMarkBitmap();
109 CHECK(current_mark_bitmap_ != NULL);
110 return;
111 }
112 }
113 GetHeap()->DumpSpaces();
114 LOG(FATAL) << "Could not find a default mark bitmap";
115}
116
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800117void MarkSweep::ExpandMarkStack() {
118 // Rare case, no need to have Thread::Current be a parameter.
119 MutexLock mu(Thread::Current(), mark_stack_expand_lock_);
120 if (UNLIKELY(mark_stack_->Size() < mark_stack_->Capacity())) {
121 // Someone else acquired the lock and expanded the mark stack before us.
122 return;
123 }
124 std::vector<Object*> temp;
125 temp.insert(temp.begin(), mark_stack_->Begin(), mark_stack_->End());
126 mark_stack_->Resize(mark_stack_->Capacity() * 2);
127 for (size_t i = 0; i < temp.size(); ++i) {
128 mark_stack_->PushBack(temp[i]);
129 }
130}
131
132inline void MarkSweep::MarkObjectNonNullParallel(const Object* obj, bool check_finger) {
133 DCHECK(obj != NULL);
134 if (MarkObjectParallel(obj)) {
135 if (kDisableFinger || (check_finger && obj < finger_)) {
136 while (UNLIKELY(!mark_stack_->AtomicPushBack(const_cast<Object*>(obj)))) {
137 // Only reason a push can fail is that the mark stack is full.
138 ExpandMarkStack();
139 }
140 }
141 }
142}
143
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700144inline void MarkSweep::MarkObjectNonNull(const Object* obj, bool check_finger) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700145 DCHECK(obj != NULL);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700146
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700147 if (obj >= immune_begin_ && obj < immune_end_) {
148 DCHECK(IsMarked(obj));
Carl Shapiro69759ea2011-07-21 18:13:35 -0700149 return;
150 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700151
152 // Try to take advantage of locality of references within a space, failing this find the space
153 // the hard way.
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700154 SpaceBitmap* object_bitmap = current_mark_bitmap_;
155 if (UNLIKELY(!object_bitmap->HasAddress(obj))) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700156 SpaceBitmap* new_bitmap = heap_->GetMarkBitmap()->GetSpaceBitmap(obj);
157 if (new_bitmap != NULL) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700158 object_bitmap = new_bitmap;
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700159 } else {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700160 MarkLargeObject(obj);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700161 return;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700162 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700163 }
164
Carl Shapiro69759ea2011-07-21 18:13:35 -0700165 // This object was not previously marked.
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700166 if (!object_bitmap->Test(obj)) {
167 object_bitmap->Set(obj);
168 if (kDisableFinger || (check_finger && obj < finger_)) {
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700169 // Do we need to expand the mark stack?
170 if (UNLIKELY(mark_stack_->Size() >= mark_stack_->Capacity())) {
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800171 ExpandMarkStack();
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700172 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700173 // The object must be pushed on to the mark stack.
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700174 mark_stack_->PushBack(const_cast<Object*>(obj));
Carl Shapiro69759ea2011-07-21 18:13:35 -0700175 }
176 }
177}
178
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700179// Rare case, probably not worth inlining since it will increase instruction cache miss rate.
180bool MarkSweep::MarkLargeObject(const Object* obj) {
181 LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
182 SpaceSetMap* large_objects = large_object_space->GetMarkObjects();
183 if (kProfileLargeObjects) {
184 ++large_object_test_;
185 }
186 if (UNLIKELY(!large_objects->Test(obj))) {
187 if (!large_object_space->Contains(obj)) {
188 LOG(ERROR) << "Tried to mark " << obj << " not contained by any spaces";
189 LOG(ERROR) << "Attempting see if it's a bad root";
190 VerifyRoots();
191 LOG(FATAL) << "Can't mark bad root";
192 }
193 if (kProfileLargeObjects) {
194 ++large_object_mark_;
195 }
196 large_objects->Set(obj);
197 // Don't need to check finger since large objects never have any object references.
198 return true;
199 }
200 return false;
201}
202
203inline bool MarkSweep::MarkObjectParallel(const Object* obj) {
204 DCHECK(obj != NULL);
205
206 if (obj >= immune_begin_ && obj < immune_end_) {
207 DCHECK(IsMarked(obj));
208 return false;
209 }
210
211 // Try to take advantage of locality of references within a space, failing this find the space
212 // the hard way.
213 SpaceBitmap* object_bitmap = current_mark_bitmap_;
214 if (UNLIKELY(!object_bitmap->HasAddress(obj))) {
215 SpaceBitmap* new_bitmap = heap_->GetMarkBitmap()->GetSpaceBitmap(obj);
216 if (new_bitmap != NULL) {
217 object_bitmap = new_bitmap;
218 } else {
219 // TODO: Remove the Thread::Current here?
220 // TODO: Convert this to some kind of atomic marking?
221 MutexLock mu(Thread::Current(), large_object_lock_);
222 return MarkLargeObject(obj);
223 }
224 }
225
226 // Return true if the object was not previously marked.
227 return !object_bitmap->AtomicTestAndSet(obj);
228}
229
Carl Shapiro69759ea2011-07-21 18:13:35 -0700230// Used to mark objects when recursing. Recursion is done by moving
231// the finger across the bitmaps in address order and marking child
232// objects. Any newly-marked objects whose addresses are lower than
233// the finger won't be visited by the bitmap scan, so those objects
234// need to be added to the mark stack.
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700235void MarkSweep::MarkObject(const Object* obj) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700236 if (obj != NULL) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700237 MarkObjectNonNull(obj, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700238 }
239}
240
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800241void MarkSweep::MarkRootParallelCallback(const Object* root, void* arg) {
242 DCHECK(root != NULL);
243 DCHECK(arg != NULL);
244 MarkSweep* mark_sweep = reinterpret_cast<MarkSweep*>(arg);
245 mark_sweep->MarkObjectNonNullParallel(root, false);
246}
247
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700248void MarkSweep::MarkObjectCallback(const Object* root, void* arg) {
Brian Carlstrom1f870082011-08-23 16:02:11 -0700249 DCHECK(root != NULL);
250 DCHECK(arg != NULL);
251 MarkSweep* mark_sweep = reinterpret_cast<MarkSweep*>(arg);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700252 mark_sweep->MarkObjectNonNull(root, false);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700253}
254
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700255void MarkSweep::ReMarkObjectVisitor(const Object* root, void* arg) {
256 DCHECK(root != NULL);
257 DCHECK(arg != NULL);
258 MarkSweep* mark_sweep = reinterpret_cast<MarkSweep*>(arg);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700259 mark_sweep->MarkObjectNonNull(root, true);
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700260}
261
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700262void MarkSweep::VerifyRootCallback(const Object* root, void* arg, size_t vreg,
Ian Rogers40e3bac2012-11-20 00:09:14 -0800263 const StackVisitor* visitor) {
264 reinterpret_cast<MarkSweep*>(arg)->VerifyRoot(root, vreg, visitor);
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700265}
266
Ian Rogers40e3bac2012-11-20 00:09:14 -0800267void MarkSweep::VerifyRoot(const Object* root, size_t vreg, const StackVisitor* visitor) {
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700268 // See if the root is on any space bitmap.
Mathieu Chartier128c52c2012-10-16 14:12:41 -0700269 if (GetHeap()->GetLiveBitmap()->GetSpaceBitmap(root) == NULL) {
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700270 LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
Mathieu Chartier4202b742012-10-17 17:51:25 -0700271 if (!large_object_space->Contains(root)) {
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700272 LOG(ERROR) << "Found invalid root: " << root;
Ian Rogers40e3bac2012-11-20 00:09:14 -0800273 if (visitor != NULL) {
274 LOG(ERROR) << visitor->DescribeLocation() << " in VReg: " << vreg;
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700275 }
276 }
277 }
278}
279
280void MarkSweep::VerifyRoots() {
281 Runtime::Current()->GetThreadList()->VerifyRoots(VerifyRootCallback, this);
282}
283
Carl Shapiro69759ea2011-07-21 18:13:35 -0700284// Marks all objects in the root set.
285void MarkSweep::MarkRoots() {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700286 Runtime::Current()->VisitNonConcurrentRoots(MarkObjectCallback, this);
Mathieu Chartier9ebae1f2012-10-15 17:38:16 -0700287}
288
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700289void MarkSweep::MarkNonThreadRoots() {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700290 Runtime::Current()->VisitNonThreadRoots(MarkObjectCallback, this);
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700291}
292
Mathieu Chartier9ebae1f2012-10-15 17:38:16 -0700293void MarkSweep::MarkConcurrentRoots() {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700294 Runtime::Current()->VisitConcurrentRoots(MarkObjectCallback, this);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700295}
296
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700297class CheckObjectVisitor {
298 public:
299 CheckObjectVisitor(MarkSweep* const mark_sweep)
300 : mark_sweep_(mark_sweep) {
301
302 }
303
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700304 void operator ()(const Object* obj, const Object* ref, MemberOffset offset, bool is_static) const
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800305 NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700306 mark_sweep_->CheckReference(obj, ref, offset, is_static);
307 }
308
309 private:
310 MarkSweep* const mark_sweep_;
311};
312
313void MarkSweep::CheckObject(const Object* obj) {
314 DCHECK(obj != NULL);
315 CheckObjectVisitor visitor(this);
316 VisitObjectReferences(obj, visitor);
317}
318
319void MarkSweep::VerifyImageRootVisitor(Object* root, void* arg) {
320 DCHECK(root != NULL);
321 DCHECK(arg != NULL);
322 MarkSweep* mark_sweep = reinterpret_cast<MarkSweep*>(arg);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700323 DCHECK(mark_sweep->heap_->GetMarkBitmap()->Test(root));
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700324 mark_sweep->CheckObject(root);
325}
326
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700327void MarkSweep::CopyMarkBits(ContinuousSpace* space) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700328 SpaceBitmap* live_bitmap = space->GetLiveBitmap();
329 SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
330 mark_bitmap->CopyFrom(live_bitmap);
Ian Rogers5d76c432011-10-31 21:42:49 -0700331}
332
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700333void MarkSweep::BindLiveToMarkBitmap(ContinuousSpace* space) {
334 CHECK(space->IsAllocSpace());
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700335 DlMallocSpace* alloc_space = space->AsAllocSpace();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700336 SpaceBitmap* live_bitmap = space->GetLiveBitmap();
337 SpaceBitmap* mark_bitmap = alloc_space->mark_bitmap_.release();
338 GetHeap()->GetMarkBitmap()->ReplaceBitmap(mark_bitmap, live_bitmap);
339 alloc_space->temp_bitmap_.reset(mark_bitmap);
340 alloc_space->mark_bitmap_.reset(live_bitmap);
341}
342
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700343class ScanObjectVisitor {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700344 public:
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700345 ScanObjectVisitor(MarkSweep* const mark_sweep) : mark_sweep_(mark_sweep) {
346
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700347 }
348
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700349 void operator ()(const Object* obj) const
Ian Rogersb726dcb2012-09-05 08:57:23 -0700350 EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_)
351 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700352 mark_sweep_->ScanObject(obj);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700353 }
354
355 private:
356 MarkSweep* const mark_sweep_;
357};
358
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800359void MarkSweep::ScanGrayObjects(byte minimum_age) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700360 const Spaces& spaces = heap_->GetSpaces();
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700361 CardTable* card_table = heap_->GetCardTable();
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700362 ScanObjectVisitor visitor(this);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700363 SetFingerVisitor finger_visitor(this);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700364 // TODO: C++ 0x auto
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700365 for (Spaces::const_iterator it = spaces.begin(); it != spaces.end(); ++it) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700366 ContinuousSpace* space = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700367 byte* begin = space->Begin();
368 byte* end = space->End();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700369 // Image spaces are handled properly since live == marked for them.
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700370 SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800371 card_table->Scan(mark_bitmap, begin, end, visitor, VoidFunctor(), minimum_age);
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700372 }
373}
374
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700375class CheckBitmapVisitor {
376 public:
377 CheckBitmapVisitor(MarkSweep* mark_sweep) : mark_sweep_(mark_sweep) {
378
379 }
380
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700381 void operator ()(const Object* obj) const
Ian Rogersb726dcb2012-09-05 08:57:23 -0700382 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_,
383 Locks::mutator_lock_) {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700384 DCHECK(obj != NULL);
385 mark_sweep_->CheckObject(obj);
386 }
387
388 private:
389 MarkSweep* mark_sweep_;
390};
391
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700392void MarkSweep::VerifyImageRoots() {
393 // Verify roots ensures that all the references inside the image space point
394 // objects which are either in the image space or marked objects in the alloc
395 // space
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700396 CheckBitmapVisitor visitor(this);
397 const Spaces& spaces = heap_->GetSpaces();
398 for (Spaces::const_iterator it = spaces.begin(); it != spaces.end(); ++it) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700399 if ((*it)->IsImageSpace()) {
400 ImageSpace* space = (*it)->AsImageSpace();
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700401 uintptr_t begin = reinterpret_cast<uintptr_t>(space->Begin());
402 uintptr_t end = reinterpret_cast<uintptr_t>(space->End());
403 SpaceBitmap* live_bitmap = space->GetLiveBitmap();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700404 DCHECK(live_bitmap != NULL);
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800405 live_bitmap->VisitMarkedRange(begin, end, visitor, VoidFunctor());
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700406 }
407 }
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700408}
409
Carl Shapiro58551df2011-07-24 03:09:51 -0700410// Populates the mark stack based on the set of marked objects and
411// recursively marks until the mark stack is emptied.
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700412void MarkSweep::RecursiveMark(bool partial, TimingLogger& timings) {
Brian Carlstrom1f870082011-08-23 16:02:11 -0700413 // RecursiveMark will build the lists of known instances of the Reference classes.
414 // See DelayReferenceReferent for details.
415 CHECK(soft_reference_list_ == NULL);
416 CHECK(weak_reference_list_ == NULL);
417 CHECK(finalizer_reference_list_ == NULL);
418 CHECK(phantom_reference_list_ == NULL);
419 CHECK(cleared_reference_list_ == NULL);
420
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700421 const Spaces& spaces = heap_->GetSpaces();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700422 SetFingerVisitor set_finger_visitor(this);
423 ScanObjectVisitor scan_visitor(this);
424 for (Spaces::const_iterator it = spaces.begin(); it != spaces.end(); ++it) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700425 ContinuousSpace* space = *it;
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700426 if ((!kDisableFinger && space->GetGcRetentionPolicy() == kGcRetentionPolicyAlwaysCollect) ||
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700427 (!partial && space->GetGcRetentionPolicy() == kGcRetentionPolicyFullCollect)
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700428 ) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700429 current_mark_bitmap_ = space->GetMarkBitmap();
430 if (current_mark_bitmap_ == NULL) {
431 GetHeap()->DumpSpaces();
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700432 LOG(FATAL) << "invalid bitmap";
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700433 }
434 // This function does not handle heap end increasing, so we must use the space end.
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700435 uintptr_t begin = reinterpret_cast<uintptr_t>(space->Begin());
436 uintptr_t end = reinterpret_cast<uintptr_t>(space->End());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700437 current_mark_bitmap_->VisitMarkedRange(begin, end, scan_visitor, set_finger_visitor);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700438 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700439 }
440 finger_ = reinterpret_cast<Object*>(~0);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700441 timings.AddSplit("RecursiveMark");
Ian Rogers5d76c432011-10-31 21:42:49 -0700442 // TODO: tune the frequency of emptying the mark stack
Carl Shapiro58551df2011-07-24 03:09:51 -0700443 ProcessMarkStack();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700444 timings.AddSplit("ProcessMarkStack");
Carl Shapiro58551df2011-07-24 03:09:51 -0700445}
446
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700447void MarkSweep::RecursiveMarkCards(CardTable* card_table, const std::vector<byte*>& cards,
448 TimingLogger& timings) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700449 ScanObjectVisitor image_root_visitor(this);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700450 SetFingerVisitor finger_visitor(this);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700451 const size_t card_count = cards.size();
452 SpaceBitmap* active_bitmap = NULL;
453 for (size_t i = 0;i < card_count;) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700454 Object* start_obj = reinterpret_cast<Object*>(card_table->AddrFromCard(cards[i]));
455 uintptr_t begin = reinterpret_cast<uintptr_t>(start_obj);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700456 uintptr_t end = begin + CardTable::kCardSize;
457 for (++i; reinterpret_cast<uintptr_t>(cards[i]) == end && i < card_count; ++i) {
458 end += CardTable::kCardSize;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700459 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700460 if (active_bitmap == NULL || !active_bitmap->HasAddress(start_obj)) {
461 active_bitmap = heap_->GetMarkBitmap()->GetSpaceBitmap(start_obj);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700462 if (kIsDebugBuild && active_bitmap == NULL) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700463 GetHeap()->DumpSpaces();
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700464 LOG(FATAL) << "Object " << reinterpret_cast<const void*>(start_obj);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700465 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700466 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700467 if (kDisableFinger) {
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800468 active_bitmap->VisitMarkedRange(begin, end, image_root_visitor, VoidFunctor());
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700469 } else {
470 active_bitmap->VisitMarkedRange(begin, end, image_root_visitor, finger_visitor);
471 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700472 }
473 timings.AddSplit("RecursiveMarkCards");
474 ProcessMarkStack();
475 timings.AddSplit("ProcessMarkStack");
476}
477
478bool MarkSweep::IsMarkedCallback(const Object* object, void* arg) {
479 return
480 reinterpret_cast<MarkSweep*>(arg)->IsMarked(object) ||
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700481 !reinterpret_cast<MarkSweep*>(arg)->GetHeap()->GetLiveBitmap()->Test(object);
482}
483
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800484void MarkSweep::RecursiveMarkDirtyObjects(byte minimum_age) {
485 ScanGrayObjects(minimum_age);
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700486 ProcessMarkStack();
487}
488
Carl Shapiro58551df2011-07-24 03:09:51 -0700489void MarkSweep::ReMarkRoots() {
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700490 Runtime::Current()->VisitRoots(ReMarkObjectVisitor, this);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700491}
492
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700493void MarkSweep::SweepJniWeakGlobals(Heap::IsMarkedTester is_marked, void* arg) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700494 JavaVMExt* vm = Runtime::Current()->GetJavaVM();
Ian Rogers50b35e22012-10-04 10:09:15 -0700495 MutexLock mu(Thread::Current(), vm->weak_globals_lock);
Elliott Hughes410c0c82011-09-01 17:58:25 -0700496 IndirectReferenceTable* table = &vm->weak_globals;
Mathieu Chartier654d3a22012-07-11 17:54:18 -0700497 typedef IndirectReferenceTable::iterator It; // TODO: C++0x auto
Elliott Hughes410c0c82011-09-01 17:58:25 -0700498 for (It it = table->begin(), end = table->end(); it != end; ++it) {
499 const Object** entry = *it;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700500 if (!is_marked(*entry, arg)) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700501 *entry = kClearedJniWeakGlobal;
502 }
503 }
504}
505
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700506struct ArrayMarkedCheck {
507 ObjectStack* live_stack;
508 MarkSweep* mark_sweep;
509};
510
511// Either marked or not live.
512bool MarkSweep::IsMarkedArrayCallback(const Object* object, void* arg) {
513 ArrayMarkedCheck* array_check = reinterpret_cast<ArrayMarkedCheck*>(arg);
514 if (array_check->mark_sweep->IsMarked(object)) {
515 return true;
516 }
517 ObjectStack* live_stack = array_check->live_stack;
518 return std::find(live_stack->Begin(), live_stack->End(), object) == live_stack->End();
519}
520
521void MarkSweep::SweepSystemWeaksArray(ObjectStack* allocations) {
Mathieu Chartier46a23632012-08-07 18:44:40 -0700522 Runtime* runtime = Runtime::Current();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700523 // The callbacks check
524 // !is_marked where is_marked is the callback but we want
525 // !IsMarked && IsLive
526 // So compute !(!IsMarked && IsLive) which is equal to (IsMarked || !IsLive).
527 // Or for swapped (IsLive || !IsMarked).
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700528
529 ArrayMarkedCheck visitor;
530 visitor.live_stack = allocations;
531 visitor.mark_sweep = this;
532 runtime->GetInternTable()->SweepInternTableWeaks(IsMarkedArrayCallback, &visitor);
533 runtime->GetMonitorList()->SweepMonitorList(IsMarkedArrayCallback, &visitor);
534 SweepJniWeakGlobals(IsMarkedArrayCallback, &visitor);
535}
536
537void MarkSweep::SweepSystemWeaks() {
538 Runtime* runtime = Runtime::Current();
539 // The callbacks check
540 // !is_marked where is_marked is the callback but we want
541 // !IsMarked && IsLive
542 // So compute !(!IsMarked && IsLive) which is equal to (IsMarked || !IsLive).
543 // Or for swapped (IsLive || !IsMarked).
544 runtime->GetInternTable()->SweepInternTableWeaks(IsMarkedCallback, this);
545 runtime->GetMonitorList()->SweepMonitorList(IsMarkedCallback, this);
546 SweepJniWeakGlobals(IsMarkedCallback, this);
Carl Shapiro58551df2011-07-24 03:09:51 -0700547}
548
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700549bool MarkSweep::VerifyIsLiveCallback(const Object* obj, void* arg) {
550 reinterpret_cast<MarkSweep*>(arg)->VerifyIsLive(obj);
551 // We don't actually want to sweep the object, so lets return "marked"
552 return true;
553}
554
555void MarkSweep::VerifyIsLive(const Object* obj) {
556 Heap* heap = GetHeap();
557 if (!heap->GetLiveBitmap()->Test(obj)) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700558 LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
559 if (!large_object_space->GetLiveObjects()->Test(obj)) {
560 if (std::find(heap->allocation_stack_->Begin(), heap->allocation_stack_->End(), obj) ==
561 heap->allocation_stack_->End()) {
562 // Object not found!
563 heap->DumpSpaces();
564 LOG(FATAL) << "Found dead object " << obj;
565 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700566 }
567 }
568}
569
570void MarkSweep::VerifySystemWeaks() {
571 Runtime* runtime = Runtime::Current();
572 // Verify system weaks, uses a special IsMarked callback which always returns true.
573 runtime->GetInternTable()->SweepInternTableWeaks(VerifyIsLiveCallback, this);
574 runtime->GetMonitorList()->SweepMonitorList(VerifyIsLiveCallback, this);
575
576 JavaVMExt* vm = runtime->GetJavaVM();
Ian Rogers50b35e22012-10-04 10:09:15 -0700577 MutexLock mu(Thread::Current(), vm->weak_globals_lock);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700578 IndirectReferenceTable* table = &vm->weak_globals;
579 typedef IndirectReferenceTable::iterator It; // TODO: C++0x auto
580 for (It it = table->begin(), end = table->end(); it != end; ++it) {
581 const Object** entry = *it;
582 VerifyIsLive(*entry);
583 }
584}
585
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800586struct SweepCallbackContext {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700587 MarkSweep* mark_sweep;
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800588 AllocSpace* space;
Ian Rogers50b35e22012-10-04 10:09:15 -0700589 Thread* self;
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800590};
591
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700592class CheckpointMarkThreadRoots : public Closure {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700593 public:
594 CheckpointMarkThreadRoots(MarkSweep* mark_sweep) : mark_sweep_(mark_sweep) {
595
596 }
597
598 virtual void Run(Thread* thread) NO_THREAD_SAFETY_ANALYSIS {
599 // Note: self is not necessarily equal to thread since thread may be suspended.
600 Thread* self = Thread::Current();
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800601 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
602 << thread->GetState() << " thread " << thread << " self " << self;
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800603 thread->VisitRoots(MarkSweep::MarkRootParallelCallback, mark_sweep_);
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700604 mark_sweep_->GetBarrier().Pass(self);
605 }
606
607 private:
608 MarkSweep* mark_sweep_;
609};
610
611Barrier& MarkSweep::GetBarrier() {
612 return *gc_barrier_;
613}
614
615void MarkSweep::MarkRootsCheckpoint() {
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800616 CheckpointMarkThreadRoots check_point(this);
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700617 ThreadList* thread_list = Runtime::Current()->GetThreadList();
618 // Increment the count of the barrier. If all of the checkpoints have already been finished then
619 // will hit 0 and continue. Otherwise we are still waiting for some checkpoints, so the counter
620 // will go positive and we will unblock when it hits zero.
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800621 gc_barrier_->Increment(Thread::Current(), thread_list->RunCheckpoint(&check_point));
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700622}
623
Ian Rogers30fab402012-01-23 15:43:46 -0800624void MarkSweep::SweepCallback(size_t num_ptrs, Object** ptrs, void* arg) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800625 SweepCallbackContext* context = static_cast<SweepCallbackContext*>(arg);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700626 MarkSweep* mark_sweep = context->mark_sweep;
627 Heap* heap = mark_sweep->GetHeap();
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800628 AllocSpace* space = context->space;
Ian Rogers50b35e22012-10-04 10:09:15 -0700629 Thread* self = context->self;
630 Locks::heap_bitmap_lock_->AssertExclusiveHeld(self);
Ian Rogers5d76c432011-10-31 21:42:49 -0700631 // Use a bulk free, that merges consecutive objects before freeing or free per object?
632 // Documentation suggests better free performance with merging, but this may be at the expensive
633 // of allocation.
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700634 size_t freed_objects = num_ptrs;
635 // AllocSpace::FreeList clears the value in ptrs, so perform after clearing the live bit
636 size_t freed_bytes = space->FreeList(self, num_ptrs, ptrs);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700637 heap->RecordFree(freed_objects, freed_bytes);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700638 mark_sweep->freed_objects_ += freed_objects;
639 mark_sweep->freed_bytes_ += freed_bytes;
Carl Shapiro58551df2011-07-24 03:09:51 -0700640}
641
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700642void MarkSweep::ZygoteSweepCallback(size_t num_ptrs, Object** ptrs, void* arg) {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700643 SweepCallbackContext* context = static_cast<SweepCallbackContext*>(arg);
Ian Rogers50b35e22012-10-04 10:09:15 -0700644 Locks::heap_bitmap_lock_->AssertExclusiveHeld(context->self);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700645 Heap* heap = context->mark_sweep->GetHeap();
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700646 // We don't free any actual memory to avoid dirtying the shared zygote pages.
647 for (size_t i = 0; i < num_ptrs; ++i) {
648 Object* obj = static_cast<Object*>(ptrs[i]);
649 heap->GetLiveBitmap()->Clear(obj);
650 heap->GetCardTable()->MarkCard(obj);
651 }
652}
653
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700654void MarkSweep::SweepArray(TimingLogger& logger, ObjectStack* allocations, bool swap_bitmaps) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700655 size_t freed_bytes = 0;
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700656 DlMallocSpace* space = heap_->GetAllocSpace();
Elliott Hughes2da50362011-10-10 16:57:08 -0700657
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700658 // If we don't swap bitmaps then newly allocated Weaks go into the live bitmap but not mark
659 // bitmap, resulting in occasional frees of Weaks which are still in use.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700660 SweepSystemWeaksArray(allocations);
661 logger.AddSplit("SweepSystemWeaks");
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700662
663 // Newly allocated objects MUST be in the alloc space and those are the only objects which we are
664 // going to free.
665 SpaceBitmap* live_bitmap = space->GetLiveBitmap();
666 SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700667 LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
668 SpaceSetMap* large_live_objects = large_object_space->GetLiveObjects();
669 SpaceSetMap* large_mark_objects = large_object_space->GetMarkObjects();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700670 if (swap_bitmaps) {
671 std::swap(live_bitmap, mark_bitmap);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700672 std::swap(large_live_objects, large_mark_objects);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700673 }
674
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700675 size_t freed_large_objects = 0;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700676 size_t count = allocations->Size();
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700677 Object** objects = const_cast<Object**>(allocations->Begin());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700678 Object** out = objects;
679
680 // Empty the allocation stack.
Ian Rogers50b35e22012-10-04 10:09:15 -0700681 Thread* self = Thread::Current();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700682 for (size_t i = 0;i < count;++i) {
683 Object* obj = objects[i];
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700684 // There should only be objects in the AllocSpace/LargeObjectSpace in the allocation stack.
685 if (LIKELY(mark_bitmap->HasAddress(obj))) {
686 if (!mark_bitmap->Test(obj)) {
687 // Don't bother un-marking since we clear the mark bitmap anyways.
688 *(out++) = obj;
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700689 }
690 } else if (!large_mark_objects->Test(obj)) {
691 ++freed_large_objects;
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700692 freed_bytes += large_object_space->Free(self, obj);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700693 }
694 }
695 logger.AddSplit("Process allocation stack");
696
697 size_t freed_objects = out - objects;
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700698 freed_bytes += space->FreeList(self, freed_objects, objects);
Mathieu Chartier40e978b2012-09-07 11:38:36 -0700699 VLOG(heap) << "Freed " << freed_objects << "/" << count
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700700 << " objects with size " << PrettySize(freed_bytes);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700701 heap_->RecordFree(freed_objects + freed_large_objects, freed_bytes);
Mathieu Chartier40e978b2012-09-07 11:38:36 -0700702 freed_objects_ += freed_objects;
703 freed_bytes_ += freed_bytes;
704 logger.AddSplit("FreeList");
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700705 allocations->Reset();
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800706 logger.AddSplit("ResetStack");
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700707}
708
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700709void MarkSweep::Sweep(TimingLogger& timings, bool partial, bool swap_bitmaps) {
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700710 DCHECK(mark_stack_->IsEmpty());
711
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700712 // If we don't swap bitmaps then newly allocated Weaks go into the live bitmap but not mark
713 // bitmap, resulting in occasional frees of Weaks which are still in use.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700714 SweepSystemWeaks();
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700715 timings.AddSplit("SweepSystemWeaks");
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700716
Mathieu Chartier46a23632012-08-07 18:44:40 -0700717 const Spaces& spaces = heap_->GetSpaces();
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800718 SweepCallbackContext scc;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700719 scc.mark_sweep = this;
Ian Rogers50b35e22012-10-04 10:09:15 -0700720 scc.self = Thread::Current();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700721 // TODO: C++0x auto
722 for (Spaces::const_iterator it = spaces.begin(); it != spaces.end(); ++it) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700723 ContinuousSpace* space = *it;
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700724 if (
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700725 space->GetGcRetentionPolicy() == kGcRetentionPolicyAlwaysCollect ||
726 (!partial && space->GetGcRetentionPolicy() == kGcRetentionPolicyFullCollect)
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700727 ) {
728 uintptr_t begin = reinterpret_cast<uintptr_t>(space->Begin());
729 uintptr_t end = reinterpret_cast<uintptr_t>(space->End());
730 scc.space = space->AsAllocSpace();
731 SpaceBitmap* live_bitmap = space->GetLiveBitmap();
732 SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700733 if (swap_bitmaps) {
734 std::swap(live_bitmap, mark_bitmap);
735 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700736 if (space->GetGcRetentionPolicy() == kGcRetentionPolicyAlwaysCollect) {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700737 // Bitmaps are pre-swapped for optimization which enables sweeping with the heap unlocked.
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700738 SpaceBitmap::SweepWalk(*live_bitmap, *mark_bitmap, begin, end,
739 &SweepCallback, reinterpret_cast<void*>(&scc));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700740 } else {
741 // Zygote sweep takes care of dirtying cards and clearing live bits, does not free actual memory.
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700742 SpaceBitmap::SweepWalk(*live_bitmap, *mark_bitmap, begin, end,
743 &ZygoteSweepCallback, reinterpret_cast<void*>(&scc));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700744 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700745 }
746 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700747 timings.AddSplit("Sweep");
Carl Shapiro58551df2011-07-24 03:09:51 -0700748}
749
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700750void MarkSweep::SweepLargeObjects(bool swap_bitmaps) {
751 // Sweep large objects
752 LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700753 SpaceSetMap* large_live_objects = large_object_space->GetLiveObjects();
754 SpaceSetMap* large_mark_objects = large_object_space->GetMarkObjects();
755 if (swap_bitmaps) {
756 std::swap(large_live_objects, large_mark_objects);
757 }
758 SpaceSetMap::Objects& live_objects = large_live_objects->GetObjects();
759 // O(n*log(n)) but hopefully there are not too many large objects.
760 size_t freed_objects = 0;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700761 size_t freed_bytes = 0;
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700762 // TODO: C++0x
Ian Rogers50b35e22012-10-04 10:09:15 -0700763 Thread* self = Thread::Current();
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700764 for (SpaceSetMap::Objects::iterator it = live_objects.begin(); it != live_objects.end(); ++it) {
765 if (!large_mark_objects->Test(*it)) {
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700766 freed_bytes += large_object_space->Free(self, const_cast<Object*>(*it));
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700767 ++freed_objects;
768 }
769 }
770 freed_objects_ += freed_objects;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700771 freed_bytes_ += freed_bytes;
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700772 // Large objects don't count towards bytes_allocated.
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700773 GetHeap()->RecordFree(freed_objects, freed_bytes);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700774}
775
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700776void MarkSweep::CheckReference(const Object* obj, const Object* ref, MemberOffset offset, bool is_static) {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700777 const Spaces& spaces = heap_->GetSpaces();
778 // TODO: C++0x auto
779 for (Spaces::const_iterator cur = spaces.begin(); cur != spaces.end(); ++cur) {
780 if ((*cur)->IsAllocSpace() && (*cur)->Contains(ref)) {
781 DCHECK(IsMarked(obj));
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700782
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700783 bool is_marked = IsMarked(ref);
784 if (!is_marked) {
785 LOG(INFO) << **cur;
786 LOG(WARNING) << (is_static ? "Static ref'" : "Instance ref'") << PrettyTypeOf(ref)
787 << "' (" << reinterpret_cast<const void*>(ref) << ") in '" << PrettyTypeOf(obj)
788 << "' (" << reinterpret_cast<const void*>(obj) << ") at offset "
789 << reinterpret_cast<void*>(offset.Int32Value()) << " wasn't marked";
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700790
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700791 const Class* klass = is_static ? obj->AsClass() : obj->GetClass();
792 DCHECK(klass != NULL);
793 const ObjectArray<Field>* fields = is_static ? klass->GetSFields() : klass->GetIFields();
794 DCHECK(fields != NULL);
795 bool found = false;
796 for (int32_t i = 0; i < fields->GetLength(); ++i) {
797 const Field* cur = fields->Get(i);
798 if (cur->GetOffset().Int32Value() == offset.Int32Value()) {
799 LOG(WARNING) << "Field referencing the alloc space was " << PrettyField(cur);
800 found = true;
801 break;
802 }
803 }
804 if (!found) {
805 LOG(WARNING) << "Could not find field in object alloc space with offset " << offset.Int32Value();
806 }
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700807
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700808 bool obj_marked = heap_->GetCardTable()->IsDirty(obj);
809 if (!obj_marked) {
810 LOG(WARNING) << "Object '" << PrettyTypeOf(obj) << "' "
811 << "(" << reinterpret_cast<const void*>(obj) << ") contains references to "
812 << "the alloc space, but wasn't card marked";
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700813 }
814 }
Ian Rogers5d76c432011-10-31 21:42:49 -0700815 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700816 break;
Ian Rogers5d76c432011-10-31 21:42:49 -0700817 }
818}
819
Carl Shapiro69759ea2011-07-21 18:13:35 -0700820// Process the "referent" field in a java.lang.ref.Reference. If the
821// referent has not yet been marked, put it on the appropriate list in
822// the gcHeap for later processing.
823void MarkSweep::DelayReferenceReferent(Object* obj) {
824 DCHECK(obj != NULL);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700825 Class* klass = obj->GetClass();
826 DCHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700827 DCHECK(klass->IsReferenceClass());
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800828 Object* pending = obj->GetFieldObject<Object*>(heap_->GetReferencePendingNextOffset(), false);
829 Object* referent = heap_->GetReferenceReferent(obj);
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800830 if (kCountJavaLangRefs) {
831 ++reference_count_;
832 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700833 if (pending == NULL && referent != NULL && !IsMarked(referent)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -0700834 Object** list = NULL;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700835 if (klass->IsSoftReferenceClass()) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700836 list = &soft_reference_list_;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700837 } else if (klass->IsWeakReferenceClass()) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700838 list = &weak_reference_list_;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700839 } else if (klass->IsFinalizerReferenceClass()) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700840 list = &finalizer_reference_list_;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700841 } else if (klass->IsPhantomReferenceClass()) {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700842 list = &phantom_reference_list_;
843 }
Brian Carlstrom0796af02011-10-12 14:31:45 -0700844 DCHECK(list != NULL) << PrettyClass(klass) << " " << std::hex << klass->GetAccessFlags();
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700845 // TODO: One lock per list?
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800846 heap_->EnqueuePendingReference(obj, list);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700847 }
848}
849
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700850void MarkSweep::ScanRoot(const Object* obj) {
851 ScanObject(obj);
852}
853
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700854class MarkObjectVisitor {
855 public:
856 MarkObjectVisitor(MarkSweep* const mark_sweep) : mark_sweep_(mark_sweep) {
857 }
858
859 void operator ()(const Object* /* obj */, const Object* ref, const MemberOffset& /* offset */,
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800860 bool /* is_static */) const EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700861 mark_sweep_->MarkObject(ref);
862 }
863
864 private:
865 MarkSweep* const mark_sweep_;
866};
867
Carl Shapiro69759ea2011-07-21 18:13:35 -0700868// Scans an object reference. Determines the type of the reference
869// and dispatches to a specialized scanning routine.
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700870void MarkSweep::ScanObject(const Object* obj) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700871 MarkObjectVisitor visitor(this);
872 ScanObjectVisit(obj, visitor);
873}
874
875class MarkStackChunk : public Task {
876public:
877 MarkStackChunk(ThreadPool* thread_pool, MarkSweep* mark_sweep, Object** begin, Object** end)
878 : mark_sweep_(mark_sweep),
879 thread_pool_(thread_pool),
880 index_(0),
881 length_(0),
882 output_(NULL) {
883 length_ = end - begin;
884 if (begin != end) {
885 // Cost not significant since we only do this for the initial set of mark stack chunks.
886 memcpy(data_, begin, length_ * sizeof(*begin));
887 }
888 if (kCountTasks) {
889 ++mark_sweep_->work_chunks_created_;
890 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700891 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700892
893 ~MarkStackChunk() {
894 DCHECK(output_ == NULL || output_->length_ == 0);
895 DCHECK_GE(index_, length_);
896 delete output_;
897 if (kCountTasks) {
898 ++mark_sweep_->work_chunks_deleted_;
899 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700900 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700901
902 MarkSweep* const mark_sweep_;
903 ThreadPool* const thread_pool_;
904 static const size_t max_size = 1 * KB;
905 // Index of which object we are scanning. Only needs to be atomic if we are doing work stealing.
906 size_t index_;
907 // Input / output mark stack. We add newly marked references to data_ until length reaches
908 // max_size. This is an optimization so that less tasks are created.
909 // TODO: Investigate using a bounded buffer FIFO.
910 Object* data_[max_size];
911 // How many elements in data_ we need to scan.
912 size_t length_;
913 // Output block, newly marked references get added to the ouput block so that another thread can
914 // scan them.
915 MarkStackChunk* output_;
916
917 class MarkObjectParallelVisitor {
918 public:
919 MarkObjectParallelVisitor(MarkStackChunk* chunk_task) : chunk_task_(chunk_task) {
920
921 }
922
923 void operator ()(const Object* /* obj */, const Object* ref,
924 const MemberOffset& /* offset */, bool /* is_static */) const {
925 if (ref != NULL && chunk_task_->mark_sweep_->MarkObjectParallel(ref)) {
926 chunk_task_->MarkStackPush(ref);
927 }
928 }
929
930 private:
931 MarkStackChunk* const chunk_task_;
932 };
933
934 // Push an object into the block.
935 // Don't need to use atomic ++ since we only one thread is writing to an output block at any
936 // given time.
937 void Push(Object* obj) {
938 data_[length_++] = obj;
939 }
940
941 void MarkStackPush(const Object* obj) {
942 if (static_cast<size_t>(length_) < max_size) {
943 Push(const_cast<Object*>(obj));
944 } else {
945 // Internal buffer is full, push to a new buffer instead.
946 if (UNLIKELY(output_ == NULL)) {
947 AllocateOutputChunk();
948 } else if (UNLIKELY(static_cast<size_t>(output_->length_) == max_size)) {
949 // Output block is full, queue it up for processing and obtain a new block.
950 EnqueueOutput();
951 AllocateOutputChunk();
952 }
953 output_->Push(const_cast<Object*>(obj));
954 }
955 }
956
957 void ScanObject(Object* obj) {
958 mark_sweep_->ScanObjectVisit(obj, MarkObjectParallelVisitor(this));
959 }
960
961 void EnqueueOutput() {
962 if (output_ != NULL) {
963 uint64_t start = 0;
964 if (kMeasureOverhead) {
965 start = NanoTime();
966 }
967 thread_pool_->AddTask(Thread::Current(), output_);
968 output_ = NULL;
969 if (kMeasureOverhead) {
970 mark_sweep_->overhead_time_ += NanoTime() - start;
971 }
972 }
973 }
974
975 void AllocateOutputChunk() {
976 uint64_t start = 0;
977 if (kMeasureOverhead) {
978 start = NanoTime();
979 }
980 output_ = new MarkStackChunk(thread_pool_, mark_sweep_, NULL, NULL);
981 if (kMeasureOverhead) {
982 mark_sweep_->overhead_time_ += NanoTime() - start;
983 }
984 }
985
986 void Finalize() {
987 EnqueueOutput();
988 delete this;
989 }
990
991 // Scans all of the objects
992 virtual void Run(Thread* self) {
993 int index;
994 while ((index = index_++) < length_) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700995 if (kUseMarkStackPrefetch) {
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800996 static const size_t prefetch_look_ahead = 1;
997 __builtin_prefetch(data_[std::min(index + prefetch_look_ahead, length_ - 1)]);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700998 }
999 Object* obj = data_[index];
1000 DCHECK(obj != NULL);
1001 ScanObject(obj);
1002 }
1003 }
1004};
1005
1006void MarkSweep::ProcessMarkStackParallel() {
1007 CHECK(kDisableFinger) << "parallel mark stack processing cannot work when finger is enabled";
1008 Thread* self = Thread::Current();
1009 ThreadPool* thread_pool = GetHeap()->GetThreadPool();
1010 // Split the current mark stack up into work tasks.
1011 const size_t num_threads = thread_pool->GetThreadCount();
1012 const size_t stack_size = mark_stack_->Size();
1013 const size_t chunk_size =
1014 std::min((stack_size + num_threads - 1) / num_threads,
1015 static_cast<size_t>(MarkStackChunk::max_size));
1016 size_t index = 0;
1017 for (size_t i = 0; i < num_threads || index < stack_size; ++i) {
1018 Object** begin = &mark_stack_->Begin()[std::min(stack_size, index)];
1019 Object** end = &mark_stack_->Begin()[std::min(stack_size, index + chunk_size)];
1020 index += chunk_size;
1021 thread_pool->AddTask(self, new MarkStackChunk(thread_pool, this, begin, end));
1022 }
1023 thread_pool->StartWorkers(self);
1024 mark_stack_->Reset();
1025 thread_pool->Wait(self, true);
1026 //LOG(INFO) << "Idle wait time " << PrettyDuration(thread_pool->GetWaitTime());
1027 CHECK_EQ(work_chunks_created_, work_chunks_deleted_) << " some of the work chunks were leaked";
Carl Shapiro69759ea2011-07-21 18:13:35 -07001028}
1029
Ian Rogers5d76c432011-10-31 21:42:49 -07001030// Scan anything that's on the mark stack.
Carl Shapiro69759ea2011-07-21 18:13:35 -07001031void MarkSweep::ProcessMarkStack() {
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001032 ThreadPool* thread_pool = GetHeap()->GetThreadPool();
1033 if (kParallelMarkStack && thread_pool != NULL && thread_pool->GetThreadCount() > 0) {
1034 ProcessMarkStackParallel();
1035 return;
1036 }
1037
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001038 if (kUseMarkStackPrefetch) {
1039 const size_t fifo_size = 4;
1040 const size_t fifo_mask = fifo_size - 1;
1041 const Object* fifo[fifo_size];
1042 for (size_t i = 0;i < fifo_size;++i) {
1043 fifo[i] = NULL;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001044 }
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001045 size_t fifo_pos = 0;
1046 size_t fifo_count = 0;
1047 for (;;) {
1048 const Object* obj = fifo[fifo_pos & fifo_mask];
1049 if (obj != NULL) {
1050 ScanObject(obj);
1051 fifo[fifo_pos & fifo_mask] = NULL;
1052 --fifo_count;
1053 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001054
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001055 if (!mark_stack_->IsEmpty()) {
1056 const Object* obj = mark_stack_->PopBack();
1057 DCHECK(obj != NULL);
1058 fifo[fifo_pos & fifo_mask] = obj;
1059 __builtin_prefetch(obj);
1060 fifo_count++;
1061 }
1062 fifo_pos++;
1063
1064 if (!fifo_count) {
1065 CHECK(mark_stack_->IsEmpty()) << mark_stack_->Size();
1066 break;
1067 }
1068 }
1069 } else {
1070 while (!mark_stack_->IsEmpty()) {
1071 const Object* obj = mark_stack_->PopBack();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001072 DCHECK(obj != NULL);
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001073 ScanObject(obj);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001074 }
1075 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001076}
1077
Carl Shapiro69759ea2011-07-21 18:13:35 -07001078// Walks the reference list marking any references subject to the
1079// reference clearing policy. References with a black referent are
1080// removed from the list. References with white referents biased
1081// toward saving are blackened and also removed from the list.
1082void MarkSweep::PreserveSomeSoftReferences(Object** list) {
1083 DCHECK(list != NULL);
1084 Object* clear = NULL;
1085 size_t counter = 0;
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001086
1087 DCHECK(mark_stack_->IsEmpty());
1088
Carl Shapiro69759ea2011-07-21 18:13:35 -07001089 while (*list != NULL) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001090 Object* ref = heap_->DequeuePendingReference(list);
1091 Object* referent = heap_->GetReferenceReferent(ref);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001092 if (referent == NULL) {
1093 // Referent was cleared by the user during marking.
1094 continue;
1095 }
1096 bool is_marked = IsMarked(referent);
1097 if (!is_marked && ((++counter) & 1)) {
1098 // Referent is white and biased toward saving, mark it.
1099 MarkObject(referent);
1100 is_marked = true;
1101 }
1102 if (!is_marked) {
1103 // Referent is white, queue it for clearing.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001104 heap_->EnqueuePendingReference(ref, &clear);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001105 }
1106 }
1107 *list = clear;
1108 // Restart the mark with the newly black references added to the
1109 // root set.
1110 ProcessMarkStack();
1111}
1112
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001113inline bool MarkSweep::IsMarked(const Object* object) const
1114 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
1115 if (object >= immune_begin_ && object < immune_end_) {
1116 return true;
1117 }
1118 DCHECK(current_mark_bitmap_ != NULL);
1119 if (current_mark_bitmap_->HasAddress(object)) {
1120 return current_mark_bitmap_->Test(object);
1121 }
1122 return heap_->GetMarkBitmap()->Test(object);
1123}
1124
1125
Carl Shapiro69759ea2011-07-21 18:13:35 -07001126// Unlink the reference list clearing references objects with white
1127// referents. Cleared references registered to a reference queue are
1128// scheduled for appending by the heap worker thread.
1129void MarkSweep::ClearWhiteReferences(Object** list) {
1130 DCHECK(list != NULL);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001131 while (*list != NULL) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001132 Object* ref = heap_->DequeuePendingReference(list);
1133 Object* referent = heap_->GetReferenceReferent(ref);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001134 if (referent != NULL && !IsMarked(referent)) {
1135 // Referent is white, clear it.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001136 heap_->ClearReferenceReferent(ref);
1137 if (heap_->IsEnqueuable(ref)) {
1138 heap_->EnqueueReference(ref, &cleared_reference_list_);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001139 }
1140 }
1141 }
1142 DCHECK(*list == NULL);
1143}
1144
1145// Enqueues finalizer references with white referents. White
1146// referents are blackened, moved to the zombie field, and the
1147// referent field is cleared.
1148void MarkSweep::EnqueueFinalizerReferences(Object** list) {
1149 DCHECK(list != NULL);
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001150 MemberOffset zombie_offset = heap_->GetFinalizerReferenceZombieOffset();
Carl Shapiro69759ea2011-07-21 18:13:35 -07001151 bool has_enqueued = false;
1152 while (*list != NULL) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001153 Object* ref = heap_->DequeuePendingReference(list);
1154 Object* referent = heap_->GetReferenceReferent(ref);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001155 if (referent != NULL && !IsMarked(referent)) {
1156 MarkObject(referent);
1157 // If the referent is non-null the reference must queuable.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001158 DCHECK(heap_->IsEnqueuable(ref));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001159 ref->SetFieldObject(zombie_offset, referent, false);
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001160 heap_->ClearReferenceReferent(ref);
1161 heap_->EnqueueReference(ref, &cleared_reference_list_);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001162 has_enqueued = true;
1163 }
1164 }
1165 if (has_enqueued) {
1166 ProcessMarkStack();
1167 }
1168 DCHECK(*list == NULL);
1169}
1170
Carl Shapiro58551df2011-07-24 03:09:51 -07001171// Process reference class instances and schedule finalizations.
Carl Shapiro69759ea2011-07-21 18:13:35 -07001172void MarkSweep::ProcessReferences(Object** soft_references, bool clear_soft,
1173 Object** weak_references,
1174 Object** finalizer_references,
1175 Object** phantom_references) {
1176 DCHECK(soft_references != NULL);
1177 DCHECK(weak_references != NULL);
1178 DCHECK(finalizer_references != NULL);
1179 DCHECK(phantom_references != NULL);
1180
1181 // Unless we are in the zygote or required to clear soft references
1182 // with white references, preserve some white referents.
Ian Rogers2945e242012-06-03 14:45:16 -07001183 if (!clear_soft && !Runtime::Current()->IsZygote()) {
Carl Shapiro69759ea2011-07-21 18:13:35 -07001184 PreserveSomeSoftReferences(soft_references);
1185 }
1186
1187 // Clear all remaining soft and weak references with white
1188 // referents.
1189 ClearWhiteReferences(soft_references);
1190 ClearWhiteReferences(weak_references);
1191
1192 // Preserve all white objects with finalize methods and schedule
1193 // them for finalization.
1194 EnqueueFinalizerReferences(finalizer_references);
1195
1196 // Clear all f-reachable soft and weak references with white
1197 // referents.
1198 ClearWhiteReferences(soft_references);
1199 ClearWhiteReferences(weak_references);
1200
1201 // Clear all phantom references with white referents.
1202 ClearWhiteReferences(phantom_references);
1203
1204 // At this point all reference lists should be empty.
1205 DCHECK(*soft_references == NULL);
1206 DCHECK(*weak_references == NULL);
1207 DCHECK(*finalizer_references == NULL);
1208 DCHECK(*phantom_references == NULL);
1209}
1210
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001211void MarkSweep::UnBindBitmaps() {
1212 const Spaces& spaces = heap_->GetSpaces();
1213 // TODO: C++0x auto
1214 for (Spaces::const_iterator it = spaces.begin(); it != spaces.end(); ++it) {
1215 Space* space = *it;
1216 if (space->IsAllocSpace()) {
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -07001217 DlMallocSpace* alloc_space = space->AsAllocSpace();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001218 if (alloc_space->temp_bitmap_.get() != NULL) {
1219 // At this point, the temp_bitmap holds our old mark bitmap.
1220 SpaceBitmap* new_bitmap = alloc_space->temp_bitmap_.release();
1221 GetHeap()->GetMarkBitmap()->ReplaceBitmap(alloc_space->mark_bitmap_.get(), new_bitmap);
1222 CHECK_EQ(alloc_space->mark_bitmap_.release(), alloc_space->live_bitmap_.get());
1223 alloc_space->mark_bitmap_.reset(new_bitmap);
1224 DCHECK(alloc_space->temp_bitmap_.get() == NULL);
1225 }
1226 }
1227 }
1228}
1229
Carl Shapiro69759ea2011-07-21 18:13:35 -07001230MarkSweep::~MarkSweep() {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001231 if (kCountScannedTypes) {
1232 VLOG(gc) << "MarkSweep scanned classes=" << class_count_ << " arrays=" << array_count_
1233 << " other=" << other_count_;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001234 }
1235
1236 if (kCountTasks) {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001237 VLOG(gc) << "Total number of work chunks allocated: " << work_chunks_created_;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001238 }
1239
1240 if (kMeasureOverhead) {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001241 VLOG(gc) << "Overhead time " << PrettyDuration(overhead_time_);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001242 }
1243
1244 if (kProfileLargeObjects) {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001245 VLOG(gc) << "Large objects tested " << large_object_test_ << " marked " << large_object_mark_;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001246 }
1247
1248 if (kCountClassesMarked) {
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001249 VLOG(gc) << "Classes marked " << classes_marked_;
1250 }
1251
1252 if (kCountJavaLangRefs) {
1253 VLOG(gc) << "References scanned " << reference_count_;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001254 }
1255
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001256 // Ensure that the mark stack is empty.
1257 CHECK(mark_stack_->IsEmpty());
1258
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001259 // Clear all of the spaces' mark bitmaps.
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001260 const Spaces& spaces = heap_->GetSpaces();
1261 // TODO: C++0x auto
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001262 for (Spaces::const_iterator it = spaces.begin(); it != spaces.end(); ++it) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001263 ContinuousSpace* space = *it;
1264 if (space->GetGcRetentionPolicy() != kGcRetentionPolicyNeverCollect) {
1265 space->GetMarkBitmap()->Clear();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001266 }
1267 }
Mathieu Chartier5301cd22012-05-31 12:11:36 -07001268 mark_stack_->Reset();
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001269
1270 // Reset the marked large objects.
1271 LargeObjectSpace* large_objects = GetHeap()->GetLargeObjectsSpace();
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001272 large_objects->GetMarkObjects()->Clear();
Carl Shapiro69759ea2011-07-21 18:13:35 -07001273}
1274
1275} // namespace art