blob: 888c75d4f2439d7f32985586d0a1788b1ec2b3b4 [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 "heap.h"
Carl Shapiro58551df2011-07-24 03:09:51 -070018
Brian Carlstrom5643b782012-02-05 12:32:53 -080019#include <sys/types.h>
20#include <sys/wait.h>
21
Brian Carlstrom58ae9412011-10-04 00:56:06 -070022#include <limits>
Carl Shapiro58551df2011-07-24 03:09:51 -070023#include <vector>
24
Ian Rogers5d76c432011-10-31 21:42:49 -070025#include "card_table.h"
Elliott Hughes767a1472011-10-26 18:49:02 -070026#include "debugger.h"
Brian Carlstrom9cff8e12011-08-18 16:47:29 -070027#include "image.h"
Carl Shapiro58551df2011-07-24 03:09:51 -070028#include "mark_sweep.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070029#include "object.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080030#include "object_utils.h"
Brian Carlstrom5643b782012-02-05 12:32:53 -080031#include "os.h"
Elliott Hughesb3bd5f02012-03-08 21:05:27 -080032#include "scoped_heap_lock.h"
Mathieu Chartier7664f5c2012-06-08 18:15:32 -070033#include "ScopedLocalRef.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070034#include "space.h"
Carl Shapiro58551df2011-07-24 03:09:51 -070035#include "stl_util.h"
Elliott Hughes8d768a92011-09-14 16:35:25 -070036#include "thread_list.h"
Elliott Hughes767a1472011-10-26 18:49:02 -070037#include "timing_logger.h"
38#include "UniquePtr.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070039#include "well_known_classes.h"
Carl Shapiro69759ea2011-07-21 18:13:35 -070040
41namespace art {
42
Ian Rogers30fab402012-01-23 15:43:46 -080043static void UpdateFirstAndLastSpace(Space** first_space, Space** last_space, Space* space) {
44 if (*first_space == NULL) {
45 *first_space = space;
46 *last_space = space;
47 } else {
48 if ((*first_space)->Begin() > space->Begin()) {
49 *first_space = space;
50 } else if (space->Begin() > (*last_space)->Begin()) {
51 *last_space = space;
52 }
53 }
54}
55
Elliott Hughesae80b492012-04-24 10:43:17 -070056static bool GenerateImage(const std::string& image_file_name) {
Brian Carlstroma004aa92012-02-08 18:05:09 -080057 const std::string boot_class_path_string(Runtime::Current()->GetBootClassPathString());
Brian Carlstrom5643b782012-02-05 12:32:53 -080058 std::vector<std::string> boot_class_path;
59 Split(boot_class_path_string, ':', boot_class_path);
Brian Carlstromb2793372012-03-17 18:27:16 -070060 if (boot_class_path.empty()) {
61 LOG(FATAL) << "Failed to generate image because no boot class path specified";
62 }
Brian Carlstrom5643b782012-02-05 12:32:53 -080063
64 std::vector<char*> arg_vector;
65
66 std::string dex2oat_string(GetAndroidRoot());
Elliott Hughes67d92002012-03-26 15:08:51 -070067 dex2oat_string += (kIsDebugBuild ? "/bin/dex2oatd" : "/bin/dex2oat");
Brian Carlstrom5643b782012-02-05 12:32:53 -080068 const char* dex2oat = dex2oat_string.c_str();
69 arg_vector.push_back(strdup(dex2oat));
70
71 std::string image_option_string("--image=");
72 image_option_string += image_file_name;
73 const char* image_option = image_option_string.c_str();
74 arg_vector.push_back(strdup(image_option));
75
76 arg_vector.push_back(strdup("--runtime-arg"));
77 arg_vector.push_back(strdup("-Xms64m"));
78
79 arg_vector.push_back(strdup("--runtime-arg"));
80 arg_vector.push_back(strdup("-Xmx64m"));
81
82 for (size_t i = 0; i < boot_class_path.size(); i++) {
83 std::string dex_file_option_string("--dex-file=");
84 dex_file_option_string += boot_class_path[i];
85 const char* dex_file_option = dex_file_option_string.c_str();
86 arg_vector.push_back(strdup(dex_file_option));
87 }
88
89 std::string oat_file_option_string("--oat-file=");
90 oat_file_option_string += image_file_name;
91 oat_file_option_string.erase(oat_file_option_string.size() - 3);
92 oat_file_option_string += "oat";
93 const char* oat_file_option = oat_file_option_string.c_str();
94 arg_vector.push_back(strdup(oat_file_option));
95
96 arg_vector.push_back(strdup("--base=0x60000000"));
97
Elliott Hughes48436bb2012-02-07 15:23:28 -080098 std::string command_line(Join(arg_vector, ' '));
Brian Carlstrom5643b782012-02-05 12:32:53 -080099 LOG(INFO) << command_line;
100
Elliott Hughes48436bb2012-02-07 15:23:28 -0800101 arg_vector.push_back(NULL);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800102 char** argv = &arg_vector[0];
103
104 // fork and exec dex2oat
105 pid_t pid = fork();
106 if (pid == 0) {
107 // no allocation allowed between fork and exec
108
109 // change process groups, so we don't get reaped by ProcessManager
110 setpgid(0, 0);
111
112 execv(dex2oat, argv);
113
114 PLOG(FATAL) << "execv(" << dex2oat << ") failed";
115 return false;
116 } else {
117 STLDeleteElements(&arg_vector);
118
119 // wait for dex2oat to finish
120 int status;
121 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
122 if (got_pid != pid) {
123 PLOG(ERROR) << "waitpid failed: wanted " << pid << ", got " << got_pid;
124 return false;
125 }
126 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
127 LOG(ERROR) << dex2oat << " failed: " << command_line;
128 return false;
129 }
130 }
131 return true;
132}
133
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800134Heap::Heap(size_t initial_size, size_t growth_limit, size_t capacity,
135 const std::string& original_image_file_name)
136 : lock_(NULL),
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700137 image_space_(NULL),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800138 alloc_space_(NULL),
139 mark_bitmap_(NULL),
140 live_bitmap_(NULL),
141 card_table_(NULL),
142 card_marking_disabled_(false),
143 is_gc_running_(false),
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700144 concurrent_start_size_(128 * KB),
145 concurrent_min_free_(256 * KB),
146 try_running_gc_(false),
147 requesting_gc_(false),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800148 num_bytes_allocated_(0),
149 num_objects_allocated_(0),
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700150 last_trim_time_(0),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800151 reference_referent_offset_(0),
152 reference_queue_offset_(0),
153 reference_queueNext_offset_(0),
154 reference_pendingNext_offset_(0),
155 finalizer_reference_zombie_offset_(0),
156 target_utilization_(0.5),
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700157 verify_objects_(false) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800158 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800159 LOG(INFO) << "Heap() entering";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700160 }
161
Ian Rogers30fab402012-01-23 15:43:46 -0800162 // Compute the bounds of all spaces for allocating live and mark bitmaps
163 // there will be at least one space (the alloc space)
164 Space* first_space = NULL;
165 Space* last_space = NULL;
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700166
Ian Rogers30fab402012-01-23 15:43:46 -0800167 // Requested begin for the alloc space, to follow the mapped image and oat files
168 byte* requested_begin = NULL;
Brian Carlstrom5643b782012-02-05 12:32:53 -0800169 std::string image_file_name(original_image_file_name);
170 if (!image_file_name.empty()) {
Brian Carlstrom5643b782012-02-05 12:32:53 -0800171 if (OS::FileExists(image_file_name.c_str())) {
172 // If the /system file exists, it should be up-to-date, don't try to generate
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700173 image_space_ = Space::CreateImageSpace(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800174 } else {
175 // If the /system file didn't exist, we need to use one from the art-cache.
176 // If the cache file exists, try to open, but if it fails, regenerate.
177 // If it does not exist, generate.
178 image_file_name = GetArtCacheFilenameOrDie(image_file_name);
179 if (OS::FileExists(image_file_name.c_str())) {
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700180 image_space_ = Space::CreateImageSpace(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800181 }
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700182 if (image_space_ == NULL) {
Brian Carlstrom5643b782012-02-05 12:32:53 -0800183 if (!GenerateImage(image_file_name)) {
184 LOG(FATAL) << "Failed to generate image: " << image_file_name;
185 }
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700186 image_space_ = Space::CreateImageSpace(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800187 }
188 }
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700189 if (image_space_ == NULL) {
Brian Carlstrom223f20f2012-02-04 23:06:55 -0800190 LOG(FATAL) << "Failed to create space from " << image_file_name;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700191 }
Brian Carlstrom5643b782012-02-05 12:32:53 -0800192
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700193 AddSpace(image_space_);
194 UpdateFirstAndLastSpace(&first_space, &last_space, image_space_);
Ian Rogers30fab402012-01-23 15:43:46 -0800195 // Oat files referenced by image files immediately follow them in memory, ensure alloc space
196 // isn't going to get in the middle
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700197 byte* oat_end_addr = image_space_->GetImageHeader().GetOatEnd();
198 CHECK(oat_end_addr > image_space_->End());
Ian Rogers30fab402012-01-23 15:43:46 -0800199 if (oat_end_addr > requested_begin) {
200 requested_begin = reinterpret_cast<byte*>(RoundUp(reinterpret_cast<uintptr_t>(oat_end_addr),
201 kPageSize));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700202 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700203 }
204
Ian Rogers30fab402012-01-23 15:43:46 -0800205 alloc_space_ = Space::CreateAllocSpace("alloc space", initial_size, growth_limit, capacity,
206 requested_begin);
Elliott Hughes307f75d2011-10-12 18:04:40 -0700207 if (alloc_space_ == NULL) {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700208 LOG(FATAL) << "Failed to create alloc space";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700209 }
Ian Rogers30fab402012-01-23 15:43:46 -0800210 AddSpace(alloc_space_);
211 UpdateFirstAndLastSpace(&first_space, &last_space, alloc_space_);
212 byte* heap_begin = first_space->Begin();
Ian Rogers3bb17a62012-01-27 23:56:44 -0800213 size_t heap_capacity = (last_space->Begin() - first_space->Begin()) + last_space->NonGrowthLimitCapacity();
Carl Shapiro69759ea2011-07-21 18:13:35 -0700214
215 // Allocate the initial live bitmap.
Ian Rogers30fab402012-01-23 15:43:46 -0800216 UniquePtr<HeapBitmap> live_bitmap(HeapBitmap::Create("dalvik-bitmap-1", heap_begin, heap_capacity));
Elliott Hughes90a33692011-08-30 13:27:07 -0700217 if (live_bitmap.get() == NULL) {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700218 LOG(FATAL) << "Failed to create live bitmap";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700219 }
220
Ian Rogers30fab402012-01-23 15:43:46 -0800221 // Mark image objects in the live bitmap
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800222 for (size_t i = 0; i < spaces_.size(); ++i) {
Ian Rogers30fab402012-01-23 15:43:46 -0800223 Space* space = spaces_[i];
224 if (space->IsImageSpace()) {
225 space->AsImageSpace()->RecordImageAllocations(live_bitmap.get());
226 }
227 }
228
Carl Shapiro69759ea2011-07-21 18:13:35 -0700229 // Allocate the initial mark bitmap.
Ian Rogers30fab402012-01-23 15:43:46 -0800230 UniquePtr<HeapBitmap> mark_bitmap(HeapBitmap::Create("dalvik-bitmap-2", heap_begin, heap_capacity));
Elliott Hughes90a33692011-08-30 13:27:07 -0700231 if (mark_bitmap.get() == NULL) {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700232 LOG(FATAL) << "Failed to create mark bitmap";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700233 }
234
Elliott Hughes6c9c06d2011-11-07 16:43:47 -0800235 // Allocate the card table.
Ian Rogers30fab402012-01-23 15:43:46 -0800236 UniquePtr<CardTable> card_table(CardTable::Create(heap_begin, heap_capacity));
Ian Rogers5d76c432011-10-31 21:42:49 -0700237 if (card_table.get() == NULL) {
238 LOG(FATAL) << "Failed to create card table";
239 }
240
Carl Shapiro69759ea2011-07-21 18:13:35 -0700241 live_bitmap_ = live_bitmap.release();
242 mark_bitmap_ = mark_bitmap.release();
Ian Rogers5d76c432011-10-31 21:42:49 -0700243 card_table_ = card_table.release();
Carl Shapiro69759ea2011-07-21 18:13:35 -0700244
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700245 num_bytes_allocated_ = 0;
246 num_objects_allocated_ = 0;
247
Mathieu Chartier5301cd22012-05-31 12:11:36 -0700248 mark_stack_ = MarkStack::Create();
249
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800250 // It's still too early to take a lock because there are no threads yet,
Elliott Hughes92b3b562011-09-08 16:32:26 -0700251 // but we can create the heap lock now. We don't create it earlier to
252 // make it clear that you can't use locks during heap initialization.
Elliott Hughesffb465f2012-03-01 18:46:05 -0800253 lock_ = new Mutex("Heap lock", kHeapLock);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700254 condition_ = new ConditionVariable("Heap condition variable");
255
256 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700257
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800258 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800259 LOG(INFO) << "Heap() exiting";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700260 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700261}
262
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800263void Heap::AddSpace(Space* space) {
264 spaces_.push_back(space);
265}
266
267Heap::~Heap() {
268 VLOG(heap) << "~Heap()";
Elliott Hughesb3e66df2012-01-12 14:49:18 -0800269 // We can't take the heap lock here because there might be a daemon thread suspended with the
270 // heap lock held. We know though that no non-daemon threads are executing, and we know that
271 // all daemon threads are suspended, and we also know that the threads list have been deleted, so
272 // those threads can't resume. We're the only running thread, and we can do whatever we like...
Carl Shapiro58551df2011-07-24 03:09:51 -0700273 STLDeleteElements(&spaces_);
Elliott Hughes4d6850c2012-01-18 15:55:06 -0800274 delete mark_bitmap_;
275 delete live_bitmap_;
276 delete card_table_;
Mathieu Chartier5301cd22012-05-31 12:11:36 -0700277 delete mark_stack_;
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700278 delete condition_;
Elliott Hughes4d6850c2012-01-18 15:55:06 -0800279 delete lock_;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700280}
281
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700282static void MSpaceChunkCallback(void* start, void* end, size_t used_bytes, void* arg) {
283 size_t& max_contiguous_allocation = *reinterpret_cast<size_t*>(arg);
284
285 size_t chunk_size = static_cast<size_t>(reinterpret_cast<uint8_t*>(end) - reinterpret_cast<uint8_t*>(start));
286 size_t chunk_free_bytes = 0;
287 if (used_bytes < chunk_size) {
288 chunk_free_bytes = chunk_size - used_bytes;
289 }
290
291 if (chunk_free_bytes > max_contiguous_allocation) {
292 max_contiguous_allocation = chunk_free_bytes;
293 }
294}
295
296Object* Heap::AllocObject(Class* c, size_t byte_count) {
297 // Used in the detail message if we throw an OOME.
298 int64_t total_bytes_free;
299 size_t max_contiguous_allocation;
300
Elliott Hughes418dfe72011-10-06 18:56:27 -0700301 {
Elliott Hughesffb465f2012-03-01 18:46:05 -0800302 ScopedHeapLock heap_lock;
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700303 DCHECK(c == NULL || (c->IsClassClass() && byte_count >= sizeof(Class)) ||
304 (c->IsVariableSize() || c->GetObjectSize() == byte_count) ||
305 strlen(ClassHelper(c).GetDescriptor()) == 0);
Elliott Hughes418dfe72011-10-06 18:56:27 -0700306 DCHECK_GE(byte_count, sizeof(Object));
307 Object* obj = AllocateLocked(byte_count);
308 if (obj != NULL) {
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700309 obj->SetClass(c);
Elliott Hughes545a0642011-11-08 19:10:03 -0800310 if (Dbg::IsAllocTrackingEnabled()) {
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700311 Dbg::RecordAllocation(c, byte_count);
Elliott Hughes545a0642011-11-08 19:10:03 -0800312 }
Mathieu Chartiera6399032012-06-11 18:49:50 -0700313
314 if (!is_gc_running_ && num_bytes_allocated_ >= concurrent_start_bytes_) {
315 // The SirtRef is necessary since the calls in RequestConcurrentGC
316 // are a safepoint.
317 SirtRef<Object> ref(obj);
318 RequestConcurrentGC();
319 }
320 VerifyObject(obj);
Elliott Hughes418dfe72011-10-06 18:56:27 -0700321 return obj;
322 }
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700323 total_bytes_free = GetFreeMemory();
324 max_contiguous_allocation = 0;
325 GetAllocSpace()->Walk(MSpaceChunkCallback, &max_contiguous_allocation);
Carl Shapiro58551df2011-07-24 03:09:51 -0700326 }
Elliott Hughes418dfe72011-10-06 18:56:27 -0700327
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700328 std::string msg(StringPrintf("Failed to allocate a %zd-byte %s (%lld total bytes free; largest possible contiguous allocation %zd bytes)",
329 byte_count,
330 PrettyDescriptor(c).c_str(),
331 total_bytes_free, max_contiguous_allocation));
332 Thread::Current()->ThrowOutOfMemoryError(msg.c_str());
Elliott Hughes418dfe72011-10-06 18:56:27 -0700333 return NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700334}
335
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700336bool Heap::IsHeapAddress(const Object* obj) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700337 // Note: we deliberately don't take the lock here, and mustn't test anything that would
338 // require taking the lock.
Elliott Hughes88c5c352012-03-15 18:49:48 -0700339 if (obj == NULL) {
340 return true;
341 }
342 if (!IsAligned<kObjectAlignment>(obj)) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700343 return false;
344 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800345 for (size_t i = 0; i < spaces_.size(); ++i) {
Ian Rogers30fab402012-01-23 15:43:46 -0800346 if (spaces_[i]->Contains(obj)) {
347 return true;
348 }
349 }
350 return false;
Elliott Hughesa2501992011-08-26 19:39:54 -0700351}
352
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700353bool Heap::IsLiveObjectLocked(const Object* obj) {
354 lock_->AssertHeld();
355 return IsHeapAddress(obj) && live_bitmap_->Test(obj);
356}
357
Elliott Hughes3e465b12011-09-02 18:26:12 -0700358#if VERIFY_OBJECT_ENABLED
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700359void Heap::VerifyObject(const Object* obj) {
jeffhao25045522012-03-13 19:34:37 -0700360 if (this == NULL || !verify_objects_ || Runtime::Current()->IsShuttingDown() ||
Ian Rogers141d6222012-04-05 12:23:06 -0700361 Thread::Current() == NULL ||
jeffhao25045522012-03-13 19:34:37 -0700362 Runtime::Current()->GetThreadList()->GetLockOwner() == Thread::Current()->GetTid()) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700363 return;
364 }
Elliott Hughesffb465f2012-03-01 18:46:05 -0800365 ScopedHeapLock heap_lock;
Elliott Hughes92b3b562011-09-08 16:32:26 -0700366 Heap::VerifyObjectLocked(obj);
367}
368#endif
369
370void Heap::VerifyObjectLocked(const Object* obj) {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700371 lock_->AssertHeld();
Elliott Hughes85d15452011-09-16 17:33:01 -0700372 if (obj != NULL) {
Elliott Hughes06b37d92011-10-16 11:51:29 -0700373 if (!IsAligned<kObjectAlignment>(obj)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700374 LOG(FATAL) << "Object isn't aligned: " << obj;
375 } else if (!live_bitmap_->Test(obj)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700376 LOG(FATAL) << "Object is dead: " << obj;
377 }
378 // Ignore early dawn of the universe verifications
Brian Carlstromdbc05252011-09-09 01:59:59 -0700379 if (num_objects_allocated_ > 10) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700380 const byte* raw_addr = reinterpret_cast<const byte*>(obj) +
381 Object::ClassOffset().Int32Value();
382 const Class* c = *reinterpret_cast<Class* const *>(raw_addr);
383 if (c == NULL) {
Elliott Hughes5d78d392011-12-13 16:53:05 -0800384 LOG(FATAL) << "Null class in object: " << obj;
Elliott Hughes06b37d92011-10-16 11:51:29 -0700385 } else if (!IsAligned<kObjectAlignment>(c)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700386 LOG(FATAL) << "Class isn't aligned: " << c << " in object: " << obj;
387 } else if (!live_bitmap_->Test(c)) {
388 LOG(FATAL) << "Class of object is dead: " << c << " in object: " << obj;
389 }
390 // Check obj.getClass().getClass() == obj.getClass().getClass().getClass()
Ian Rogersad25ac52011-10-04 19:13:33 -0700391 // Note: we don't use the accessors here as they have internal sanity checks
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700392 // that we don't want to run
Ian Rogers30fab402012-01-23 15:43:46 -0800393 raw_addr = reinterpret_cast<const byte*>(c) + Object::ClassOffset().Int32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700394 const Class* c_c = *reinterpret_cast<Class* const *>(raw_addr);
Ian Rogers30fab402012-01-23 15:43:46 -0800395 raw_addr = reinterpret_cast<const byte*>(c_c) + Object::ClassOffset().Int32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700396 const Class* c_c_c = *reinterpret_cast<Class* const *>(raw_addr);
397 CHECK_EQ(c_c, c_c_c);
398 }
399 }
400}
401
Brian Carlstrom78128a62011-09-15 17:21:19 -0700402void Heap::VerificationCallback(Object* obj, void* arg) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700403 DCHECK(obj != NULL);
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800404 reinterpret_cast<Heap*>(arg)->VerifyObjectLocked(obj);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700405}
406
407void Heap::VerifyHeap() {
Elliott Hughesffb465f2012-03-01 18:46:05 -0800408 ScopedHeapLock heap_lock;
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800409 live_bitmap_->Walk(Heap::VerificationCallback, this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700410}
411
Ian Rogers30fab402012-01-23 15:43:46 -0800412void Heap::RecordAllocationLocked(AllocSpace* space, const Object* obj) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700413#ifndef NDEBUG
414 if (Runtime::Current()->IsStarted()) {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700415 lock_->AssertHeld();
Elliott Hughes92b3b562011-09-08 16:32:26 -0700416 }
417#endif
Carl Shapiro58551df2011-07-24 03:09:51 -0700418 size_t size = space->AllocationSize(obj);
Elliott Hughes5d78d392011-12-13 16:53:05 -0800419 DCHECK_GT(size, 0u);
Carl Shapiro58551df2011-07-24 03:09:51 -0700420 num_bytes_allocated_ += size;
421 num_objects_allocated_ += 1;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700422
423 if (Runtime::Current()->HasStatsEnabled()) {
424 RuntimeStats* global_stats = Runtime::Current()->GetStats();
425 RuntimeStats* thread_stats = Thread::Current()->GetStats();
426 ++global_stats->allocated_objects;
427 ++thread_stats->allocated_objects;
428 global_stats->allocated_bytes += size;
429 thread_stats->allocated_bytes += size;
430 }
431
Carl Shapiro58551df2011-07-24 03:09:51 -0700432 live_bitmap_->Set(obj);
433}
434
Elliott Hughes307f75d2011-10-12 18:04:40 -0700435void Heap::RecordFreeLocked(size_t freed_objects, size_t freed_bytes) {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700436 lock_->AssertHeld();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700437
438 if (freed_objects < num_objects_allocated_) {
439 num_objects_allocated_ -= freed_objects;
440 } else {
441 num_objects_allocated_ = 0;
442 }
443 if (freed_bytes < num_bytes_allocated_) {
444 num_bytes_allocated_ -= freed_bytes;
Carl Shapiro58551df2011-07-24 03:09:51 -0700445 } else {
446 num_bytes_allocated_ = 0;
447 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700448
449 if (Runtime::Current()->HasStatsEnabled()) {
450 RuntimeStats* global_stats = Runtime::Current()->GetStats();
451 RuntimeStats* thread_stats = Thread::Current()->GetStats();
452 ++global_stats->freed_objects;
453 ++thread_stats->freed_objects;
Elliott Hughes307f75d2011-10-12 18:04:40 -0700454 global_stats->freed_bytes += freed_bytes;
455 thread_stats->freed_bytes += freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700456 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700457}
458
Elliott Hughes92b3b562011-09-08 16:32:26 -0700459Object* Heap::AllocateLocked(size_t size) {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700460 lock_->AssertHeld();
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700461 DCHECK(alloc_space_ != NULL);
Ian Rogers30fab402012-01-23 15:43:46 -0800462 AllocSpace* space = alloc_space_;
Elliott Hughes92b3b562011-09-08 16:32:26 -0700463 Object* obj = AllocateLocked(space, size);
Carl Shapiro58551df2011-07-24 03:09:51 -0700464 if (obj != NULL) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700465 RecordAllocationLocked(space, obj);
Carl Shapiro58551df2011-07-24 03:09:51 -0700466 }
467 return obj;
468}
469
Ian Rogers30fab402012-01-23 15:43:46 -0800470Object* Heap::AllocateLocked(AllocSpace* space, size_t alloc_size) {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700471 lock_->AssertHeld();
Elliott Hughes92b3b562011-09-08 16:32:26 -0700472
Brian Carlstromb82b6872011-10-26 17:18:07 -0700473 // Since allocation can cause a GC which will need to SuspendAll,
474 // make sure all allocators are in the kRunnable state.
Elliott Hughes34e06962012-04-09 13:55:55 -0700475 CHECK_EQ(Thread::Current()->GetState(), kRunnable);
Brian Carlstromb82b6872011-10-26 17:18:07 -0700476
Ian Rogers30fab402012-01-23 15:43:46 -0800477 // Fail impossible allocations
478 if (alloc_size > space->Capacity()) {
479 // On failure collect soft references
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700480 CollectGarbageInternal(false, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700481 return NULL;
482 }
483
Ian Rogers30fab402012-01-23 15:43:46 -0800484 Object* ptr = space->AllocWithoutGrowth(alloc_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700485 if (ptr != NULL) {
486 return ptr;
487 }
488
Ian Rogers30fab402012-01-23 15:43:46 -0800489 // The allocation failed. If the GC is running, block until it completes and retry.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700490 if (is_gc_running_) {
Ian Rogers30fab402012-01-23 15:43:46 -0800491 // The GC is concurrently tracing the heap. Release the heap lock, wait for the GC to
492 // complete, and retrying allocating.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700493 WaitForConcurrentGcToComplete();
Ian Rogers30fab402012-01-23 15:43:46 -0800494 ptr = space->AllocWithoutGrowth(alloc_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700495 if (ptr != NULL) {
496 return ptr;
497 }
498 }
499
500 // Another failure. Our thread was starved or there may be too many
501 // live objects. Try a foreground GC. This will have no effect if
502 // the concurrent GC is already running.
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700503 if (Runtime::Current()->HasStatsEnabled()) {
504 ++Runtime::Current()->GetStats()->gc_for_alloc_count;
505 ++Thread::Current()->GetStats()->gc_for_alloc_count;
506 }
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700507 CollectGarbageInternal(false, false);
Ian Rogers30fab402012-01-23 15:43:46 -0800508 ptr = space->AllocWithoutGrowth(alloc_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700509 if (ptr != NULL) {
510 return ptr;
511 }
512
513 // Even that didn't work; this is an exceptional state.
514 // Try harder, growing the heap if necessary.
Ian Rogers30fab402012-01-23 15:43:46 -0800515 ptr = space->AllocWithGrowth(alloc_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700516 if (ptr != NULL) {
Ian Rogers30fab402012-01-23 15:43:46 -0800517 size_t new_footprint = space->GetFootprintLimit();
Elliott Hughes418dfe72011-10-06 18:56:27 -0700518 // OLD-TODO: may want to grow a little bit more so that the amount of
Carl Shapiro58551df2011-07-24 03:09:51 -0700519 // free space is equal to the old free space + the
520 // utilization slop for the new allocation.
Ian Rogers3bb17a62012-01-27 23:56:44 -0800521 VLOG(gc) << "Grow heap (frag case) to " << PrettySize(new_footprint)
Ian Rogers162a31c2012-01-31 16:14:31 -0800522 << " for a " << PrettySize(alloc_size) << " allocation";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700523 return ptr;
524 }
525
Elliott Hughes81ff3182012-03-23 20:35:56 -0700526 // Most allocations should have succeeded by now, so the heap is really full, really fragmented,
527 // or the requested size is really big. Do another GC, collecting SoftReferences this time. The
528 // VM spec requires that all SoftReferences have been collected and cleared before throwing OOME.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700529
Elliott Hughes418dfe72011-10-06 18:56:27 -0700530 // OLD-TODO: wait for the finalizers from the previous GC to finish
Ian Rogers3bb17a62012-01-27 23:56:44 -0800531 VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size) << " allocation";
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700532 CollectGarbageInternal(false, true);
Ian Rogers30fab402012-01-23 15:43:46 -0800533 ptr = space->AllocWithGrowth(alloc_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700534 if (ptr != NULL) {
535 return ptr;
536 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700537
Carl Shapiro69759ea2011-07-21 18:13:35 -0700538 return NULL;
539}
540
Elliott Hughesbf86d042011-08-31 17:53:14 -0700541int64_t Heap::GetMaxMemory() {
Ian Rogers30fab402012-01-23 15:43:46 -0800542 return alloc_space_->Capacity();
Elliott Hughesbf86d042011-08-31 17:53:14 -0700543}
544
545int64_t Heap::GetTotalMemory() {
Ian Rogers30fab402012-01-23 15:43:46 -0800546 return alloc_space_->Capacity();
Elliott Hughesbf86d042011-08-31 17:53:14 -0700547}
548
549int64_t Heap::GetFreeMemory() {
Ian Rogers30fab402012-01-23 15:43:46 -0800550 return alloc_space_->Capacity() - num_bytes_allocated_;
Elliott Hughesbf86d042011-08-31 17:53:14 -0700551}
552
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700553class InstanceCounter {
554 public:
555 InstanceCounter(Class* c, bool count_assignable)
556 : class_(c), count_assignable_(count_assignable), count_(0) {
557 }
558
559 size_t GetCount() {
560 return count_;
561 }
562
563 static void Callback(Object* o, void* arg) {
564 reinterpret_cast<InstanceCounter*>(arg)->VisitInstance(o);
565 }
566
567 private:
568 void VisitInstance(Object* o) {
569 Class* instance_class = o->GetClass();
570 if (count_assignable_) {
571 if (instance_class == class_) {
572 ++count_;
573 }
574 } else {
575 if (instance_class != NULL && class_->IsAssignableFrom(instance_class)) {
576 ++count_;
577 }
578 }
579 }
580
581 Class* class_;
582 bool count_assignable_;
583 size_t count_;
584};
585
586int64_t Heap::CountInstances(Class* c, bool count_assignable) {
Elliott Hughesffb465f2012-03-01 18:46:05 -0800587 ScopedHeapLock heap_lock;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700588 InstanceCounter counter(c, count_assignable);
589 live_bitmap_->Walk(InstanceCounter::Callback, &counter);
590 return counter.GetCount();
591}
592
Ian Rogers30fab402012-01-23 15:43:46 -0800593void Heap::CollectGarbage(bool clear_soft_references) {
Elliott Hughesffb465f2012-03-01 18:46:05 -0800594 ScopedHeapLock heap_lock;
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700595 CollectGarbageInternal(false, clear_soft_references);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700596}
597
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700598void Heap::CollectGarbageInternal(bool concurrent, bool clear_soft_references) {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700599 lock_->AssertHeld();
Carl Shapiro58551df2011-07-24 03:09:51 -0700600
Mathieu Chartiera6399032012-06-11 18:49:50 -0700601 DCHECK(!is_gc_running_);
602 is_gc_running_ = true;
603
Mathieu Chartier662618f2012-06-06 12:01:47 -0700604 TimingLogger timings("CollectGarbageInternal");
Elliott Hughes24edeb52012-06-18 15:29:46 -0700605 uint64_t t0 = NanoTime(), root_end = 0, dirty_begin = 0, dirty_end = 0;
Mathieu Chartier662618f2012-06-06 12:01:47 -0700606
Elliott Hughes8d768a92011-09-14 16:35:25 -0700607 ThreadList* thread_list = Runtime::Current()->GetThreadList();
608 thread_list->SuspendAll();
Mathieu Chartier662618f2012-06-06 12:01:47 -0700609 timings.AddSplit("SuspendAll");
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700610
611 size_t initial_size = num_bytes_allocated_;
Elliott Hughesadb460d2011-10-05 17:02:34 -0700612 Object* cleared_references = NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700613 {
Mathieu Chartier5301cd22012-05-31 12:11:36 -0700614 MarkSweep mark_sweep(mark_stack_);
Elliott Hughes307f75d2011-10-12 18:04:40 -0700615 timings.AddSplit("ctor");
Carl Shapiro58551df2011-07-24 03:09:51 -0700616
617 mark_sweep.Init();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700618 timings.AddSplit("Init");
Carl Shapiro58551df2011-07-24 03:09:51 -0700619
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700620 if (concurrent) {
621 card_table_->ClearNonImageSpaceCards(this);
622 }
623
Carl Shapiro58551df2011-07-24 03:09:51 -0700624 mark_sweep.MarkRoots();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700625 timings.AddSplit("MarkRoots");
Carl Shapiro58551df2011-07-24 03:09:51 -0700626
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700627 if (!concurrent) {
628 mark_sweep.ScanDirtyImageRoots();
629 timings.AddSplit("ScanDirtyImageRoots");
630 }
631
Ian Rogers5d76c432011-10-31 21:42:49 -0700632 // Roots are marked on the bitmap and the mark_stack is empty
633 DCHECK(mark_sweep.IsMarkStackEmpty());
Carl Shapiro58551df2011-07-24 03:09:51 -0700634
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700635 if (concurrent) {
Mathieu Chartiera6399032012-06-11 18:49:50 -0700636 // We need to resume before unlocking or else a thread waiting for the
637 // heap lock would re-suspend since we have not yet called ResumeAll.
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700638 thread_list->ResumeAll();
Mathieu Chartiera6399032012-06-11 18:49:50 -0700639 Unlock();
Elliott Hughes24edeb52012-06-18 15:29:46 -0700640 root_end = NanoTime();
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700641 timings.AddSplit("RootEnd");
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700642 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700643
Ian Rogers5d76c432011-10-31 21:42:49 -0700644 // Recursively mark all bits set in the non-image mark bitmap
Carl Shapiro58551df2011-07-24 03:09:51 -0700645 mark_sweep.RecursiveMark();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700646 timings.AddSplit("RecursiveMark");
Carl Shapiro58551df2011-07-24 03:09:51 -0700647
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700648 if (concurrent) {
Elliott Hughes24edeb52012-06-18 15:29:46 -0700649 dirty_begin = NanoTime();
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700650 Lock();
651 thread_list->SuspendAll();
Mathieu Chartier662618f2012-06-06 12:01:47 -0700652 timings.AddSplit("ReSuspend");
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700653
654 // Re-mark root set.
655 mark_sweep.ReMarkRoots();
656 timings.AddSplit("ReMarkRoots");
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700657
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700658 // Scan dirty objects, this is required even if we are not doing a
659 // concurrent GC since we use the card table to locate image roots.
660 mark_sweep.RecursiveMarkDirtyObjects();
661 timings.AddSplit("RecursiveMarkDirtyObjects");
662 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700663
Ian Rogers30fab402012-01-23 15:43:46 -0800664 mark_sweep.ProcessReferences(clear_soft_references);
Elliott Hughes307f75d2011-10-12 18:04:40 -0700665 timings.AddSplit("ProcessReferences");
Carl Shapiro58551df2011-07-24 03:09:51 -0700666
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700667 // TODO: swap live and marked bitmaps
668 // Note: Need to be careful about image spaces if we do this since not
669 // everything image space will be marked, resulting in things not being
670 // marked as live anymore.
671
672 // Verify that we only reach marked objects from the image space
673 mark_sweep.VerifyImageRoots();
674 timings.AddSplit("VerifyImageRoots");
Carl Shapiro58551df2011-07-24 03:09:51 -0700675
676 mark_sweep.Sweep();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700677 timings.AddSplit("Sweep");
Elliott Hughesadb460d2011-10-05 17:02:34 -0700678
679 cleared_references = mark_sweep.GetClearedReferences();
Carl Shapiro58551df2011-07-24 03:09:51 -0700680 }
681
682 GrowForUtilization();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700683 timings.AddSplit("GrowForUtilization");
Elliott Hughes8d768a92011-09-14 16:35:25 -0700684 thread_list->ResumeAll();
Elliott Hughes24edeb52012-06-18 15:29:46 -0700685 dirty_end = NanoTime();
Elliott Hughesadb460d2011-10-05 17:02:34 -0700686
687 EnqueueClearedReferences(&cleared_references);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -0800688 RequestHeapTrim();
Mathieu Chartier662618f2012-06-06 12:01:47 -0700689 timings.AddSplit("Finish");
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700690
Mathieu Chartier662618f2012-06-06 12:01:47 -0700691 uint64_t t1 = NanoTime();
Ian Rogers3bb17a62012-01-27 23:56:44 -0800692 uint64_t duration_ns = t1 - t0;
Elliott Hughes8cf5bc02012-02-02 16:32:16 -0800693 bool gc_was_particularly_slow = duration_ns > MsToNs(50); // TODO: crank this down for concurrent.
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800694 if (VLOG_IS_ON(gc) || gc_was_particularly_slow) {
Ian Rogers3bb17a62012-01-27 23:56:44 -0800695 // TODO: somehow make the specific GC implementation (here MarkSweep) responsible for logging.
Mathieu Chartiera6399032012-06-11 18:49:50 -0700696 // Reason: For CMS sometimes initial_size < num_bytes_allocated_ results in overflow (3GB freed message).
Ian Rogers3bb17a62012-01-27 23:56:44 -0800697 size_t bytes_freed = initial_size - num_bytes_allocated_;
Ian Rogers3bb17a62012-01-27 23:56:44 -0800698 // lose low nanoseconds in duration. TODO: make this part of PrettyDuration
699 duration_ns = (duration_ns / 1000) * 1000;
Mathieu Chartier662618f2012-06-06 12:01:47 -0700700 if (concurrent) {
Elliott Hughes24edeb52012-06-18 15:29:46 -0700701 uint64_t pause_roots_time = (root_end - t0) / 1000 * 1000;
702 uint64_t pause_dirty_time = (dirty_end - dirty_begin) / 1000 * 1000;
Mathieu Chartier662618f2012-06-06 12:01:47 -0700703 LOG(INFO) << "GC freed " << PrettySize(bytes_freed) << ", " << GetPercentFree() << "% free, "
704 << PrettySize(num_bytes_allocated_) << "/" << PrettySize(GetTotalMemory()) << ", "
Elliott Hughes24edeb52012-06-18 15:29:46 -0700705 << "paused " << PrettyDuration(pause_roots_time) << "+" << PrettyDuration(pause_dirty_time)
Mathieu Chartier662618f2012-06-06 12:01:47 -0700706 << ", total " << PrettyDuration(duration_ns);
707 } else {
Elliott Hughes24edeb52012-06-18 15:29:46 -0700708 uint64_t markSweepTime = (dirty_end - t0) / 1000 * 1000;
Mathieu Chartier662618f2012-06-06 12:01:47 -0700709 LOG(INFO) << "GC freed " << PrettySize(bytes_freed) << ", " << GetPercentFree() << "% free, "
710 << PrettySize(num_bytes_allocated_) << "/" << PrettySize(GetTotalMemory()) << ", "
711 << "paused " << PrettyDuration(markSweepTime)
712 << ", total " << PrettyDuration(duration_ns);
713 }
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700714 }
Elliott Hughes767a1472011-10-26 18:49:02 -0700715 Dbg::GcDidFinish();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800716 if (VLOG_IS_ON(heap)) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700717 timings.Dump();
718 }
Mathieu Chartiera6399032012-06-11 18:49:50 -0700719
720 is_gc_running_ = false;
721
722 // Wake anyone who may have been waiting for the GC to complete.
723 condition_->Broadcast();
Carl Shapiro69759ea2011-07-21 18:13:35 -0700724}
725
726void Heap::WaitForConcurrentGcToComplete() {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700727 lock_->AssertHeld();
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700728
729 // Busy wait for GC to finish
730 if (is_gc_running_) {
Mathieu Chartiera6399032012-06-11 18:49:50 -0700731 uint64_t wait_start = NanoTime();
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700732 do {
Mathieu Chartiera6399032012-06-11 18:49:50 -0700733 ScopedThreadStateChange tsc(Thread::Current(), kVmWait);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700734 condition_->Wait(*lock_);
735 } while (is_gc_running_);
Mathieu Chartiera6399032012-06-11 18:49:50 -0700736 uint64_t wait_time = NanoTime() - wait_start;
737 if (wait_time > MsToNs(5)) {
738 LOG(INFO) << "WaitForConcurrentGcToComplete blocked for " << PrettyDuration(wait_time);
739 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700740 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700741}
742
Elliott Hughesc967f782012-04-16 10:23:15 -0700743void Heap::DumpForSigQuit(std::ostream& os) {
744 os << "Heap: " << GetPercentFree() << "% free, "
745 << PrettySize(num_bytes_allocated_) << "/" << PrettySize(GetTotalMemory())
Elliott Hughesae80b492012-04-24 10:43:17 -0700746 << "; " << num_objects_allocated_ << " objects\n";
Elliott Hughesc967f782012-04-16 10:23:15 -0700747}
748
749size_t Heap::GetPercentFree() {
750 size_t total = GetTotalMemory();
751 return 100 - static_cast<size_t>(100.0f * static_cast<float>(num_bytes_allocated_) / total);
752}
753
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800754void Heap::SetIdealFootprint(size_t max_allowed_footprint) {
Ian Rogers30fab402012-01-23 15:43:46 -0800755 size_t alloc_space_capacity = alloc_space_->Capacity();
756 if (max_allowed_footprint > alloc_space_capacity) {
Ian Rogers3bb17a62012-01-27 23:56:44 -0800757 VLOG(gc) << "Clamp target GC heap from " << PrettySize(max_allowed_footprint)
758 << " to " << PrettySize(alloc_space_capacity);
Ian Rogers30fab402012-01-23 15:43:46 -0800759 max_allowed_footprint = alloc_space_capacity;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -0700760 }
Ian Rogers30fab402012-01-23 15:43:46 -0800761 alloc_space_->SetFootprintLimit(max_allowed_footprint);
Shih-wei Liao8c2f6412011-10-03 22:58:14 -0700762}
763
Ian Rogers3bb17a62012-01-27 23:56:44 -0800764// kHeapIdealFree is the ideal maximum free size, when we grow the heap for utilization.
Shih-wei Liao7f1caab2011-10-06 12:11:04 -0700765static const size_t kHeapIdealFree = 2 * MB;
Ian Rogers3bb17a62012-01-27 23:56:44 -0800766// kHeapMinFree guarantees that you always have at least 512 KB free, when you grow for utilization,
767// regardless of target utilization ratio.
Shih-wei Liao8c2f6412011-10-03 22:58:14 -0700768static const size_t kHeapMinFree = kHeapIdealFree / 4;
769
Carl Shapiro69759ea2011-07-21 18:13:35 -0700770void Heap::GrowForUtilization() {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700771 lock_->AssertHeld();
Shih-wei Liao8c2f6412011-10-03 22:58:14 -0700772
773 // We know what our utilization is at this moment.
774 // This doesn't actually resize any memory. It just lets the heap grow more
775 // when necessary.
Elliott Hughes362f9bc2011-10-17 18:56:41 -0700776 size_t target_size(num_bytes_allocated_ / Heap::GetTargetHeapUtilization());
Shih-wei Liao8c2f6412011-10-03 22:58:14 -0700777
778 if (target_size > num_bytes_allocated_ + kHeapIdealFree) {
779 target_size = num_bytes_allocated_ + kHeapIdealFree;
780 } else if (target_size < num_bytes_allocated_ + kHeapMinFree) {
781 target_size = num_bytes_allocated_ + kHeapMinFree;
782 }
783
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700784 // Calculate when to perform the next ConcurrentGC.
785 if (GetTotalMemory() - num_bytes_allocated_ < concurrent_min_free_) {
786 // Not enough free memory to perform concurrent GC.
787 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
788 } else {
789 concurrent_start_bytes_ = alloc_space_->GetFootprintLimit() - concurrent_start_size_;
790 }
791
Shih-wei Liao8c2f6412011-10-03 22:58:14 -0700792 SetIdealFootprint(target_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700793}
794
jeffhaoc1160702011-10-27 15:48:45 -0700795void Heap::ClearGrowthLimit() {
Elliott Hughesffb465f2012-03-01 18:46:05 -0800796 ScopedHeapLock heap_lock;
jeffhaoc1160702011-10-27 15:48:45 -0700797 WaitForConcurrentGcToComplete();
jeffhaoc1160702011-10-27 15:48:45 -0700798 alloc_space_->ClearGrowthLimit();
799}
800
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -0700801pid_t Heap::GetLockOwner() {
Elliott Hughesaccd83d2011-10-17 14:25:58 -0700802 return lock_->GetOwner();
803}
804
Elliott Hughes92b3b562011-09-08 16:32:26 -0700805void Heap::Lock() {
Elliott Hughes34e06962012-04-09 13:55:55 -0700806 // Grab the lock, but put ourselves into kVmWait if it looks
Brian Carlstromfad71432011-10-16 20:25:10 -0700807 // like we're going to have to wait on the mutex. This prevents
808 // deadlock if another thread is calling CollectGarbageInternal,
809 // since they will have the heap lock and be waiting for mutators to
810 // suspend.
811 if (!lock_->TryLock()) {
Elliott Hughes34e06962012-04-09 13:55:55 -0700812 ScopedThreadStateChange tsc(Thread::Current(), kVmWait);
Brian Carlstromfad71432011-10-16 20:25:10 -0700813 lock_->Lock();
814 }
Elliott Hughes92b3b562011-09-08 16:32:26 -0700815}
816
817void Heap::Unlock() {
818 lock_->Unlock();
819}
820
Elliott Hughesadb460d2011-10-05 17:02:34 -0700821void Heap::SetReferenceOffsets(MemberOffset reference_referent_offset,
822 MemberOffset reference_queue_offset,
823 MemberOffset reference_queueNext_offset,
824 MemberOffset reference_pendingNext_offset,
825 MemberOffset finalizer_reference_zombie_offset) {
826 reference_referent_offset_ = reference_referent_offset;
827 reference_queue_offset_ = reference_queue_offset;
828 reference_queueNext_offset_ = reference_queueNext_offset;
829 reference_pendingNext_offset_ = reference_pendingNext_offset;
830 finalizer_reference_zombie_offset_ = finalizer_reference_zombie_offset;
831 CHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
832 CHECK_NE(reference_queue_offset_.Uint32Value(), 0U);
833 CHECK_NE(reference_queueNext_offset_.Uint32Value(), 0U);
834 CHECK_NE(reference_pendingNext_offset_.Uint32Value(), 0U);
835 CHECK_NE(finalizer_reference_zombie_offset_.Uint32Value(), 0U);
836}
837
838Object* Heap::GetReferenceReferent(Object* reference) {
839 DCHECK(reference != NULL);
840 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
841 return reference->GetFieldObject<Object*>(reference_referent_offset_, true);
842}
843
844void Heap::ClearReferenceReferent(Object* reference) {
845 DCHECK(reference != NULL);
846 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
847 reference->SetFieldObject(reference_referent_offset_, NULL, true);
848}
849
850// Returns true if the reference object has not yet been enqueued.
851bool Heap::IsEnqueuable(const Object* ref) {
852 DCHECK(ref != NULL);
853 const Object* queue = ref->GetFieldObject<Object*>(reference_queue_offset_, false);
854 const Object* queue_next = ref->GetFieldObject<Object*>(reference_queueNext_offset_, false);
855 return (queue != NULL) && (queue_next == NULL);
856}
857
858void Heap::EnqueueReference(Object* ref, Object** cleared_reference_list) {
859 DCHECK(ref != NULL);
860 CHECK(ref->GetFieldObject<Object*>(reference_queue_offset_, false) != NULL);
861 CHECK(ref->GetFieldObject<Object*>(reference_queueNext_offset_, false) == NULL);
862 EnqueuePendingReference(ref, cleared_reference_list);
863}
864
865void Heap::EnqueuePendingReference(Object* ref, Object** list) {
866 DCHECK(ref != NULL);
867 DCHECK(list != NULL);
868
869 if (*list == NULL) {
870 ref->SetFieldObject(reference_pendingNext_offset_, ref, false);
871 *list = ref;
872 } else {
873 Object* head = (*list)->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
874 ref->SetFieldObject(reference_pendingNext_offset_, head, false);
875 (*list)->SetFieldObject(reference_pendingNext_offset_, ref, false);
876 }
877}
878
879Object* Heap::DequeuePendingReference(Object** list) {
880 DCHECK(list != NULL);
881 DCHECK(*list != NULL);
882 Object* head = (*list)->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
883 Object* ref;
884 if (*list == head) {
885 ref = *list;
886 *list = NULL;
887 } else {
888 Object* next = head->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
889 (*list)->SetFieldObject(reference_pendingNext_offset_, next, false);
890 ref = head;
891 }
892 ref->SetFieldObject(reference_pendingNext_offset_, NULL, false);
893 return ref;
894}
895
Ian Rogers5d4bdc22011-11-02 22:15:43 -0700896void Heap::AddFinalizerReference(Thread* self, Object* object) {
Elliott Hughes34e06962012-04-09 13:55:55 -0700897 ScopedThreadStateChange tsc(self, kRunnable);
Elliott Hughes77405792012-03-15 15:22:12 -0700898 JValue args[1];
Elliott Hughesf24d3ce2012-04-11 17:43:37 -0700899 args[0].SetL(object);
Elliott Hughesa4f94742012-05-29 16:28:38 -0700900 DecodeMethod(WellKnownClasses::java_lang_ref_FinalizerReference_add)->Invoke(self, NULL, args, NULL);
Elliott Hughesadb460d2011-10-05 17:02:34 -0700901}
902
903void Heap::EnqueueClearedReferences(Object** cleared) {
904 DCHECK(cleared != NULL);
905 if (*cleared != NULL) {
Elliott Hughesadb460d2011-10-05 17:02:34 -0700906 Thread* self = Thread::Current();
Elliott Hughes34e06962012-04-09 13:55:55 -0700907 ScopedThreadStateChange tsc(self, kRunnable);
Elliott Hughes77405792012-03-15 15:22:12 -0700908 JValue args[1];
Elliott Hughesf24d3ce2012-04-11 17:43:37 -0700909 args[0].SetL(*cleared);
Elliott Hughesa4f94742012-05-29 16:28:38 -0700910 DecodeMethod(WellKnownClasses::java_lang_ref_ReferenceQueue_add)->Invoke(self, NULL, args, NULL);
Elliott Hughesadb460d2011-10-05 17:02:34 -0700911 *cleared = NULL;
912 }
913}
914
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700915void Heap::RequestConcurrentGC() {
Mathieu Chartier069387a2012-06-18 12:01:01 -0700916 // Make sure that we can do a concurrent GC.
917 if (requesting_gc_ ||
918 !Runtime::Current()->IsFinishedStarting() ||
919 Runtime::Current()->IsShuttingDown() ||
920 !Runtime::Current()->IsConcurrentGcEnabled()) {
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700921 return;
922 }
923
924 requesting_gc_ = true;
925 JNIEnv* env = Thread::Current()->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -0700926 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
927 DCHECK(WellKnownClasses::java_lang_Daemons_requestGC != NULL);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700928 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons, WellKnownClasses::java_lang_Daemons_requestGC);
929 CHECK(!env->ExceptionCheck());
930 requesting_gc_ = false;
931}
932
933void Heap::ConcurrentGC() {
934 ScopedHeapLock heap_lock;
935 WaitForConcurrentGcToComplete();
936 // Current thread needs to be runnable or else we can't suspend all threads.
937 ScopedThreadStateChange tsc(Thread::Current(), kRunnable);
938 CollectGarbageInternal(true, false);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700939}
940
941void Heap::Trim() {
Mathieu Chartier5dbf8292012-06-11 13:51:41 -0700942 lock_->AssertHeld();
Mathieu Chartiera6399032012-06-11 18:49:50 -0700943 WaitForConcurrentGcToComplete();
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700944 GetAllocSpace()->Trim();
945}
946
Elliott Hughes8cf5bc02012-02-02 16:32:16 -0800947void Heap::RequestHeapTrim() {
948 // We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
949 // because that only marks object heads, so a large array looks like lots of empty space. We
950 // don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
951 // to utilization (which is probably inversely proportional to how much benefit we can expect).
952 // We could try mincore(2) but that's only a measure of how many pages we haven't given away,
953 // not how much use we're making of those pages.
954 float utilization = static_cast<float>(num_bytes_allocated_) / alloc_space_->Size();
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700955 uint64_t ms_time = NsToMs(NanoTime());
956 if (utilization > 0.75f || ms_time - last_trim_time_ < 2 * 1000) {
957 // Don't bother trimming the heap if it's more than 75% utilized, or if a
958 // heap trim occurred in the last two seconds.
Elliott Hughes8cf5bc02012-02-02 16:32:16 -0800959 return;
960 }
Mathieu Chartiera6399032012-06-11 18:49:50 -0700961 if (!Runtime::Current()->IsFinishedStarting() || Runtime::Current()->IsShuttingDown()) {
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700962 // Heap trimming isn't supported without a Java runtime or Daemons (such as at dex2oat time)
Mathieu Chartiera6399032012-06-11 18:49:50 -0700963 // Also: we do not wish to start a heap trim if the runtime is shutting down.
Ian Rogerse1d490c2012-02-03 09:09:07 -0800964 return;
965 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700966 last_trim_time_ = ms_time;
Elliott Hughes8cf5bc02012-02-02 16:32:16 -0800967 JNIEnv* env = Thread::Current()->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -0700968 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
969 DCHECK(WellKnownClasses::java_lang_Daemons_requestHeapTrim != NULL);
Elliott Hugheseac76672012-05-24 21:56:51 -0700970 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons, WellKnownClasses::java_lang_Daemons_requestHeapTrim);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -0800971 CHECK(!env->ExceptionCheck());
972}
973
Carl Shapiro69759ea2011-07-21 18:13:35 -0700974} // namespace art