blob: d7c9584ae6ad2eb6fb395c3bc778377978579dc0 [file] [log] [blame]
Carl Shapiro69759ea2011-07-21 18:13:35 -07001// Copyright 2011 Google Inc. All Rights Reserved.
Carl Shapiro69759ea2011-07-21 18:13:35 -07002
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003#include "heap.h"
Carl Shapiro58551df2011-07-24 03:09:51 -07004
Brian Carlstrom58ae9412011-10-04 00:56:06 -07005#include <limits>
Carl Shapiro58551df2011-07-24 03:09:51 -07006#include <vector>
7
Elliott Hughes90a33692011-08-30 13:27:07 -07008#include "UniquePtr.h"
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07009#include "image.h"
Carl Shapiro58551df2011-07-24 03:09:51 -070010#include "mark_sweep.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070011#include "object.h"
12#include "space.h"
Carl Shapiro58551df2011-07-24 03:09:51 -070013#include "stl_util.h"
Elliott Hughes307f75d2011-10-12 18:04:40 -070014#include "timing_logger.h"
Elliott Hughes8d768a92011-09-14 16:35:25 -070015#include "thread_list.h"
Carl Shapiro69759ea2011-07-21 18:13:35 -070016
17namespace art {
18
Carl Shapiro58551df2011-07-24 03:09:51 -070019std::vector<Space*> Heap::spaces_;
Carl Shapiro69759ea2011-07-21 18:13:35 -070020
Brian Carlstrom4a289ed2011-08-16 17:17:49 -070021Space* Heap::alloc_space_ = NULL;
Carl Shapiro69759ea2011-07-21 18:13:35 -070022
23size_t Heap::maximum_size_ = 0;
24
Carl Shapiro58551df2011-07-24 03:09:51 -070025size_t Heap::num_bytes_allocated_ = 0;
26
27size_t Heap::num_objects_allocated_ = 0;
28
Carl Shapiro69759ea2011-07-21 18:13:35 -070029bool Heap::is_gc_running_ = false;
30
31HeapBitmap* Heap::mark_bitmap_ = NULL;
32
33HeapBitmap* Heap::live_bitmap_ = NULL;
34
Elliott Hughesadb460d2011-10-05 17:02:34 -070035Class* Heap::java_lang_ref_FinalizerReference_ = NULL;
36Class* Heap::java_lang_ref_ReferenceQueue_ = NULL;
37
Ian Rogers0cfe1fb2011-08-26 03:29:44 -070038MemberOffset Heap::reference_referent_offset_ = MemberOffset(0);
39MemberOffset Heap::reference_queue_offset_ = MemberOffset(0);
40MemberOffset Heap::reference_queueNext_offset_ = MemberOffset(0);
41MemberOffset Heap::reference_pendingNext_offset_ = MemberOffset(0);
42MemberOffset Heap::finalizer_reference_zombie_offset_ = MemberOffset(0);
Brian Carlstrom1f870082011-08-23 16:02:11 -070043
Brian Carlstrom395520e2011-09-25 19:35:00 -070044float Heap::target_utilization_ = 0.5;
45
Elliott Hughes92b3b562011-09-08 16:32:26 -070046Mutex* Heap::lock_ = NULL;
47
Elliott Hughes9d5ccec2011-09-19 13:19:50 -070048bool Heap::verify_objects_ = false;
49
Elliott Hughes92b3b562011-09-08 16:32:26 -070050class ScopedHeapLock {
51 public:
52 ScopedHeapLock() {
53 Heap::Lock();
54 }
55
56 ~ScopedHeapLock() {
57 Heap::Unlock();
58 }
59};
60
Elliott Hughesbe759c62011-09-08 19:38:21 -070061void Heap::Init(size_t initial_size, size_t maximum_size,
Brian Carlstrom58ae9412011-10-04 00:56:06 -070062 const std::vector<std::string>& image_file_names) {
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -070063 const Runtime* runtime = Runtime::Current();
64 if (runtime->IsVerboseStartup()) {
65 LOG(INFO) << "Heap::Init entering";
66 }
67
Brian Carlstrom58ae9412011-10-04 00:56:06 -070068 // bounds of all spaces for allocating live and mark bitmaps
69 // there will be at least one space (the alloc space),
70 // so set to base to max and limit to min to start
71 byte* base = reinterpret_cast<byte*>(std::numeric_limits<uintptr_t>::max());
72 byte* limit = reinterpret_cast<byte*>(std::numeric_limits<uintptr_t>::min());
Brian Carlstrom4a289ed2011-08-16 17:17:49 -070073
Brian Carlstrom58ae9412011-10-04 00:56:06 -070074 byte* requested_base = NULL;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070075 std::vector<Space*> image_spaces;
76 for (size_t i = 0; i < image_file_names.size(); i++) {
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -070077 Space* space = Space::CreateFromImage(image_file_names[i]);
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070078 if (space == NULL) {
Elliott Hughesbe759c62011-09-08 19:38:21 -070079 LOG(FATAL) << "Failed to create space from " << image_file_names[i];
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070080 }
81 image_spaces.push_back(space);
82 spaces_.push_back(space);
Brian Carlstrome24fa612011-09-29 00:53:55 -070083 byte* oat_limit_addr = space->GetImageHeader().GetOatLimitAddr();
Brian Carlstrom58ae9412011-10-04 00:56:06 -070084 if (oat_limit_addr > requested_base) {
85 requested_base = reinterpret_cast<byte*>(RoundUp(reinterpret_cast<uintptr_t>(oat_limit_addr),
86 kPageSize));
87 }
88 base = std::min(base, space->GetBase());
89 limit = std::max(limit, space->GetLimit());
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070090 }
91
Elliott Hughes307f75d2011-10-12 18:04:40 -070092 alloc_space_ = Space::Create("alloc space", initial_size, maximum_size, requested_base);
93 if (alloc_space_ == NULL) {
Elliott Hughesbe759c62011-09-08 19:38:21 -070094 LOG(FATAL) << "Failed to create alloc space";
Carl Shapiro69759ea2011-07-21 18:13:35 -070095 }
Elliott Hughes307f75d2011-10-12 18:04:40 -070096 base = std::min(base, alloc_space_->GetBase());
97 limit = std::max(limit, alloc_space_->GetLimit());
Brian Carlstrom4a289ed2011-08-16 17:17:49 -070098 DCHECK_LT(base, limit);
99 size_t num_bytes = limit - base;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700100
101 // Allocate the initial live bitmap.
Elliott Hughes90a33692011-08-30 13:27:07 -0700102 UniquePtr<HeapBitmap> live_bitmap(HeapBitmap::Create(base, num_bytes));
103 if (live_bitmap.get() == NULL) {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700104 LOG(FATAL) << "Failed to create live bitmap";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700105 }
106
107 // Allocate the initial mark bitmap.
Elliott Hughes90a33692011-08-30 13:27:07 -0700108 UniquePtr<HeapBitmap> mark_bitmap(HeapBitmap::Create(base, num_bytes));
109 if (mark_bitmap.get() == NULL) {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700110 LOG(FATAL) << "Failed to create mark bitmap";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700111 }
112
Elliott Hughes307f75d2011-10-12 18:04:40 -0700113 spaces_.push_back(alloc_space_);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700114 maximum_size_ = maximum_size;
115 live_bitmap_ = live_bitmap.release();
116 mark_bitmap_ = mark_bitmap.release();
117
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700118 num_bytes_allocated_ = 0;
119 num_objects_allocated_ = 0;
120
Carl Shapiro69759ea2011-07-21 18:13:35 -0700121 // TODO: allocate the card table
122
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700123 // Make image objects live (after live_bitmap_ is set)
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700124 for (size_t i = 0; i < image_spaces.size(); i++) {
125 RecordImageAllocations(image_spaces[i]);
126 }
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700127
Elliott Hughes85d15452011-09-16 17:33:01 -0700128 Heap::EnableObjectValidation();
129
Elliott Hughes92b3b562011-09-08 16:32:26 -0700130 // It's still to early to take a lock because there are no threads yet,
131 // but we can create the heap lock now. We don't create it earlier to
132 // make it clear that you can't use locks during heap initialization.
Elliott Hughes8daa0922011-09-11 13:46:25 -0700133 lock_ = new Mutex("Heap lock");
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700134
135 if (runtime->IsVerboseStartup()) {
136 LOG(INFO) << "Heap::Init exiting";
137 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700138}
139
140void Heap::Destroy() {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700141 ScopedHeapLock lock;
Carl Shapiro58551df2011-07-24 03:09:51 -0700142 STLDeleteElements(&spaces_);
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700143 if (mark_bitmap_ != NULL) {
144 delete mark_bitmap_;
145 mark_bitmap_ = NULL;
146 }
147 if (live_bitmap_ != NULL) {
148 delete live_bitmap_;
149 }
150 live_bitmap_ = NULL;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700151}
152
Elliott Hughes418dfe72011-10-06 18:56:27 -0700153Object* Heap::AllocObject(Class* klass, size_t byte_count) {
154 {
155 ScopedHeapLock lock;
156 DCHECK(klass == NULL || klass->GetDescriptor() == NULL ||
157 (klass->IsClassClass() && byte_count >= sizeof(Class)) ||
158 (klass->IsVariableSize() || klass->GetObjectSize() == byte_count));
159 DCHECK_GE(byte_count, sizeof(Object));
160 Object* obj = AllocateLocked(byte_count);
161 if (obj != NULL) {
162 obj->SetClass(klass);
163 return obj;
164 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700165 }
Elliott Hughes418dfe72011-10-06 18:56:27 -0700166
167 Thread::Current()->ThrowOutOfMemoryError(klass, byte_count);
168 return NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700169}
170
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700171bool Heap::IsHeapAddress(const Object* obj) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700172 // Note: we deliberately don't take the lock here, and mustn't test anything that would
173 // require taking the lock.
Elliott Hughes06b37d92011-10-16 11:51:29 -0700174 if (!IsAligned<kObjectAlignment>(obj)) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700175 return false;
176 }
177 // TODO
178 return true;
179}
180
Elliott Hughes3e465b12011-09-02 18:26:12 -0700181#if VERIFY_OBJECT_ENABLED
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700182void Heap::VerifyObject(const Object* obj) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700183 if (!verify_objects_) {
184 return;
185 }
Elliott Hughes92b3b562011-09-08 16:32:26 -0700186 ScopedHeapLock lock;
187 Heap::VerifyObjectLocked(obj);
188}
189#endif
190
191void Heap::VerifyObjectLocked(const Object* obj) {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700192 lock_->AssertHeld();
Elliott Hughes85d15452011-09-16 17:33:01 -0700193 if (obj != NULL) {
Elliott Hughes06b37d92011-10-16 11:51:29 -0700194 if (!IsAligned<kObjectAlignment>(obj)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700195 LOG(FATAL) << "Object isn't aligned: " << obj;
196 } else if (!live_bitmap_->Test(obj)) {
197 // TODO: we don't hold a lock here as it is assumed the live bit map
198 // isn't changing if the mutator is running.
199 LOG(FATAL) << "Object is dead: " << obj;
200 }
201 // Ignore early dawn of the universe verifications
Brian Carlstromdbc05252011-09-09 01:59:59 -0700202 if (num_objects_allocated_ > 10) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700203 const byte* raw_addr = reinterpret_cast<const byte*>(obj) +
204 Object::ClassOffset().Int32Value();
205 const Class* c = *reinterpret_cast<Class* const *>(raw_addr);
206 if (c == NULL) {
207 LOG(FATAL) << "Null class" << " in object: " << obj;
Elliott Hughes06b37d92011-10-16 11:51:29 -0700208 } else if (!IsAligned<kObjectAlignment>(c)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700209 LOG(FATAL) << "Class isn't aligned: " << c << " in object: " << obj;
210 } else if (!live_bitmap_->Test(c)) {
211 LOG(FATAL) << "Class of object is dead: " << c << " in object: " << obj;
212 }
213 // Check obj.getClass().getClass() == obj.getClass().getClass().getClass()
Ian Rogersad25ac52011-10-04 19:13:33 -0700214 // Note: we don't use the accessors here as they have internal sanity checks
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700215 // that we don't want to run
216 raw_addr = reinterpret_cast<const byte*>(c) +
217 Object::ClassOffset().Int32Value();
218 const Class* c_c = *reinterpret_cast<Class* const *>(raw_addr);
219 raw_addr = reinterpret_cast<const byte*>(c_c) +
220 Object::ClassOffset().Int32Value();
221 const Class* c_c_c = *reinterpret_cast<Class* const *>(raw_addr);
222 CHECK_EQ(c_c, c_c_c);
223 }
224 }
225}
226
Brian Carlstrom78128a62011-09-15 17:21:19 -0700227void Heap::VerificationCallback(Object* obj, void* arg) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700228 DCHECK(obj != NULL);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700229 Heap::VerifyObjectLocked(obj);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700230}
231
232void Heap::VerifyHeap() {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700233 ScopedHeapLock lock;
234 live_bitmap_->Walk(Heap::VerificationCallback, NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700235}
236
Elliott Hughes92b3b562011-09-08 16:32:26 -0700237void Heap::RecordAllocationLocked(Space* space, const Object* obj) {
238#ifndef NDEBUG
239 if (Runtime::Current()->IsStarted()) {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700240 lock_->AssertHeld();
Elliott Hughes92b3b562011-09-08 16:32:26 -0700241 }
242#endif
Carl Shapiro58551df2011-07-24 03:09:51 -0700243 size_t size = space->AllocationSize(obj);
244 DCHECK_NE(size, 0u);
245 num_bytes_allocated_ += size;
246 num_objects_allocated_ += 1;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700247
248 if (Runtime::Current()->HasStatsEnabled()) {
249 RuntimeStats* global_stats = Runtime::Current()->GetStats();
250 RuntimeStats* thread_stats = Thread::Current()->GetStats();
251 ++global_stats->allocated_objects;
252 ++thread_stats->allocated_objects;
253 global_stats->allocated_bytes += size;
254 thread_stats->allocated_bytes += size;
255 }
256
Carl Shapiro58551df2011-07-24 03:09:51 -0700257 live_bitmap_->Set(obj);
258}
259
Elliott Hughes307f75d2011-10-12 18:04:40 -0700260void Heap::RecordFreeLocked(size_t freed_objects, size_t freed_bytes) {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700261 lock_->AssertHeld();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700262
263 if (freed_objects < num_objects_allocated_) {
264 num_objects_allocated_ -= freed_objects;
265 } else {
266 num_objects_allocated_ = 0;
267 }
268 if (freed_bytes < num_bytes_allocated_) {
269 num_bytes_allocated_ -= freed_bytes;
Carl Shapiro58551df2011-07-24 03:09:51 -0700270 } else {
271 num_bytes_allocated_ = 0;
272 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700273
274 if (Runtime::Current()->HasStatsEnabled()) {
275 RuntimeStats* global_stats = Runtime::Current()->GetStats();
276 RuntimeStats* thread_stats = Thread::Current()->GetStats();
277 ++global_stats->freed_objects;
278 ++thread_stats->freed_objects;
Elliott Hughes307f75d2011-10-12 18:04:40 -0700279 global_stats->freed_bytes += freed_bytes;
280 thread_stats->freed_bytes += freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700281 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700282}
283
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700284void Heap::RecordImageAllocations(Space* space) {
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700285 const Runtime* runtime = Runtime::Current();
286 if (runtime->IsVerboseStartup()) {
287 LOG(INFO) << "Heap::RecordImageAllocations entering";
288 }
Elliott Hughes92b3b562011-09-08 16:32:26 -0700289 DCHECK(!Runtime::Current()->IsStarted());
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700290 CHECK(space != NULL);
291 CHECK(live_bitmap_ != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700292 byte* current = space->GetBase() + RoundUp(sizeof(ImageHeader), kObjectAlignment);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700293 while (current < space->GetLimit()) {
Elliott Hughes06b37d92011-10-16 11:51:29 -0700294 DCHECK_ALIGNED(current, kObjectAlignment);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700295 const Object* obj = reinterpret_cast<const Object*>(current);
296 live_bitmap_->Set(obj);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700297 current += RoundUp(obj->SizeOf(), kObjectAlignment);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700298 }
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700299 if (runtime->IsVerboseStartup()) {
300 LOG(INFO) << "Heap::RecordImageAllocations exiting";
301 }
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700302}
303
Elliott Hughes92b3b562011-09-08 16:32:26 -0700304Object* Heap::AllocateLocked(size_t size) {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700305 lock_->AssertHeld();
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700306 DCHECK(alloc_space_ != NULL);
307 Space* space = alloc_space_;
Elliott Hughes92b3b562011-09-08 16:32:26 -0700308 Object* obj = AllocateLocked(space, size);
Carl Shapiro58551df2011-07-24 03:09:51 -0700309 if (obj != NULL) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700310 RecordAllocationLocked(space, obj);
Carl Shapiro58551df2011-07-24 03:09:51 -0700311 }
312 return obj;
313}
314
Elliott Hughes92b3b562011-09-08 16:32:26 -0700315Object* Heap::AllocateLocked(Space* space, size_t size) {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700316 lock_->AssertHeld();
Elliott Hughes92b3b562011-09-08 16:32:26 -0700317
Carl Shapiro69759ea2011-07-21 18:13:35 -0700318 // Fail impossible allocations. TODO: collect soft references.
319 if (size > maximum_size_) {
320 return NULL;
321 }
322
Carl Shapiro58551df2011-07-24 03:09:51 -0700323 Object* ptr = space->AllocWithoutGrowth(size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700324 if (ptr != NULL) {
325 return ptr;
326 }
327
328 // The allocation failed. If the GC is running, block until it
329 // completes and retry.
330 if (is_gc_running_) {
331 // The GC is concurrently tracing the heap. Release the heap
332 // lock, wait for the GC to complete, and retrying allocating.
333 WaitForConcurrentGcToComplete();
Carl Shapiro58551df2011-07-24 03:09:51 -0700334 ptr = space->AllocWithoutGrowth(size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700335 if (ptr != NULL) {
336 return ptr;
337 }
338 }
339
340 // Another failure. Our thread was starved or there may be too many
341 // live objects. Try a foreground GC. This will have no effect if
342 // the concurrent GC is already running.
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700343 if (Runtime::Current()->HasStatsEnabled()) {
344 ++Runtime::Current()->GetStats()->gc_for_alloc_count;
345 ++Thread::Current()->GetStats()->gc_for_alloc_count;
346 }
Elliott Hughes418dfe72011-10-06 18:56:27 -0700347 LOG(INFO) << "GC_FOR_ALLOC: AllocWithoutGrowth: TODO: test";
Carl Shapiro58551df2011-07-24 03:09:51 -0700348 CollectGarbageInternal();
349 ptr = space->AllocWithoutGrowth(size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700350 if (ptr != NULL) {
351 return ptr;
352 }
353
Elliott Hughes418dfe72011-10-06 18:56:27 -0700354 LOG(INFO) << "GC_FOR_ALLOC: AllocWithGrowth: TODO: test";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700355 // Even that didn't work; this is an exceptional state.
356 // Try harder, growing the heap if necessary.
Carl Shapiro58551df2011-07-24 03:09:51 -0700357 ptr = space->AllocWithGrowth(size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700358 if (ptr != NULL) {
359 //size_t new_footprint = dvmHeapSourceGetIdealFootprint();
Shih-wei Liao7f1caab2011-10-06 12:11:04 -0700360 size_t new_footprint = space->GetMaxAllowedFootprint();
Elliott Hughes418dfe72011-10-06 18:56:27 -0700361 // OLD-TODO: may want to grow a little bit more so that the amount of
Carl Shapiro58551df2011-07-24 03:09:51 -0700362 // free space is equal to the old free space + the
363 // utilization slop for the new allocation.
364 LOG(INFO) << "Grow heap (frag case) to " << new_footprint / MB
Carl Shapiro69759ea2011-07-21 18:13:35 -0700365 << "for " << size << "-byte allocation";
366 return ptr;
367 }
368
369 // Most allocations should have succeeded by now, so the heap is
370 // really full, really fragmented, or the requested size is really
371 // big. Do another GC, collecting SoftReferences this time. The VM
372 // spec requires that all SoftReferences have been collected and
373 // cleared before throwing an OOME.
374
Elliott Hughes418dfe72011-10-06 18:56:27 -0700375 // OLD-TODO: wait for the finalizers from the previous GC to finish
Carl Shapiro69759ea2011-07-21 18:13:35 -0700376 LOG(INFO) << "Forcing collection of SoftReferences for "
377 << size << "-byte allocation";
Carl Shapiro58551df2011-07-24 03:09:51 -0700378 CollectGarbageInternal();
379 ptr = space->AllocWithGrowth(size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700380 if (ptr != NULL) {
381 return ptr;
382 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700383
Carl Shapiro69759ea2011-07-21 18:13:35 -0700384 LOG(ERROR) << "Out of memory on a " << size << " byte allocation";
385
Carl Shapiro58551df2011-07-24 03:09:51 -0700386 // TODO: tell the HeapSource to dump its state
387 // TODO: dump stack traces for all threads
Carl Shapiro69759ea2011-07-21 18:13:35 -0700388
Carl Shapiro69759ea2011-07-21 18:13:35 -0700389 return NULL;
390}
391
Elliott Hughesbf86d042011-08-31 17:53:14 -0700392int64_t Heap::GetMaxMemory() {
393 UNIMPLEMENTED(WARNING);
394 return 0;
395}
396
397int64_t Heap::GetTotalMemory() {
398 UNIMPLEMENTED(WARNING);
399 return 0;
400}
401
402int64_t Heap::GetFreeMemory() {
403 UNIMPLEMENTED(WARNING);
404 return 0;
405}
406
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700407class InstanceCounter {
408 public:
409 InstanceCounter(Class* c, bool count_assignable)
410 : class_(c), count_assignable_(count_assignable), count_(0) {
411 }
412
413 size_t GetCount() {
414 return count_;
415 }
416
417 static void Callback(Object* o, void* arg) {
418 reinterpret_cast<InstanceCounter*>(arg)->VisitInstance(o);
419 }
420
421 private:
422 void VisitInstance(Object* o) {
423 Class* instance_class = o->GetClass();
424 if (count_assignable_) {
425 if (instance_class == class_) {
426 ++count_;
427 }
428 } else {
429 if (instance_class != NULL && class_->IsAssignableFrom(instance_class)) {
430 ++count_;
431 }
432 }
433 }
434
435 Class* class_;
436 bool count_assignable_;
437 size_t count_;
438};
439
440int64_t Heap::CountInstances(Class* c, bool count_assignable) {
441 ScopedHeapLock lock;
442 InstanceCounter counter(c, count_assignable);
443 live_bitmap_->Walk(InstanceCounter::Callback, &counter);
444 return counter.GetCount();
445}
446
Carl Shapiro69759ea2011-07-21 18:13:35 -0700447void Heap::CollectGarbage() {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700448 ScopedHeapLock lock;
Carl Shapiro58551df2011-07-24 03:09:51 -0700449 CollectGarbageInternal();
Carl Shapiro69759ea2011-07-21 18:13:35 -0700450}
451
452void Heap::CollectGarbageInternal() {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700453 lock_->AssertHeld();
Carl Shapiro58551df2011-07-24 03:09:51 -0700454
Elliott Hughes8d768a92011-09-14 16:35:25 -0700455 ThreadList* thread_list = Runtime::Current()->GetThreadList();
456 thread_list->SuspendAll();
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700457
458 size_t initial_size = num_bytes_allocated_;
Elliott Hughes307f75d2011-10-12 18:04:40 -0700459 TimingLogger timings("CollectGarbageInternal");
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700460 uint64_t t0 = NanoTime();
Elliott Hughesadb460d2011-10-05 17:02:34 -0700461 Object* cleared_references = NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700462 {
463 MarkSweep mark_sweep;
Elliott Hughes307f75d2011-10-12 18:04:40 -0700464 timings.AddSplit("ctor");
Carl Shapiro58551df2011-07-24 03:09:51 -0700465
466 mark_sweep.Init();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700467 timings.AddSplit("Init");
Carl Shapiro58551df2011-07-24 03:09:51 -0700468
469 mark_sweep.MarkRoots();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700470 timings.AddSplit("MarkRoots");
Carl Shapiro58551df2011-07-24 03:09:51 -0700471
472 // Push marked roots onto the mark stack
473
474 // TODO: if concurrent
475 // unlock heap
Elliott Hughes8d768a92011-09-14 16:35:25 -0700476 // thread_list->ResumeAll();
Carl Shapiro58551df2011-07-24 03:09:51 -0700477
478 mark_sweep.RecursiveMark();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700479 timings.AddSplit("RecursiveMark");
Carl Shapiro58551df2011-07-24 03:09:51 -0700480
481 // TODO: if concurrent
482 // lock heap
Elliott Hughes8d768a92011-09-14 16:35:25 -0700483 // thread_list->SuspendAll();
Carl Shapiro58551df2011-07-24 03:09:51 -0700484 // re-mark root set
485 // scan dirty objects
486
487 mark_sweep.ProcessReferences(false);
Elliott Hughes307f75d2011-10-12 18:04:40 -0700488 timings.AddSplit("ProcessReferences");
Carl Shapiro58551df2011-07-24 03:09:51 -0700489
Elliott Hughes2da50362011-10-10 16:57:08 -0700490 // TODO: if concurrent
491 // swap bitmaps
Carl Shapiro58551df2011-07-24 03:09:51 -0700492
493 mark_sweep.Sweep();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700494 timings.AddSplit("Sweep");
Elliott Hughesadb460d2011-10-05 17:02:34 -0700495
496 cleared_references = mark_sweep.GetClearedReferences();
Carl Shapiro58551df2011-07-24 03:09:51 -0700497 }
498
499 GrowForUtilization();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700500 timings.AddSplit("GrowForUtilization");
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700501 uint64_t t1 = NanoTime();
Elliott Hughes8d768a92011-09-14 16:35:25 -0700502 thread_list->ResumeAll();
Elliott Hughesadb460d2011-10-05 17:02:34 -0700503
504 EnqueueClearedReferences(&cleared_references);
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700505
506 // TODO: somehow make the specific GC implementation (here MarkSweep) responsible for logging.
507 size_t bytes_freed = initial_size - num_bytes_allocated_;
508 bool is_small = (bytes_freed > 0 && bytes_freed < 1024);
509 size_t kib_freed = (bytes_freed > 0 ? std::max(bytes_freed/1024, 1U) : 0);
510
511 size_t footprint = alloc_space_->Size();
512 size_t percentFree = 100 - static_cast<size_t>(100.0f * float(num_bytes_allocated_) / footprint);
513
514 uint32_t duration = (t1 - t0)/1000/1000;
515 LOG(INFO) << "GC freed " << (is_small ? "<" : "") << kib_freed << "KiB, "
516 << percentFree << "% free "
517 << (num_bytes_allocated_/1024) << "KiB/" << (footprint/1024) << "KiB, "
518 << "paused " << duration << "ms";
Elliott Hughes307f75d2011-10-12 18:04:40 -0700519 timings.Dump();
Carl Shapiro69759ea2011-07-21 18:13:35 -0700520}
521
522void Heap::WaitForConcurrentGcToComplete() {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700523 lock_->AssertHeld();
Carl Shapiro69759ea2011-07-21 18:13:35 -0700524}
525
Shih-wei Liao8c2f6412011-10-03 22:58:14 -0700526/* Terminology:
527 * 1. Footprint: Capacity we allocate from system.
528 * 2. Active space: a.k.a. alloc_space_.
529 * 3. Soft footprint: external allocation + spaces footprint + active space footprint
530 * 4. Overhead: soft footprint excluding active.
531 *
Shih-wei Liao7f1caab2011-10-06 12:11:04 -0700532 * Layout: (The spaces below might not be contiguous, but are lumped together to depict size.)
533 * |----------------------spaces footprint--------- --------------|----active space footprint----|
Shih-wei Liao8c2f6412011-10-03 22:58:14 -0700534 * |--active space allocated--|
535 * |--------------------soft footprint (include active)--------------------------------------|
536 * |----------------soft footprint excluding active---------------|
537 * |------------soft limit-------...|
538 * |------------------------------------ideal footprint-----------------------------------------...|
539 *
540 */
541
542// Sets the maximum number of bytes that the heap is allowed to
543// allocate from the system. Clamps to the appropriate maximum
544// value.
545// Old spaces will count against the ideal size.
546//
547void Heap::SetIdealFootprint(size_t max_allowed_footprint)
548{
549 if (max_allowed_footprint > Heap::maximum_size_) {
550 LOG(INFO) << "Clamp target GC heap from " << max_allowed_footprint
551 << " to " << Heap::maximum_size_;
552 max_allowed_footprint = Heap::maximum_size_;
553 }
554
Shih-wei Liao7f1caab2011-10-06 12:11:04 -0700555 alloc_space_->SetMaxAllowedFootprint(max_allowed_footprint);
Shih-wei Liao8c2f6412011-10-03 22:58:14 -0700556}
557
Shih-wei Liao7f1caab2011-10-06 12:11:04 -0700558// kHeapIdealFree is the ideal maximum free size, when we grow the heap for
559// utlization.
560static const size_t kHeapIdealFree = 2 * MB;
561// kHeapMinFree guarantees that you always have at least 512 KB free, when
562// you grow for utilization, regardless of target utilization ratio.
Shih-wei Liao8c2f6412011-10-03 22:58:14 -0700563static const size_t kHeapMinFree = kHeapIdealFree / 4;
564
565// Given the current contents of the active space, increase the allowed
Carl Shapiro69759ea2011-07-21 18:13:35 -0700566// heap footprint to match the target utilization ratio. This should
567// only be called immediately after a full garbage collection.
Shih-wei Liao8c2f6412011-10-03 22:58:14 -0700568//
Carl Shapiro69759ea2011-07-21 18:13:35 -0700569void Heap::GrowForUtilization() {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700570 lock_->AssertHeld();
Shih-wei Liao8c2f6412011-10-03 22:58:14 -0700571
572 // We know what our utilization is at this moment.
573 // This doesn't actually resize any memory. It just lets the heap grow more
574 // when necessary.
575 size_t target_size = size_t( num_bytes_allocated_ /
576 Heap::GetTargetHeapUtilization() );
577
578 if (target_size > num_bytes_allocated_ + kHeapIdealFree) {
579 target_size = num_bytes_allocated_ + kHeapIdealFree;
580 } else if (target_size < num_bytes_allocated_ + kHeapMinFree) {
581 target_size = num_bytes_allocated_ + kHeapMinFree;
582 }
583
584 SetIdealFootprint(target_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700585}
586
Elliott Hughes92b3b562011-09-08 16:32:26 -0700587void Heap::Lock() {
Elliott Hughes93e74e82011-09-13 11:07:03 -0700588 // TODO: grab the lock, but put ourselves into Thread::kVmWait if it looks like
Elliott Hughes92b3b562011-09-08 16:32:26 -0700589 // we're going to have to wait on the mutex.
590 lock_->Lock();
591}
592
593void Heap::Unlock() {
594 lock_->Unlock();
595}
596
Elliott Hughesadb460d2011-10-05 17:02:34 -0700597void Heap::SetWellKnownClasses(Class* java_lang_ref_FinalizerReference,
598 Class* java_lang_ref_ReferenceQueue) {
599 java_lang_ref_FinalizerReference_ = java_lang_ref_FinalizerReference;
600 java_lang_ref_ReferenceQueue_ = java_lang_ref_ReferenceQueue;
601 CHECK(java_lang_ref_FinalizerReference_ != NULL);
602 CHECK(java_lang_ref_ReferenceQueue_ != NULL);
603}
604
605void Heap::SetReferenceOffsets(MemberOffset reference_referent_offset,
606 MemberOffset reference_queue_offset,
607 MemberOffset reference_queueNext_offset,
608 MemberOffset reference_pendingNext_offset,
609 MemberOffset finalizer_reference_zombie_offset) {
610 reference_referent_offset_ = reference_referent_offset;
611 reference_queue_offset_ = reference_queue_offset;
612 reference_queueNext_offset_ = reference_queueNext_offset;
613 reference_pendingNext_offset_ = reference_pendingNext_offset;
614 finalizer_reference_zombie_offset_ = finalizer_reference_zombie_offset;
615 CHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
616 CHECK_NE(reference_queue_offset_.Uint32Value(), 0U);
617 CHECK_NE(reference_queueNext_offset_.Uint32Value(), 0U);
618 CHECK_NE(reference_pendingNext_offset_.Uint32Value(), 0U);
619 CHECK_NE(finalizer_reference_zombie_offset_.Uint32Value(), 0U);
620}
621
622Object* Heap::GetReferenceReferent(Object* reference) {
623 DCHECK(reference != NULL);
624 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
625 return reference->GetFieldObject<Object*>(reference_referent_offset_, true);
626}
627
628void Heap::ClearReferenceReferent(Object* reference) {
629 DCHECK(reference != NULL);
630 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
631 reference->SetFieldObject(reference_referent_offset_, NULL, true);
632}
633
634// Returns true if the reference object has not yet been enqueued.
635bool Heap::IsEnqueuable(const Object* ref) {
636 DCHECK(ref != NULL);
637 const Object* queue = ref->GetFieldObject<Object*>(reference_queue_offset_, false);
638 const Object* queue_next = ref->GetFieldObject<Object*>(reference_queueNext_offset_, false);
639 return (queue != NULL) && (queue_next == NULL);
640}
641
642void Heap::EnqueueReference(Object* ref, Object** cleared_reference_list) {
643 DCHECK(ref != NULL);
644 CHECK(ref->GetFieldObject<Object*>(reference_queue_offset_, false) != NULL);
645 CHECK(ref->GetFieldObject<Object*>(reference_queueNext_offset_, false) == NULL);
646 EnqueuePendingReference(ref, cleared_reference_list);
647}
648
649void Heap::EnqueuePendingReference(Object* ref, Object** list) {
650 DCHECK(ref != NULL);
651 DCHECK(list != NULL);
652
653 if (*list == NULL) {
654 ref->SetFieldObject(reference_pendingNext_offset_, ref, false);
655 *list = ref;
656 } else {
657 Object* head = (*list)->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
658 ref->SetFieldObject(reference_pendingNext_offset_, head, false);
659 (*list)->SetFieldObject(reference_pendingNext_offset_, ref, false);
660 }
661}
662
663Object* Heap::DequeuePendingReference(Object** list) {
664 DCHECK(list != NULL);
665 DCHECK(*list != NULL);
666 Object* head = (*list)->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
667 Object* ref;
668 if (*list == head) {
669 ref = *list;
670 *list = NULL;
671 } else {
672 Object* next = head->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
673 (*list)->SetFieldObject(reference_pendingNext_offset_, next, false);
674 ref = head;
675 }
676 ref->SetFieldObject(reference_pendingNext_offset_, NULL, false);
677 return ref;
678}
679
680void Heap::AddFinalizerReference(Object* object) {
681 static Method* FinalizerReference_add =
682 java_lang_ref_FinalizerReference_->FindDirectMethod("add", "(Ljava/lang/Object;)V");
683 DCHECK(FinalizerReference_add != NULL);
684 Object* args[] = { object };
685 FinalizerReference_add->Invoke(Thread::Current(), NULL, reinterpret_cast<byte*>(&args), NULL);
686}
687
688void Heap::EnqueueClearedReferences(Object** cleared) {
689 DCHECK(cleared != NULL);
690 if (*cleared != NULL) {
691 static Method* ReferenceQueue_add =
692 java_lang_ref_ReferenceQueue_->FindDirectMethod("add", "(Ljava/lang/ref/Reference;)V");
693 DCHECK(ReferenceQueue_add != NULL);
694
695 Thread* self = Thread::Current();
696 ScopedThreadStateChange tsc(self, Thread::kRunnable);
697 Object* args[] = { *cleared };
698 ReferenceQueue_add->Invoke(self, NULL, reinterpret_cast<byte*>(&args), NULL);
699 *cleared = NULL;
700 }
701}
702
Carl Shapiro69759ea2011-07-21 18:13:35 -0700703} // namespace art