blob: 9fe77508e3578a7a1cc68e36d064f69772a100ff [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 Hughes767a1472011-10-26 18:49:02 -07008#include "debugger.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 Hughes8d768a92011-09-14 16:35:25 -070014#include "thread_list.h"
Elliott Hughes767a1472011-10-26 18:49:02 -070015#include "timing_logger.h"
16#include "UniquePtr.h"
Carl Shapiro69759ea2011-07-21 18:13:35 -070017
18namespace art {
19
Brian Carlstrom6b4ef022011-10-23 14:59:04 -070020bool Heap::is_verbose_heap_ = false;
21
22bool Heap::is_verbose_gc_ = false;
23
Carl Shapiro58551df2011-07-24 03:09:51 -070024std::vector<Space*> Heap::spaces_;
Carl Shapiro69759ea2011-07-21 18:13:35 -070025
Brian Carlstrom4a289ed2011-08-16 17:17:49 -070026Space* Heap::alloc_space_ = NULL;
Carl Shapiro69759ea2011-07-21 18:13:35 -070027
28size_t Heap::maximum_size_ = 0;
29
Carl Shapiro58551df2011-07-24 03:09:51 -070030size_t Heap::num_bytes_allocated_ = 0;
31
32size_t Heap::num_objects_allocated_ = 0;
33
Carl Shapiro69759ea2011-07-21 18:13:35 -070034bool Heap::is_gc_running_ = false;
35
36HeapBitmap* Heap::mark_bitmap_ = NULL;
37
38HeapBitmap* Heap::live_bitmap_ = NULL;
39
Elliott Hughesadb460d2011-10-05 17:02:34 -070040Class* Heap::java_lang_ref_FinalizerReference_ = NULL;
41Class* Heap::java_lang_ref_ReferenceQueue_ = NULL;
42
Ian Rogers0cfe1fb2011-08-26 03:29:44 -070043MemberOffset Heap::reference_referent_offset_ = MemberOffset(0);
44MemberOffset Heap::reference_queue_offset_ = MemberOffset(0);
45MemberOffset Heap::reference_queueNext_offset_ = MemberOffset(0);
46MemberOffset Heap::reference_pendingNext_offset_ = MemberOffset(0);
47MemberOffset Heap::finalizer_reference_zombie_offset_ = MemberOffset(0);
Brian Carlstrom1f870082011-08-23 16:02:11 -070048
Brian Carlstrom395520e2011-09-25 19:35:00 -070049float Heap::target_utilization_ = 0.5;
50
Elliott Hughes92b3b562011-09-08 16:32:26 -070051Mutex* Heap::lock_ = NULL;
52
Elliott Hughes9d5ccec2011-09-19 13:19:50 -070053bool Heap::verify_objects_ = false;
54
Elliott Hughes92b3b562011-09-08 16:32:26 -070055class ScopedHeapLock {
56 public:
57 ScopedHeapLock() {
58 Heap::Lock();
59 }
60
61 ~ScopedHeapLock() {
62 Heap::Unlock();
63 }
64};
65
Brian Carlstrom6b4ef022011-10-23 14:59:04 -070066void Heap::Init(bool is_verbose_heap, bool is_verbose_gc,
67 size_t initial_size, size_t maximum_size,
Brian Carlstrom58ae9412011-10-04 00:56:06 -070068 const std::vector<std::string>& image_file_names) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -070069 is_verbose_heap_ = is_verbose_heap;
70 is_verbose_gc_ = is_verbose_gc;
71
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -070072 const Runtime* runtime = Runtime::Current();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -070073 if (is_verbose_heap_ || runtime->IsVerboseStartup()) {
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -070074 LOG(INFO) << "Heap::Init entering";
75 }
76
Brian Carlstrom58ae9412011-10-04 00:56:06 -070077 // bounds of all spaces for allocating live and mark bitmaps
78 // there will be at least one space (the alloc space),
79 // so set to base to max and limit to min to start
80 byte* base = reinterpret_cast<byte*>(std::numeric_limits<uintptr_t>::max());
81 byte* limit = reinterpret_cast<byte*>(std::numeric_limits<uintptr_t>::min());
Brian Carlstrom4a289ed2011-08-16 17:17:49 -070082
Brian Carlstrom58ae9412011-10-04 00:56:06 -070083 byte* requested_base = NULL;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070084 std::vector<Space*> image_spaces;
85 for (size_t i = 0; i < image_file_names.size(); i++) {
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -070086 Space* space = Space::CreateFromImage(image_file_names[i]);
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070087 if (space == NULL) {
Elliott Hughesbe759c62011-09-08 19:38:21 -070088 LOG(FATAL) << "Failed to create space from " << image_file_names[i];
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070089 }
90 image_spaces.push_back(space);
91 spaces_.push_back(space);
Brian Carlstrome24fa612011-09-29 00:53:55 -070092 byte* oat_limit_addr = space->GetImageHeader().GetOatLimitAddr();
Brian Carlstrom58ae9412011-10-04 00:56:06 -070093 if (oat_limit_addr > requested_base) {
94 requested_base = reinterpret_cast<byte*>(RoundUp(reinterpret_cast<uintptr_t>(oat_limit_addr),
95 kPageSize));
96 }
97 base = std::min(base, space->GetBase());
98 limit = std::max(limit, space->GetLimit());
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070099 }
100
Elliott Hughes307f75d2011-10-12 18:04:40 -0700101 alloc_space_ = Space::Create("alloc space", initial_size, maximum_size, requested_base);
102 if (alloc_space_ == NULL) {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700103 LOG(FATAL) << "Failed to create alloc space";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700104 }
Elliott Hughes307f75d2011-10-12 18:04:40 -0700105 base = std::min(base, alloc_space_->GetBase());
106 limit = std::max(limit, alloc_space_->GetLimit());
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700107 DCHECK_LT(base, limit);
108 size_t num_bytes = limit - base;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700109
110 // Allocate the initial live bitmap.
Elliott Hughes90a33692011-08-30 13:27:07 -0700111 UniquePtr<HeapBitmap> live_bitmap(HeapBitmap::Create(base, num_bytes));
112 if (live_bitmap.get() == NULL) {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700113 LOG(FATAL) << "Failed to create live bitmap";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700114 }
115
116 // Allocate the initial mark bitmap.
Elliott Hughes90a33692011-08-30 13:27:07 -0700117 UniquePtr<HeapBitmap> mark_bitmap(HeapBitmap::Create(base, num_bytes));
118 if (mark_bitmap.get() == NULL) {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700119 LOG(FATAL) << "Failed to create mark bitmap";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700120 }
121
Elliott Hughes307f75d2011-10-12 18:04:40 -0700122 spaces_.push_back(alloc_space_);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700123 maximum_size_ = maximum_size;
124 live_bitmap_ = live_bitmap.release();
125 mark_bitmap_ = mark_bitmap.release();
126
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700127 num_bytes_allocated_ = 0;
128 num_objects_allocated_ = 0;
129
Carl Shapiro69759ea2011-07-21 18:13:35 -0700130 // TODO: allocate the card table
131
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700132 // Make image objects live (after live_bitmap_ is set)
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700133 for (size_t i = 0; i < image_spaces.size(); i++) {
134 RecordImageAllocations(image_spaces[i]);
135 }
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700136
Elliott Hughes85d15452011-09-16 17:33:01 -0700137 Heap::EnableObjectValidation();
138
Elliott Hughes92b3b562011-09-08 16:32:26 -0700139 // It's still to early to take a lock because there are no threads yet,
140 // but we can create the heap lock now. We don't create it earlier to
141 // make it clear that you can't use locks during heap initialization.
Elliott Hughes8daa0922011-09-11 13:46:25 -0700142 lock_ = new Mutex("Heap lock");
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700143
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700144 if (is_verbose_heap_ || runtime->IsVerboseStartup()) {
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700145 LOG(INFO) << "Heap::Init exiting";
146 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700147}
148
149void Heap::Destroy() {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700150 ScopedHeapLock lock;
Carl Shapiro58551df2011-07-24 03:09:51 -0700151 STLDeleteElements(&spaces_);
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700152 if (mark_bitmap_ != NULL) {
153 delete mark_bitmap_;
154 mark_bitmap_ = NULL;
155 }
156 if (live_bitmap_ != NULL) {
157 delete live_bitmap_;
158 }
159 live_bitmap_ = NULL;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700160}
161
Elliott Hughes418dfe72011-10-06 18:56:27 -0700162Object* Heap::AllocObject(Class* klass, size_t byte_count) {
163 {
164 ScopedHeapLock lock;
165 DCHECK(klass == NULL || klass->GetDescriptor() == NULL ||
166 (klass->IsClassClass() && byte_count >= sizeof(Class)) ||
167 (klass->IsVariableSize() || klass->GetObjectSize() == byte_count));
168 DCHECK_GE(byte_count, sizeof(Object));
169 Object* obj = AllocateLocked(byte_count);
170 if (obj != NULL) {
171 obj->SetClass(klass);
172 return obj;
173 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700174 }
Elliott Hughes418dfe72011-10-06 18:56:27 -0700175
176 Thread::Current()->ThrowOutOfMemoryError(klass, byte_count);
177 return NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700178}
179
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700180bool Heap::IsHeapAddress(const Object* obj) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700181 // Note: we deliberately don't take the lock here, and mustn't test anything that would
182 // require taking the lock.
Elliott Hughes06b37d92011-10-16 11:51:29 -0700183 if (!IsAligned<kObjectAlignment>(obj)) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700184 return false;
185 }
186 // TODO
187 return true;
188}
189
Elliott Hughes3e465b12011-09-02 18:26:12 -0700190#if VERIFY_OBJECT_ENABLED
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700191void Heap::VerifyObject(const Object* obj) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700192 if (!verify_objects_) {
193 return;
194 }
Elliott Hughes92b3b562011-09-08 16:32:26 -0700195 ScopedHeapLock lock;
196 Heap::VerifyObjectLocked(obj);
197}
198#endif
199
200void Heap::VerifyObjectLocked(const Object* obj) {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700201 lock_->AssertHeld();
Elliott Hughes85d15452011-09-16 17:33:01 -0700202 if (obj != NULL) {
Elliott Hughes06b37d92011-10-16 11:51:29 -0700203 if (!IsAligned<kObjectAlignment>(obj)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700204 LOG(FATAL) << "Object isn't aligned: " << obj;
205 } else if (!live_bitmap_->Test(obj)) {
206 // TODO: we don't hold a lock here as it is assumed the live bit map
207 // isn't changing if the mutator is running.
208 LOG(FATAL) << "Object is dead: " << obj;
209 }
210 // Ignore early dawn of the universe verifications
Brian Carlstromdbc05252011-09-09 01:59:59 -0700211 if (num_objects_allocated_ > 10) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700212 const byte* raw_addr = reinterpret_cast<const byte*>(obj) +
213 Object::ClassOffset().Int32Value();
214 const Class* c = *reinterpret_cast<Class* const *>(raw_addr);
215 if (c == NULL) {
216 LOG(FATAL) << "Null class" << " in object: " << obj;
Elliott Hughes06b37d92011-10-16 11:51:29 -0700217 } else if (!IsAligned<kObjectAlignment>(c)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700218 LOG(FATAL) << "Class isn't aligned: " << c << " in object: " << obj;
219 } else if (!live_bitmap_->Test(c)) {
220 LOG(FATAL) << "Class of object is dead: " << c << " in object: " << obj;
221 }
222 // Check obj.getClass().getClass() == obj.getClass().getClass().getClass()
Ian Rogersad25ac52011-10-04 19:13:33 -0700223 // Note: we don't use the accessors here as they have internal sanity checks
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700224 // that we don't want to run
225 raw_addr = reinterpret_cast<const byte*>(c) +
226 Object::ClassOffset().Int32Value();
227 const Class* c_c = *reinterpret_cast<Class* const *>(raw_addr);
228 raw_addr = reinterpret_cast<const byte*>(c_c) +
229 Object::ClassOffset().Int32Value();
230 const Class* c_c_c = *reinterpret_cast<Class* const *>(raw_addr);
231 CHECK_EQ(c_c, c_c_c);
232 }
233 }
234}
235
Brian Carlstrom78128a62011-09-15 17:21:19 -0700236void Heap::VerificationCallback(Object* obj, void* arg) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700237 DCHECK(obj != NULL);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700238 Heap::VerifyObjectLocked(obj);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700239}
240
241void Heap::VerifyHeap() {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700242 ScopedHeapLock lock;
243 live_bitmap_->Walk(Heap::VerificationCallback, NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700244}
245
Elliott Hughes92b3b562011-09-08 16:32:26 -0700246void Heap::RecordAllocationLocked(Space* space, const Object* obj) {
247#ifndef NDEBUG
248 if (Runtime::Current()->IsStarted()) {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700249 lock_->AssertHeld();
Elliott Hughes92b3b562011-09-08 16:32:26 -0700250 }
251#endif
Carl Shapiro58551df2011-07-24 03:09:51 -0700252 size_t size = space->AllocationSize(obj);
253 DCHECK_NE(size, 0u);
254 num_bytes_allocated_ += size;
255 num_objects_allocated_ += 1;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700256
257 if (Runtime::Current()->HasStatsEnabled()) {
258 RuntimeStats* global_stats = Runtime::Current()->GetStats();
259 RuntimeStats* thread_stats = Thread::Current()->GetStats();
260 ++global_stats->allocated_objects;
261 ++thread_stats->allocated_objects;
262 global_stats->allocated_bytes += size;
263 thread_stats->allocated_bytes += size;
264 }
265
Carl Shapiro58551df2011-07-24 03:09:51 -0700266 live_bitmap_->Set(obj);
267}
268
Elliott Hughes307f75d2011-10-12 18:04:40 -0700269void Heap::RecordFreeLocked(size_t freed_objects, size_t freed_bytes) {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700270 lock_->AssertHeld();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700271
272 if (freed_objects < num_objects_allocated_) {
273 num_objects_allocated_ -= freed_objects;
274 } else {
275 num_objects_allocated_ = 0;
276 }
277 if (freed_bytes < num_bytes_allocated_) {
278 num_bytes_allocated_ -= freed_bytes;
Carl Shapiro58551df2011-07-24 03:09:51 -0700279 } else {
280 num_bytes_allocated_ = 0;
281 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700282
283 if (Runtime::Current()->HasStatsEnabled()) {
284 RuntimeStats* global_stats = Runtime::Current()->GetStats();
285 RuntimeStats* thread_stats = Thread::Current()->GetStats();
286 ++global_stats->freed_objects;
287 ++thread_stats->freed_objects;
Elliott Hughes307f75d2011-10-12 18:04:40 -0700288 global_stats->freed_bytes += freed_bytes;
289 thread_stats->freed_bytes += freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700290 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700291}
292
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700293void Heap::RecordImageAllocations(Space* space) {
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700294 const Runtime* runtime = Runtime::Current();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700295 if (is_verbose_heap_ || runtime->IsVerboseStartup()) {
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700296 LOG(INFO) << "Heap::RecordImageAllocations entering";
297 }
Elliott Hughes92b3b562011-09-08 16:32:26 -0700298 DCHECK(!Runtime::Current()->IsStarted());
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700299 CHECK(space != NULL);
300 CHECK(live_bitmap_ != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700301 byte* current = space->GetBase() + RoundUp(sizeof(ImageHeader), kObjectAlignment);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700302 while (current < space->GetLimit()) {
Elliott Hughes06b37d92011-10-16 11:51:29 -0700303 DCHECK_ALIGNED(current, kObjectAlignment);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700304 const Object* obj = reinterpret_cast<const Object*>(current);
305 live_bitmap_->Set(obj);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700306 current += RoundUp(obj->SizeOf(), kObjectAlignment);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700307 }
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700308 if (is_verbose_heap_ || runtime->IsVerboseStartup()) {
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700309 LOG(INFO) << "Heap::RecordImageAllocations exiting";
310 }
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700311}
312
Elliott Hughes92b3b562011-09-08 16:32:26 -0700313Object* Heap::AllocateLocked(size_t size) {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700314 lock_->AssertHeld();
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700315 DCHECK(alloc_space_ != NULL);
316 Space* space = alloc_space_;
Elliott Hughes92b3b562011-09-08 16:32:26 -0700317 Object* obj = AllocateLocked(space, size);
Carl Shapiro58551df2011-07-24 03:09:51 -0700318 if (obj != NULL) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700319 RecordAllocationLocked(space, obj);
Carl Shapiro58551df2011-07-24 03:09:51 -0700320 }
321 return obj;
322}
323
Elliott Hughes92b3b562011-09-08 16:32:26 -0700324Object* Heap::AllocateLocked(Space* space, size_t size) {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700325 lock_->AssertHeld();
Elliott Hughes92b3b562011-09-08 16:32:26 -0700326
Brian Carlstromb82b6872011-10-26 17:18:07 -0700327 // Since allocation can cause a GC which will need to SuspendAll,
328 // make sure all allocators are in the kRunnable state.
329 DCHECK_EQ(Thread::Current()->GetState(), Thread::kRunnable);
330
Carl Shapiro69759ea2011-07-21 18:13:35 -0700331 // Fail impossible allocations. TODO: collect soft references.
332 if (size > maximum_size_) {
333 return NULL;
334 }
335
Carl Shapiro58551df2011-07-24 03:09:51 -0700336 Object* ptr = space->AllocWithoutGrowth(size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700337 if (ptr != NULL) {
338 return ptr;
339 }
340
341 // The allocation failed. If the GC is running, block until it
342 // completes and retry.
343 if (is_gc_running_) {
344 // The GC is concurrently tracing the heap. Release the heap
345 // lock, wait for the GC to complete, and retrying allocating.
346 WaitForConcurrentGcToComplete();
Carl Shapiro58551df2011-07-24 03:09:51 -0700347 ptr = space->AllocWithoutGrowth(size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700348 if (ptr != NULL) {
349 return ptr;
350 }
351 }
352
353 // Another failure. Our thread was starved or there may be too many
354 // live objects. Try a foreground GC. This will have no effect if
355 // the concurrent GC is already running.
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700356 if (Runtime::Current()->HasStatsEnabled()) {
357 ++Runtime::Current()->GetStats()->gc_for_alloc_count;
358 ++Thread::Current()->GetStats()->gc_for_alloc_count;
359 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700360 CollectGarbageInternal();
361 ptr = space->AllocWithoutGrowth(size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700362 if (ptr != NULL) {
363 return ptr;
364 }
365
366 // Even that didn't work; this is an exceptional state.
367 // Try harder, growing the heap if necessary.
Carl Shapiro58551df2011-07-24 03:09:51 -0700368 ptr = space->AllocWithGrowth(size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700369 if (ptr != NULL) {
370 //size_t new_footprint = dvmHeapSourceGetIdealFootprint();
Shih-wei Liao7f1caab2011-10-06 12:11:04 -0700371 size_t new_footprint = space->GetMaxAllowedFootprint();
Elliott Hughes418dfe72011-10-06 18:56:27 -0700372 // OLD-TODO: may want to grow a little bit more so that the amount of
Carl Shapiro58551df2011-07-24 03:09:51 -0700373 // free space is equal to the old free space + the
374 // utilization slop for the new allocation.
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700375 if (is_verbose_gc_) {
376 LOG(INFO) << "Grow heap (frag case) to " << new_footprint / MB
Brian Carlstromf28bc5b2011-10-26 01:15:03 -0700377 << " for " << size << "-byte allocation";
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700378 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700379 return ptr;
380 }
381
382 // Most allocations should have succeeded by now, so the heap is
383 // really full, really fragmented, or the requested size is really
384 // big. Do another GC, collecting SoftReferences this time. The VM
385 // spec requires that all SoftReferences have been collected and
386 // cleared before throwing an OOME.
387
Elliott Hughes418dfe72011-10-06 18:56:27 -0700388 // OLD-TODO: wait for the finalizers from the previous GC to finish
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700389 if (is_verbose_gc_) {
390 LOG(INFO) << "Forcing collection of SoftReferences for "
391 << size << "-byte allocation";
392 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700393 CollectGarbageInternal();
394 ptr = space->AllocWithGrowth(size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700395 if (ptr != NULL) {
396 return ptr;
397 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700398
Carl Shapiro69759ea2011-07-21 18:13:35 -0700399 LOG(ERROR) << "Out of memory on a " << size << " byte allocation";
400
Carl Shapiro58551df2011-07-24 03:09:51 -0700401 // TODO: tell the HeapSource to dump its state
402 // TODO: dump stack traces for all threads
Carl Shapiro69759ea2011-07-21 18:13:35 -0700403
Carl Shapiro69759ea2011-07-21 18:13:35 -0700404 return NULL;
405}
406
Elliott Hughesbf86d042011-08-31 17:53:14 -0700407int64_t Heap::GetMaxMemory() {
Elliott Hughes7162ad92011-10-27 14:08:42 -0700408 return maximum_size_;
Elliott Hughesbf86d042011-08-31 17:53:14 -0700409}
410
411int64_t Heap::GetTotalMemory() {
Elliott Hughes7162ad92011-10-27 14:08:42 -0700412 return alloc_space_->Size();
Elliott Hughesbf86d042011-08-31 17:53:14 -0700413}
414
415int64_t Heap::GetFreeMemory() {
Elliott Hughes7162ad92011-10-27 14:08:42 -0700416 return alloc_space_->Size() - num_bytes_allocated_;
Elliott Hughesbf86d042011-08-31 17:53:14 -0700417}
418
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700419class InstanceCounter {
420 public:
421 InstanceCounter(Class* c, bool count_assignable)
422 : class_(c), count_assignable_(count_assignable), count_(0) {
423 }
424
425 size_t GetCount() {
426 return count_;
427 }
428
429 static void Callback(Object* o, void* arg) {
430 reinterpret_cast<InstanceCounter*>(arg)->VisitInstance(o);
431 }
432
433 private:
434 void VisitInstance(Object* o) {
435 Class* instance_class = o->GetClass();
436 if (count_assignable_) {
437 if (instance_class == class_) {
438 ++count_;
439 }
440 } else {
441 if (instance_class != NULL && class_->IsAssignableFrom(instance_class)) {
442 ++count_;
443 }
444 }
445 }
446
447 Class* class_;
448 bool count_assignable_;
449 size_t count_;
450};
451
452int64_t Heap::CountInstances(Class* c, bool count_assignable) {
453 ScopedHeapLock lock;
454 InstanceCounter counter(c, count_assignable);
455 live_bitmap_->Walk(InstanceCounter::Callback, &counter);
456 return counter.GetCount();
457}
458
Carl Shapiro69759ea2011-07-21 18:13:35 -0700459void Heap::CollectGarbage() {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700460 ScopedHeapLock lock;
Carl Shapiro58551df2011-07-24 03:09:51 -0700461 CollectGarbageInternal();
Carl Shapiro69759ea2011-07-21 18:13:35 -0700462}
463
464void Heap::CollectGarbageInternal() {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700465 lock_->AssertHeld();
Carl Shapiro58551df2011-07-24 03:09:51 -0700466
Elliott Hughes8d768a92011-09-14 16:35:25 -0700467 ThreadList* thread_list = Runtime::Current()->GetThreadList();
468 thread_list->SuspendAll();
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700469
470 size_t initial_size = num_bytes_allocated_;
Elliott Hughes307f75d2011-10-12 18:04:40 -0700471 TimingLogger timings("CollectGarbageInternal");
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700472 uint64_t t0 = NanoTime();
Elliott Hughesadb460d2011-10-05 17:02:34 -0700473 Object* cleared_references = NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700474 {
475 MarkSweep mark_sweep;
Elliott Hughes307f75d2011-10-12 18:04:40 -0700476 timings.AddSplit("ctor");
Carl Shapiro58551df2011-07-24 03:09:51 -0700477
478 mark_sweep.Init();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700479 timings.AddSplit("Init");
Carl Shapiro58551df2011-07-24 03:09:51 -0700480
481 mark_sweep.MarkRoots();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700482 timings.AddSplit("MarkRoots");
Carl Shapiro58551df2011-07-24 03:09:51 -0700483
484 // Push marked roots onto the mark stack
485
486 // TODO: if concurrent
487 // unlock heap
Elliott Hughes8d768a92011-09-14 16:35:25 -0700488 // thread_list->ResumeAll();
Carl Shapiro58551df2011-07-24 03:09:51 -0700489
490 mark_sweep.RecursiveMark();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700491 timings.AddSplit("RecursiveMark");
Carl Shapiro58551df2011-07-24 03:09:51 -0700492
493 // TODO: if concurrent
494 // lock heap
Elliott Hughes8d768a92011-09-14 16:35:25 -0700495 // thread_list->SuspendAll();
Carl Shapiro58551df2011-07-24 03:09:51 -0700496 // re-mark root set
497 // scan dirty objects
498
499 mark_sweep.ProcessReferences(false);
Elliott Hughes307f75d2011-10-12 18:04:40 -0700500 timings.AddSplit("ProcessReferences");
Carl Shapiro58551df2011-07-24 03:09:51 -0700501
Elliott Hughes2da50362011-10-10 16:57:08 -0700502 // TODO: if concurrent
503 // swap bitmaps
Carl Shapiro58551df2011-07-24 03:09:51 -0700504
505 mark_sweep.Sweep();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700506 timings.AddSplit("Sweep");
Elliott Hughesadb460d2011-10-05 17:02:34 -0700507
508 cleared_references = mark_sweep.GetClearedReferences();
Carl Shapiro58551df2011-07-24 03:09:51 -0700509 }
510
511 GrowForUtilization();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700512 timings.AddSplit("GrowForUtilization");
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700513 uint64_t t1 = NanoTime();
Elliott Hughes8d768a92011-09-14 16:35:25 -0700514 thread_list->ResumeAll();
Elliott Hughesadb460d2011-10-05 17:02:34 -0700515
516 EnqueueClearedReferences(&cleared_references);
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700517
518 // TODO: somehow make the specific GC implementation (here MarkSweep) responsible for logging.
519 size_t bytes_freed = initial_size - num_bytes_allocated_;
520 bool is_small = (bytes_freed > 0 && bytes_freed < 1024);
521 size_t kib_freed = (bytes_freed > 0 ? std::max(bytes_freed/1024, 1U) : 0);
522
Elliott Hughes7162ad92011-10-27 14:08:42 -0700523 size_t total = GetTotalMemory();
524 size_t percentFree = 100 - static_cast<size_t>(100.0f * float(num_bytes_allocated_) / total);
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700525
526 uint32_t duration = (t1 - t0)/1000/1000;
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700527 if (is_verbose_gc_) {
528 LOG(INFO) << "GC freed " << (is_small ? "<" : "") << kib_freed << "KiB, "
529 << percentFree << "% free "
Elliott Hughes7162ad92011-10-27 14:08:42 -0700530 << (num_bytes_allocated_/1024) << "KiB/" << (total/1024) << "KiB, "
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700531 << "paused " << duration << "ms";
532 }
Elliott Hughes767a1472011-10-26 18:49:02 -0700533 Dbg::GcDidFinish();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700534 if (is_verbose_heap_) {
535 timings.Dump();
536 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700537}
538
539void Heap::WaitForConcurrentGcToComplete() {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700540 lock_->AssertHeld();
Carl Shapiro69759ea2011-07-21 18:13:35 -0700541}
542
Shih-wei Liao8c2f6412011-10-03 22:58:14 -0700543/* Terminology:
544 * 1. Footprint: Capacity we allocate from system.
545 * 2. Active space: a.k.a. alloc_space_.
546 * 3. Soft footprint: external allocation + spaces footprint + active space footprint
547 * 4. Overhead: soft footprint excluding active.
548 *
Shih-wei Liao7f1caab2011-10-06 12:11:04 -0700549 * Layout: (The spaces below might not be contiguous, but are lumped together to depict size.)
550 * |----------------------spaces footprint--------- --------------|----active space footprint----|
Shih-wei Liao8c2f6412011-10-03 22:58:14 -0700551 * |--active space allocated--|
552 * |--------------------soft footprint (include active)--------------------------------------|
553 * |----------------soft footprint excluding active---------------|
554 * |------------soft limit-------...|
555 * |------------------------------------ideal footprint-----------------------------------------...|
556 *
557 */
558
559// Sets the maximum number of bytes that the heap is allowed to
560// allocate from the system. Clamps to the appropriate maximum
561// value.
562// Old spaces will count against the ideal size.
563//
564void Heap::SetIdealFootprint(size_t max_allowed_footprint)
565{
566 if (max_allowed_footprint > Heap::maximum_size_) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700567 if (is_verbose_gc_) {
568 LOG(INFO) << "Clamp target GC heap from " << max_allowed_footprint
569 << " to " << Heap::maximum_size_;
570 }
Shih-wei Liao8c2f6412011-10-03 22:58:14 -0700571 max_allowed_footprint = Heap::maximum_size_;
572 }
573
Shih-wei Liao7f1caab2011-10-06 12:11:04 -0700574 alloc_space_->SetMaxAllowedFootprint(max_allowed_footprint);
Shih-wei Liao8c2f6412011-10-03 22:58:14 -0700575}
576
Shih-wei Liao7f1caab2011-10-06 12:11:04 -0700577// kHeapIdealFree is the ideal maximum free size, when we grow the heap for
578// utlization.
579static const size_t kHeapIdealFree = 2 * MB;
580// kHeapMinFree guarantees that you always have at least 512 KB free, when
581// you grow for utilization, regardless of target utilization ratio.
Shih-wei Liao8c2f6412011-10-03 22:58:14 -0700582static const size_t kHeapMinFree = kHeapIdealFree / 4;
583
584// Given the current contents of the active space, increase the allowed
Carl Shapiro69759ea2011-07-21 18:13:35 -0700585// heap footprint to match the target utilization ratio. This should
586// only be called immediately after a full garbage collection.
Shih-wei Liao8c2f6412011-10-03 22:58:14 -0700587//
Carl Shapiro69759ea2011-07-21 18:13:35 -0700588void Heap::GrowForUtilization() {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700589 lock_->AssertHeld();
Shih-wei Liao8c2f6412011-10-03 22:58:14 -0700590
591 // We know what our utilization is at this moment.
592 // This doesn't actually resize any memory. It just lets the heap grow more
593 // when necessary.
Elliott Hughes362f9bc2011-10-17 18:56:41 -0700594 size_t target_size(num_bytes_allocated_ / Heap::GetTargetHeapUtilization());
Shih-wei Liao8c2f6412011-10-03 22:58:14 -0700595
596 if (target_size > num_bytes_allocated_ + kHeapIdealFree) {
597 target_size = num_bytes_allocated_ + kHeapIdealFree;
598 } else if (target_size < num_bytes_allocated_ + kHeapMinFree) {
599 target_size = num_bytes_allocated_ + kHeapMinFree;
600 }
601
602 SetIdealFootprint(target_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700603}
604
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -0700605pid_t Heap::GetLockOwner() {
Elliott Hughesaccd83d2011-10-17 14:25:58 -0700606 return lock_->GetOwner();
607}
608
Elliott Hughes92b3b562011-09-08 16:32:26 -0700609void Heap::Lock() {
Brian Carlstromfad71432011-10-16 20:25:10 -0700610 // Grab the lock, but put ourselves into Thread::kVmWait if it looks
611 // like we're going to have to wait on the mutex. This prevents
612 // deadlock if another thread is calling CollectGarbageInternal,
613 // since they will have the heap lock and be waiting for mutators to
614 // suspend.
615 if (!lock_->TryLock()) {
616 ScopedThreadStateChange tsc(Thread::Current(), Thread::kVmWait);
617 lock_->Lock();
618 }
Elliott Hughes92b3b562011-09-08 16:32:26 -0700619}
620
621void Heap::Unlock() {
622 lock_->Unlock();
623}
624
Elliott Hughesadb460d2011-10-05 17:02:34 -0700625void Heap::SetWellKnownClasses(Class* java_lang_ref_FinalizerReference,
626 Class* java_lang_ref_ReferenceQueue) {
627 java_lang_ref_FinalizerReference_ = java_lang_ref_FinalizerReference;
628 java_lang_ref_ReferenceQueue_ = java_lang_ref_ReferenceQueue;
629 CHECK(java_lang_ref_FinalizerReference_ != NULL);
630 CHECK(java_lang_ref_ReferenceQueue_ != NULL);
631}
632
633void Heap::SetReferenceOffsets(MemberOffset reference_referent_offset,
634 MemberOffset reference_queue_offset,
635 MemberOffset reference_queueNext_offset,
636 MemberOffset reference_pendingNext_offset,
637 MemberOffset finalizer_reference_zombie_offset) {
638 reference_referent_offset_ = reference_referent_offset;
639 reference_queue_offset_ = reference_queue_offset;
640 reference_queueNext_offset_ = reference_queueNext_offset;
641 reference_pendingNext_offset_ = reference_pendingNext_offset;
642 finalizer_reference_zombie_offset_ = finalizer_reference_zombie_offset;
643 CHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
644 CHECK_NE(reference_queue_offset_.Uint32Value(), 0U);
645 CHECK_NE(reference_queueNext_offset_.Uint32Value(), 0U);
646 CHECK_NE(reference_pendingNext_offset_.Uint32Value(), 0U);
647 CHECK_NE(finalizer_reference_zombie_offset_.Uint32Value(), 0U);
648}
649
650Object* Heap::GetReferenceReferent(Object* reference) {
651 DCHECK(reference != NULL);
652 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
653 return reference->GetFieldObject<Object*>(reference_referent_offset_, true);
654}
655
656void Heap::ClearReferenceReferent(Object* reference) {
657 DCHECK(reference != NULL);
658 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
659 reference->SetFieldObject(reference_referent_offset_, NULL, true);
660}
661
662// Returns true if the reference object has not yet been enqueued.
663bool Heap::IsEnqueuable(const Object* ref) {
664 DCHECK(ref != NULL);
665 const Object* queue = ref->GetFieldObject<Object*>(reference_queue_offset_, false);
666 const Object* queue_next = ref->GetFieldObject<Object*>(reference_queueNext_offset_, false);
667 return (queue != NULL) && (queue_next == NULL);
668}
669
670void Heap::EnqueueReference(Object* ref, Object** cleared_reference_list) {
671 DCHECK(ref != NULL);
672 CHECK(ref->GetFieldObject<Object*>(reference_queue_offset_, false) != NULL);
673 CHECK(ref->GetFieldObject<Object*>(reference_queueNext_offset_, false) == NULL);
674 EnqueuePendingReference(ref, cleared_reference_list);
675}
676
677void Heap::EnqueuePendingReference(Object* ref, Object** list) {
678 DCHECK(ref != NULL);
679 DCHECK(list != NULL);
680
681 if (*list == NULL) {
682 ref->SetFieldObject(reference_pendingNext_offset_, ref, false);
683 *list = ref;
684 } else {
685 Object* head = (*list)->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
686 ref->SetFieldObject(reference_pendingNext_offset_, head, false);
687 (*list)->SetFieldObject(reference_pendingNext_offset_, ref, false);
688 }
689}
690
691Object* Heap::DequeuePendingReference(Object** list) {
692 DCHECK(list != NULL);
693 DCHECK(*list != NULL);
694 Object* head = (*list)->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
695 Object* ref;
696 if (*list == head) {
697 ref = *list;
698 *list = NULL;
699 } else {
700 Object* next = head->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
701 (*list)->SetFieldObject(reference_pendingNext_offset_, next, false);
702 ref = head;
703 }
704 ref->SetFieldObject(reference_pendingNext_offset_, NULL, false);
705 return ref;
706}
707
708void Heap::AddFinalizerReference(Object* object) {
709 static Method* FinalizerReference_add =
710 java_lang_ref_FinalizerReference_->FindDirectMethod("add", "(Ljava/lang/Object;)V");
711 DCHECK(FinalizerReference_add != NULL);
712 Object* args[] = { object };
713 FinalizerReference_add->Invoke(Thread::Current(), NULL, reinterpret_cast<byte*>(&args), NULL);
714}
715
716void Heap::EnqueueClearedReferences(Object** cleared) {
717 DCHECK(cleared != NULL);
718 if (*cleared != NULL) {
719 static Method* ReferenceQueue_add =
720 java_lang_ref_ReferenceQueue_->FindDirectMethod("add", "(Ljava/lang/ref/Reference;)V");
721 DCHECK(ReferenceQueue_add != NULL);
722
723 Thread* self = Thread::Current();
724 ScopedThreadStateChange tsc(self, Thread::kRunnable);
725 Object* args[] = { *cleared };
726 ReferenceQueue_add->Invoke(self, NULL, reinterpret_cast<byte*>(&args), NULL);
727 *cleared = NULL;
728 }
729}
730
Carl Shapiro69759ea2011-07-21 18:13:35 -0700731} // namespace art