blob: 55a8afec130bd33b18b0bf6605d3263b84f5b6ec [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 Chartier06f79872012-06-21 13:51:52 -070033#include "scoped_thread_list_lock_releaser.h"
Mathieu Chartier7664f5c2012-06-08 18:15:32 -070034#include "ScopedLocalRef.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070035#include "space.h"
Carl Shapiro58551df2011-07-24 03:09:51 -070036#include "stl_util.h"
Elliott Hughes8d768a92011-09-14 16:35:25 -070037#include "thread_list.h"
Elliott Hughes767a1472011-10-26 18:49:02 -070038#include "timing_logger.h"
39#include "UniquePtr.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070040#include "well_known_classes.h"
Carl Shapiro69759ea2011-07-21 18:13:35 -070041
42namespace art {
43
Ian Rogers30fab402012-01-23 15:43:46 -080044static void UpdateFirstAndLastSpace(Space** first_space, Space** last_space, Space* space) {
45 if (*first_space == NULL) {
46 *first_space = space;
47 *last_space = space;
48 } else {
49 if ((*first_space)->Begin() > space->Begin()) {
50 *first_space = space;
51 } else if (space->Begin() > (*last_space)->Begin()) {
52 *last_space = space;
53 }
54 }
55}
56
Elliott Hughesae80b492012-04-24 10:43:17 -070057static bool GenerateImage(const std::string& image_file_name) {
Brian Carlstroma004aa92012-02-08 18:05:09 -080058 const std::string boot_class_path_string(Runtime::Current()->GetBootClassPathString());
Brian Carlstrom5643b782012-02-05 12:32:53 -080059 std::vector<std::string> boot_class_path;
60 Split(boot_class_path_string, ':', boot_class_path);
Brian Carlstromb2793372012-03-17 18:27:16 -070061 if (boot_class_path.empty()) {
62 LOG(FATAL) << "Failed to generate image because no boot class path specified";
63 }
Brian Carlstrom5643b782012-02-05 12:32:53 -080064
65 std::vector<char*> arg_vector;
66
67 std::string dex2oat_string(GetAndroidRoot());
Elliott Hughes67d92002012-03-26 15:08:51 -070068 dex2oat_string += (kIsDebugBuild ? "/bin/dex2oatd" : "/bin/dex2oat");
Brian Carlstrom5643b782012-02-05 12:32:53 -080069 const char* dex2oat = dex2oat_string.c_str();
70 arg_vector.push_back(strdup(dex2oat));
71
72 std::string image_option_string("--image=");
73 image_option_string += image_file_name;
74 const char* image_option = image_option_string.c_str();
75 arg_vector.push_back(strdup(image_option));
76
77 arg_vector.push_back(strdup("--runtime-arg"));
78 arg_vector.push_back(strdup("-Xms64m"));
79
80 arg_vector.push_back(strdup("--runtime-arg"));
81 arg_vector.push_back(strdup("-Xmx64m"));
82
83 for (size_t i = 0; i < boot_class_path.size(); i++) {
84 std::string dex_file_option_string("--dex-file=");
85 dex_file_option_string += boot_class_path[i];
86 const char* dex_file_option = dex_file_option_string.c_str();
87 arg_vector.push_back(strdup(dex_file_option));
88 }
89
90 std::string oat_file_option_string("--oat-file=");
91 oat_file_option_string += image_file_name;
92 oat_file_option_string.erase(oat_file_option_string.size() - 3);
93 oat_file_option_string += "oat";
94 const char* oat_file_option = oat_file_option_string.c_str();
95 arg_vector.push_back(strdup(oat_file_option));
96
97 arg_vector.push_back(strdup("--base=0x60000000"));
98
Elliott Hughes48436bb2012-02-07 15:23:28 -080099 std::string command_line(Join(arg_vector, ' '));
Brian Carlstrom5643b782012-02-05 12:32:53 -0800100 LOG(INFO) << command_line;
101
Elliott Hughes48436bb2012-02-07 15:23:28 -0800102 arg_vector.push_back(NULL);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800103 char** argv = &arg_vector[0];
104
105 // fork and exec dex2oat
106 pid_t pid = fork();
107 if (pid == 0) {
108 // no allocation allowed between fork and exec
109
110 // change process groups, so we don't get reaped by ProcessManager
111 setpgid(0, 0);
112
113 execv(dex2oat, argv);
114
115 PLOG(FATAL) << "execv(" << dex2oat << ") failed";
116 return false;
117 } else {
118 STLDeleteElements(&arg_vector);
119
120 // wait for dex2oat to finish
121 int status;
122 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
123 if (got_pid != pid) {
124 PLOG(ERROR) << "waitpid failed: wanted " << pid << ", got " << got_pid;
125 return false;
126 }
127 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
128 LOG(ERROR) << dex2oat << " failed: " << command_line;
129 return false;
130 }
131 }
132 return true;
133}
134
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800135Heap::Heap(size_t initial_size, size_t growth_limit, size_t capacity,
136 const std::string& original_image_file_name)
137 : lock_(NULL),
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700138 image_space_(NULL),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800139 alloc_space_(NULL),
140 mark_bitmap_(NULL),
141 live_bitmap_(NULL),
142 card_table_(NULL),
143 card_marking_disabled_(false),
144 is_gc_running_(false),
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700145 concurrent_start_size_(128 * KB),
146 concurrent_min_free_(256 * KB),
147 try_running_gc_(false),
148 requesting_gc_(false),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800149 num_bytes_allocated_(0),
150 num_objects_allocated_(0),
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700151 last_trim_time_(0),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800152 reference_referent_offset_(0),
153 reference_queue_offset_(0),
154 reference_queueNext_offset_(0),
155 reference_pendingNext_offset_(0),
156 finalizer_reference_zombie_offset_(0),
157 target_utilization_(0.5),
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700158 verify_objects_(false) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800159 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800160 LOG(INFO) << "Heap() entering";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700161 }
162
Ian Rogers30fab402012-01-23 15:43:46 -0800163 // Compute the bounds of all spaces for allocating live and mark bitmaps
164 // there will be at least one space (the alloc space)
165 Space* first_space = NULL;
166 Space* last_space = NULL;
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700167
Ian Rogers30fab402012-01-23 15:43:46 -0800168 // Requested begin for the alloc space, to follow the mapped image and oat files
169 byte* requested_begin = NULL;
Brian Carlstrom5643b782012-02-05 12:32:53 -0800170 std::string image_file_name(original_image_file_name);
171 if (!image_file_name.empty()) {
Brian Carlstrom5643b782012-02-05 12:32:53 -0800172 if (OS::FileExists(image_file_name.c_str())) {
173 // If the /system file exists, it should be up-to-date, don't try to generate
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700174 image_space_ = Space::CreateImageSpace(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800175 } else {
176 // If the /system file didn't exist, we need to use one from the art-cache.
177 // If the cache file exists, try to open, but if it fails, regenerate.
178 // If it does not exist, generate.
179 image_file_name = GetArtCacheFilenameOrDie(image_file_name);
180 if (OS::FileExists(image_file_name.c_str())) {
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700181 image_space_ = Space::CreateImageSpace(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800182 }
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700183 if (image_space_ == NULL) {
Brian Carlstrom5643b782012-02-05 12:32:53 -0800184 if (!GenerateImage(image_file_name)) {
185 LOG(FATAL) << "Failed to generate image: " << image_file_name;
186 }
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700187 image_space_ = Space::CreateImageSpace(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800188 }
189 }
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700190 if (image_space_ == NULL) {
Brian Carlstrom223f20f2012-02-04 23:06:55 -0800191 LOG(FATAL) << "Failed to create space from " << image_file_name;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700192 }
Brian Carlstrom5643b782012-02-05 12:32:53 -0800193
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700194 AddSpace(image_space_);
195 UpdateFirstAndLastSpace(&first_space, &last_space, image_space_);
Ian Rogers30fab402012-01-23 15:43:46 -0800196 // Oat files referenced by image files immediately follow them in memory, ensure alloc space
197 // isn't going to get in the middle
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700198 byte* oat_end_addr = image_space_->GetImageHeader().GetOatEnd();
199 CHECK(oat_end_addr > image_space_->End());
Ian Rogers30fab402012-01-23 15:43:46 -0800200 if (oat_end_addr > requested_begin) {
201 requested_begin = reinterpret_cast<byte*>(RoundUp(reinterpret_cast<uintptr_t>(oat_end_addr),
202 kPageSize));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700203 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700204 }
205
Ian Rogers30fab402012-01-23 15:43:46 -0800206 alloc_space_ = Space::CreateAllocSpace("alloc space", initial_size, growth_limit, capacity,
207 requested_begin);
Elliott Hughes307f75d2011-10-12 18:04:40 -0700208 if (alloc_space_ == NULL) {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700209 LOG(FATAL) << "Failed to create alloc space";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700210 }
Ian Rogers30fab402012-01-23 15:43:46 -0800211 AddSpace(alloc_space_);
212 UpdateFirstAndLastSpace(&first_space, &last_space, alloc_space_);
213 byte* heap_begin = first_space->Begin();
Ian Rogers3bb17a62012-01-27 23:56:44 -0800214 size_t heap_capacity = (last_space->Begin() - first_space->Begin()) + last_space->NonGrowthLimitCapacity();
Carl Shapiro69759ea2011-07-21 18:13:35 -0700215
216 // Allocate the initial live bitmap.
Ian Rogers30fab402012-01-23 15:43:46 -0800217 UniquePtr<HeapBitmap> live_bitmap(HeapBitmap::Create("dalvik-bitmap-1", heap_begin, heap_capacity));
Elliott Hughes90a33692011-08-30 13:27:07 -0700218 if (live_bitmap.get() == NULL) {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700219 LOG(FATAL) << "Failed to create live bitmap";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700220 }
221
Ian Rogers30fab402012-01-23 15:43:46 -0800222 // Mark image objects in the live bitmap
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800223 for (size_t i = 0; i < spaces_.size(); ++i) {
Ian Rogers30fab402012-01-23 15:43:46 -0800224 Space* space = spaces_[i];
225 if (space->IsImageSpace()) {
226 space->AsImageSpace()->RecordImageAllocations(live_bitmap.get());
227 }
228 }
229
Carl Shapiro69759ea2011-07-21 18:13:35 -0700230 // Allocate the initial mark bitmap.
Ian Rogers30fab402012-01-23 15:43:46 -0800231 UniquePtr<HeapBitmap> mark_bitmap(HeapBitmap::Create("dalvik-bitmap-2", heap_begin, heap_capacity));
Elliott Hughes90a33692011-08-30 13:27:07 -0700232 if (mark_bitmap.get() == NULL) {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700233 LOG(FATAL) << "Failed to create mark bitmap";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700234 }
235
Elliott Hughes6c9c06d2011-11-07 16:43:47 -0800236 // Allocate the card table.
Ian Rogers30fab402012-01-23 15:43:46 -0800237 UniquePtr<CardTable> card_table(CardTable::Create(heap_begin, heap_capacity));
Ian Rogers5d76c432011-10-31 21:42:49 -0700238 if (card_table.get() == NULL) {
239 LOG(FATAL) << "Failed to create card table";
240 }
241
Carl Shapiro69759ea2011-07-21 18:13:35 -0700242 live_bitmap_ = live_bitmap.release();
243 mark_bitmap_ = mark_bitmap.release();
Ian Rogers5d76c432011-10-31 21:42:49 -0700244 card_table_ = card_table.release();
Carl Shapiro69759ea2011-07-21 18:13:35 -0700245
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700246 num_bytes_allocated_ = 0;
247 num_objects_allocated_ = 0;
248
Mathieu Chartier5301cd22012-05-31 12:11:36 -0700249 mark_stack_ = MarkStack::Create();
250
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800251 // It's still too early to take a lock because there are no threads yet,
Elliott Hughes92b3b562011-09-08 16:32:26 -0700252 // but we can create the heap lock now. We don't create it earlier to
253 // make it clear that you can't use locks during heap initialization.
Elliott Hughesffb465f2012-03-01 18:46:05 -0800254 lock_ = new Mutex("Heap lock", kHeapLock);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700255 condition_ = new ConditionVariable("Heap condition variable");
256
257 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700258
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800259 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800260 LOG(INFO) << "Heap() exiting";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700261 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700262}
263
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800264void Heap::AddSpace(Space* space) {
265 spaces_.push_back(space);
266}
267
268Heap::~Heap() {
269 VLOG(heap) << "~Heap()";
Elliott Hughesb3e66df2012-01-12 14:49:18 -0800270 // We can't take the heap lock here because there might be a daemon thread suspended with the
271 // heap lock held. We know though that no non-daemon threads are executing, and we know that
272 // all daemon threads are suspended, and we also know that the threads list have been deleted, so
273 // 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 -0700274 STLDeleteElements(&spaces_);
Elliott Hughes4d6850c2012-01-18 15:55:06 -0800275 delete mark_bitmap_;
276 delete live_bitmap_;
277 delete card_table_;
Mathieu Chartier5301cd22012-05-31 12:11:36 -0700278 delete mark_stack_;
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700279 delete condition_;
Elliott Hughes4d6850c2012-01-18 15:55:06 -0800280 delete lock_;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700281}
282
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700283static void MSpaceChunkCallback(void* start, void* end, size_t used_bytes, void* arg) {
284 size_t& max_contiguous_allocation = *reinterpret_cast<size_t*>(arg);
285
286 size_t chunk_size = static_cast<size_t>(reinterpret_cast<uint8_t*>(end) - reinterpret_cast<uint8_t*>(start));
287 size_t chunk_free_bytes = 0;
288 if (used_bytes < chunk_size) {
289 chunk_free_bytes = chunk_size - used_bytes;
290 }
291
292 if (chunk_free_bytes > max_contiguous_allocation) {
293 max_contiguous_allocation = chunk_free_bytes;
294 }
295}
296
297Object* Heap::AllocObject(Class* c, size_t byte_count) {
298 // Used in the detail message if we throw an OOME.
299 int64_t total_bytes_free;
300 size_t max_contiguous_allocation;
301
Elliott Hughes418dfe72011-10-06 18:56:27 -0700302 {
Elliott Hughesffb465f2012-03-01 18:46:05 -0800303 ScopedHeapLock heap_lock;
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700304 DCHECK(c == NULL || (c->IsClassClass() && byte_count >= sizeof(Class)) ||
305 (c->IsVariableSize() || c->GetObjectSize() == byte_count) ||
306 strlen(ClassHelper(c).GetDescriptor()) == 0);
Elliott Hughes418dfe72011-10-06 18:56:27 -0700307 DCHECK_GE(byte_count, sizeof(Object));
308 Object* obj = AllocateLocked(byte_count);
309 if (obj != NULL) {
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700310 obj->SetClass(c);
Elliott Hughes545a0642011-11-08 19:10:03 -0800311 if (Dbg::IsAllocTrackingEnabled()) {
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700312 Dbg::RecordAllocation(c, byte_count);
Elliott Hughes545a0642011-11-08 19:10:03 -0800313 }
Mathieu Chartiera6399032012-06-11 18:49:50 -0700314
315 if (!is_gc_running_ && num_bytes_allocated_ >= concurrent_start_bytes_) {
316 // The SirtRef is necessary since the calls in RequestConcurrentGC
317 // are a safepoint.
318 SirtRef<Object> ref(obj);
319 RequestConcurrentGC();
320 }
321 VerifyObject(obj);
Elliott Hughes418dfe72011-10-06 18:56:27 -0700322 return obj;
323 }
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700324 total_bytes_free = GetFreeMemory();
325 max_contiguous_allocation = 0;
326 GetAllocSpace()->Walk(MSpaceChunkCallback, &max_contiguous_allocation);
Carl Shapiro58551df2011-07-24 03:09:51 -0700327 }
Elliott Hughes418dfe72011-10-06 18:56:27 -0700328
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700329 std::string msg(StringPrintf("Failed to allocate a %zd-byte %s (%lld total bytes free; largest possible contiguous allocation %zd bytes)",
330 byte_count,
331 PrettyDescriptor(c).c_str(),
332 total_bytes_free, max_contiguous_allocation));
333 Thread::Current()->ThrowOutOfMemoryError(msg.c_str());
Elliott Hughes418dfe72011-10-06 18:56:27 -0700334 return NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700335}
336
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700337bool Heap::IsHeapAddress(const Object* obj) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700338 // Note: we deliberately don't take the lock here, and mustn't test anything that would
339 // require taking the lock.
Elliott Hughes88c5c352012-03-15 18:49:48 -0700340 if (obj == NULL) {
341 return true;
342 }
343 if (!IsAligned<kObjectAlignment>(obj)) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700344 return false;
345 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800346 for (size_t i = 0; i < spaces_.size(); ++i) {
Ian Rogers30fab402012-01-23 15:43:46 -0800347 if (spaces_[i]->Contains(obj)) {
348 return true;
349 }
350 }
351 return false;
Elliott Hughesa2501992011-08-26 19:39:54 -0700352}
353
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700354bool Heap::IsLiveObjectLocked(const Object* obj) {
355 lock_->AssertHeld();
356 return IsHeapAddress(obj) && live_bitmap_->Test(obj);
357}
358
Elliott Hughes3e465b12011-09-02 18:26:12 -0700359#if VERIFY_OBJECT_ENABLED
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700360void Heap::VerifyObject(const Object* obj) {
jeffhao25045522012-03-13 19:34:37 -0700361 if (this == NULL || !verify_objects_ || Runtime::Current()->IsShuttingDown() ||
Ian Rogers141d6222012-04-05 12:23:06 -0700362 Thread::Current() == NULL ||
jeffhao25045522012-03-13 19:34:37 -0700363 Runtime::Current()->GetThreadList()->GetLockOwner() == Thread::Current()->GetTid()) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700364 return;
365 }
Elliott Hughesffb465f2012-03-01 18:46:05 -0800366 ScopedHeapLock heap_lock;
Elliott Hughes92b3b562011-09-08 16:32:26 -0700367 Heap::VerifyObjectLocked(obj);
368}
369#endif
370
371void Heap::VerifyObjectLocked(const Object* obj) {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700372 lock_->AssertHeld();
Elliott Hughes85d15452011-09-16 17:33:01 -0700373 if (obj != NULL) {
Elliott Hughes06b37d92011-10-16 11:51:29 -0700374 if (!IsAligned<kObjectAlignment>(obj)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700375 LOG(FATAL) << "Object isn't aligned: " << obj;
376 } else if (!live_bitmap_->Test(obj)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700377 LOG(FATAL) << "Object is dead: " << obj;
378 }
379 // Ignore early dawn of the universe verifications
Brian Carlstromdbc05252011-09-09 01:59:59 -0700380 if (num_objects_allocated_ > 10) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700381 const byte* raw_addr = reinterpret_cast<const byte*>(obj) +
382 Object::ClassOffset().Int32Value();
383 const Class* c = *reinterpret_cast<Class* const *>(raw_addr);
384 if (c == NULL) {
Elliott Hughes5d78d392011-12-13 16:53:05 -0800385 LOG(FATAL) << "Null class in object: " << obj;
Elliott Hughes06b37d92011-10-16 11:51:29 -0700386 } else if (!IsAligned<kObjectAlignment>(c)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700387 LOG(FATAL) << "Class isn't aligned: " << c << " in object: " << obj;
388 } else if (!live_bitmap_->Test(c)) {
389 LOG(FATAL) << "Class of object is dead: " << c << " in object: " << obj;
390 }
391 // Check obj.getClass().getClass() == obj.getClass().getClass().getClass()
Ian Rogersad25ac52011-10-04 19:13:33 -0700392 // Note: we don't use the accessors here as they have internal sanity checks
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700393 // that we don't want to run
Ian Rogers30fab402012-01-23 15:43:46 -0800394 raw_addr = reinterpret_cast<const byte*>(c) + Object::ClassOffset().Int32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700395 const Class* c_c = *reinterpret_cast<Class* const *>(raw_addr);
Ian Rogers30fab402012-01-23 15:43:46 -0800396 raw_addr = reinterpret_cast<const byte*>(c_c) + Object::ClassOffset().Int32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700397 const Class* c_c_c = *reinterpret_cast<Class* const *>(raw_addr);
398 CHECK_EQ(c_c, c_c_c);
399 }
400 }
401}
402
Brian Carlstrom78128a62011-09-15 17:21:19 -0700403void Heap::VerificationCallback(Object* obj, void* arg) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700404 DCHECK(obj != NULL);
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800405 reinterpret_cast<Heap*>(arg)->VerifyObjectLocked(obj);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700406}
407
408void Heap::VerifyHeap() {
Elliott Hughesffb465f2012-03-01 18:46:05 -0800409 ScopedHeapLock heap_lock;
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800410 live_bitmap_->Walk(Heap::VerificationCallback, this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700411}
412
Ian Rogers30fab402012-01-23 15:43:46 -0800413void Heap::RecordAllocationLocked(AllocSpace* space, const Object* obj) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700414#ifndef NDEBUG
415 if (Runtime::Current()->IsStarted()) {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700416 lock_->AssertHeld();
Elliott Hughes92b3b562011-09-08 16:32:26 -0700417 }
418#endif
Carl Shapiro58551df2011-07-24 03:09:51 -0700419 size_t size = space->AllocationSize(obj);
Elliott Hughes5d78d392011-12-13 16:53:05 -0800420 DCHECK_GT(size, 0u);
Carl Shapiro58551df2011-07-24 03:09:51 -0700421 num_bytes_allocated_ += size;
422 num_objects_allocated_ += 1;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700423
424 if (Runtime::Current()->HasStatsEnabled()) {
425 RuntimeStats* global_stats = Runtime::Current()->GetStats();
426 RuntimeStats* thread_stats = Thread::Current()->GetStats();
427 ++global_stats->allocated_objects;
428 ++thread_stats->allocated_objects;
429 global_stats->allocated_bytes += size;
430 thread_stats->allocated_bytes += size;
431 }
432
Carl Shapiro58551df2011-07-24 03:09:51 -0700433 live_bitmap_->Set(obj);
434}
435
Elliott Hughes307f75d2011-10-12 18:04:40 -0700436void Heap::RecordFreeLocked(size_t freed_objects, size_t freed_bytes) {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700437 lock_->AssertHeld();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700438
439 if (freed_objects < num_objects_allocated_) {
440 num_objects_allocated_ -= freed_objects;
441 } else {
442 num_objects_allocated_ = 0;
443 }
444 if (freed_bytes < num_bytes_allocated_) {
445 num_bytes_allocated_ -= freed_bytes;
Carl Shapiro58551df2011-07-24 03:09:51 -0700446 } else {
447 num_bytes_allocated_ = 0;
448 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700449
450 if (Runtime::Current()->HasStatsEnabled()) {
451 RuntimeStats* global_stats = Runtime::Current()->GetStats();
452 RuntimeStats* thread_stats = Thread::Current()->GetStats();
453 ++global_stats->freed_objects;
454 ++thread_stats->freed_objects;
Elliott Hughes307f75d2011-10-12 18:04:40 -0700455 global_stats->freed_bytes += freed_bytes;
456 thread_stats->freed_bytes += freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700457 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700458}
459
Elliott Hughes92b3b562011-09-08 16:32:26 -0700460Object* Heap::AllocateLocked(size_t size) {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700461 lock_->AssertHeld();
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700462 DCHECK(alloc_space_ != NULL);
Ian Rogers30fab402012-01-23 15:43:46 -0800463 AllocSpace* space = alloc_space_;
Elliott Hughes92b3b562011-09-08 16:32:26 -0700464 Object* obj = AllocateLocked(space, size);
Carl Shapiro58551df2011-07-24 03:09:51 -0700465 if (obj != NULL) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700466 RecordAllocationLocked(space, obj);
Carl Shapiro58551df2011-07-24 03:09:51 -0700467 }
468 return obj;
469}
470
Ian Rogers30fab402012-01-23 15:43:46 -0800471Object* Heap::AllocateLocked(AllocSpace* space, size_t alloc_size) {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700472 lock_->AssertHeld();
Elliott Hughes92b3b562011-09-08 16:32:26 -0700473
Brian Carlstromb82b6872011-10-26 17:18:07 -0700474 // Since allocation can cause a GC which will need to SuspendAll,
475 // make sure all allocators are in the kRunnable state.
Elliott Hughes34e06962012-04-09 13:55:55 -0700476 CHECK_EQ(Thread::Current()->GetState(), kRunnable);
Brian Carlstromb82b6872011-10-26 17:18:07 -0700477
Ian Rogers30fab402012-01-23 15:43:46 -0800478 // Fail impossible allocations
479 if (alloc_size > space->Capacity()) {
480 // On failure collect soft references
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -0700481 WaitForConcurrentGcToComplete();
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700482 CollectGarbageInternal(false, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700483 return NULL;
484 }
485
Ian Rogers30fab402012-01-23 15:43:46 -0800486 Object* ptr = space->AllocWithoutGrowth(alloc_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700487 if (ptr != NULL) {
488 return ptr;
489 }
490
Ian Rogers30fab402012-01-23 15:43:46 -0800491 // The allocation failed. If the GC is running, block until it completes and retry.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700492 if (is_gc_running_) {
Ian Rogers30fab402012-01-23 15:43:46 -0800493 // The GC is concurrently tracing the heap. Release the heap lock, wait for the GC to
494 // complete, and retrying allocating.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700495 WaitForConcurrentGcToComplete();
Ian Rogers30fab402012-01-23 15:43:46 -0800496 ptr = space->AllocWithoutGrowth(alloc_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700497 if (ptr != NULL) {
498 return ptr;
499 }
500 }
501
502 // Another failure. Our thread was starved or there may be too many
503 // live objects. Try a foreground GC. This will have no effect if
504 // the concurrent GC is already running.
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700505 if (Runtime::Current()->HasStatsEnabled()) {
506 ++Runtime::Current()->GetStats()->gc_for_alloc_count;
507 ++Thread::Current()->GetStats()->gc_for_alloc_count;
508 }
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -0700509 // We don't need a WaitForConcurrentGcToComplete here since we checked
510 // is_gc_running_ earlier and we are in a heap lock.
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700511 CollectGarbageInternal(false, false);
Ian Rogers30fab402012-01-23 15:43:46 -0800512 ptr = space->AllocWithoutGrowth(alloc_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700513 if (ptr != NULL) {
514 return ptr;
515 }
516
517 // Even that didn't work; this is an exceptional state.
518 // Try harder, growing the heap if necessary.
Ian Rogers30fab402012-01-23 15:43:46 -0800519 ptr = space->AllocWithGrowth(alloc_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700520 if (ptr != NULL) {
Ian Rogers30fab402012-01-23 15:43:46 -0800521 size_t new_footprint = space->GetFootprintLimit();
Elliott Hughes418dfe72011-10-06 18:56:27 -0700522 // OLD-TODO: may want to grow a little bit more so that the amount of
Carl Shapiro58551df2011-07-24 03:09:51 -0700523 // free space is equal to the old free space + the
524 // utilization slop for the new allocation.
Ian Rogers3bb17a62012-01-27 23:56:44 -0800525 VLOG(gc) << "Grow heap (frag case) to " << PrettySize(new_footprint)
Ian Rogers162a31c2012-01-31 16:14:31 -0800526 << " for a " << PrettySize(alloc_size) << " allocation";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700527 return ptr;
528 }
529
Elliott Hughes81ff3182012-03-23 20:35:56 -0700530 // Most allocations should have succeeded by now, so the heap is really full, really fragmented,
531 // or the requested size is really big. Do another GC, collecting SoftReferences this time. The
532 // VM spec requires that all SoftReferences have been collected and cleared before throwing OOME.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700533
Elliott Hughes418dfe72011-10-06 18:56:27 -0700534 // OLD-TODO: wait for the finalizers from the previous GC to finish
Ian Rogers3bb17a62012-01-27 23:56:44 -0800535 VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size) << " allocation";
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -0700536 // We don't need a WaitForConcurrentGcToComplete here either.
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700537 CollectGarbageInternal(false, true);
Ian Rogers30fab402012-01-23 15:43:46 -0800538 ptr = space->AllocWithGrowth(alloc_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700539 if (ptr != NULL) {
540 return ptr;
541 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700542
Carl Shapiro69759ea2011-07-21 18:13:35 -0700543 return NULL;
544}
545
Elliott Hughesbf86d042011-08-31 17:53:14 -0700546int64_t Heap::GetMaxMemory() {
Ian Rogers30fab402012-01-23 15:43:46 -0800547 return alloc_space_->Capacity();
Elliott Hughesbf86d042011-08-31 17:53:14 -0700548}
549
550int64_t Heap::GetTotalMemory() {
Ian Rogers30fab402012-01-23 15:43:46 -0800551 return alloc_space_->Capacity();
Elliott Hughesbf86d042011-08-31 17:53:14 -0700552}
553
554int64_t Heap::GetFreeMemory() {
Ian Rogers30fab402012-01-23 15:43:46 -0800555 return alloc_space_->Capacity() - num_bytes_allocated_;
Elliott Hughesbf86d042011-08-31 17:53:14 -0700556}
557
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700558class InstanceCounter {
559 public:
560 InstanceCounter(Class* c, bool count_assignable)
561 : class_(c), count_assignable_(count_assignable), count_(0) {
562 }
563
564 size_t GetCount() {
565 return count_;
566 }
567
568 static void Callback(Object* o, void* arg) {
569 reinterpret_cast<InstanceCounter*>(arg)->VisitInstance(o);
570 }
571
572 private:
573 void VisitInstance(Object* o) {
574 Class* instance_class = o->GetClass();
575 if (count_assignable_) {
576 if (instance_class == class_) {
577 ++count_;
578 }
579 } else {
580 if (instance_class != NULL && class_->IsAssignableFrom(instance_class)) {
581 ++count_;
582 }
583 }
584 }
585
586 Class* class_;
587 bool count_assignable_;
588 size_t count_;
589};
590
591int64_t Heap::CountInstances(Class* c, bool count_assignable) {
Elliott Hughesffb465f2012-03-01 18:46:05 -0800592 ScopedHeapLock heap_lock;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700593 InstanceCounter counter(c, count_assignable);
594 live_bitmap_->Walk(InstanceCounter::Callback, &counter);
595 return counter.GetCount();
596}
597
Ian Rogers30fab402012-01-23 15:43:46 -0800598void Heap::CollectGarbage(bool clear_soft_references) {
Elliott Hughesffb465f2012-03-01 18:46:05 -0800599 ScopedHeapLock heap_lock;
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -0700600 // If we just waited for a GC to complete then we do not need to do another
601 // GC unless we clear soft references.
602 if (!WaitForConcurrentGcToComplete() || clear_soft_references) {
603 CollectGarbageInternal(false, clear_soft_references);
604 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700605}
606
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700607void Heap::CollectGarbageInternal(bool concurrent, bool clear_soft_references) {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700608 lock_->AssertHeld();
Carl Shapiro58551df2011-07-24 03:09:51 -0700609
Mathieu Chartiera6399032012-06-11 18:49:50 -0700610 DCHECK(!is_gc_running_);
611 is_gc_running_ = true;
612
Mathieu Chartier662618f2012-06-06 12:01:47 -0700613 TimingLogger timings("CollectGarbageInternal");
Elliott Hughes24edeb52012-06-18 15:29:46 -0700614 uint64_t t0 = NanoTime(), root_end = 0, dirty_begin = 0, dirty_end = 0;
Mathieu Chartier662618f2012-06-06 12:01:47 -0700615
Elliott Hughes8d768a92011-09-14 16:35:25 -0700616 ThreadList* thread_list = Runtime::Current()->GetThreadList();
617 thread_list->SuspendAll();
Mathieu Chartier662618f2012-06-06 12:01:47 -0700618 timings.AddSplit("SuspendAll");
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700619
620 size_t initial_size = num_bytes_allocated_;
Elliott Hughesadb460d2011-10-05 17:02:34 -0700621 Object* cleared_references = NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700622 {
Mathieu Chartier5301cd22012-05-31 12:11:36 -0700623 MarkSweep mark_sweep(mark_stack_);
Elliott Hughes307f75d2011-10-12 18:04:40 -0700624 timings.AddSplit("ctor");
Carl Shapiro58551df2011-07-24 03:09:51 -0700625
626 mark_sweep.Init();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700627 timings.AddSplit("Init");
Carl Shapiro58551df2011-07-24 03:09:51 -0700628
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700629 if (concurrent) {
630 card_table_->ClearNonImageSpaceCards(this);
631 }
632
Carl Shapiro58551df2011-07-24 03:09:51 -0700633 mark_sweep.MarkRoots();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700634 timings.AddSplit("MarkRoots");
Carl Shapiro58551df2011-07-24 03:09:51 -0700635
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700636 if (!concurrent) {
637 mark_sweep.ScanDirtyImageRoots();
638 timings.AddSplit("ScanDirtyImageRoots");
639 }
640
Ian Rogers5d76c432011-10-31 21:42:49 -0700641 // Roots are marked on the bitmap and the mark_stack is empty
642 DCHECK(mark_sweep.IsMarkStackEmpty());
Carl Shapiro58551df2011-07-24 03:09:51 -0700643
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700644 if (concurrent) {
Mathieu Chartiera6399032012-06-11 18:49:50 -0700645 // We need to resume before unlocking or else a thread waiting for the
646 // heap lock would re-suspend since we have not yet called ResumeAll.
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700647 thread_list->ResumeAll();
Mathieu Chartiera6399032012-06-11 18:49:50 -0700648 Unlock();
Elliott Hughes24edeb52012-06-18 15:29:46 -0700649 root_end = NanoTime();
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700650 timings.AddSplit("RootEnd");
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700651 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700652
Ian Rogers5d76c432011-10-31 21:42:49 -0700653 // Recursively mark all bits set in the non-image mark bitmap
Carl Shapiro58551df2011-07-24 03:09:51 -0700654 mark_sweep.RecursiveMark();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700655 timings.AddSplit("RecursiveMark");
Carl Shapiro58551df2011-07-24 03:09:51 -0700656
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700657 if (concurrent) {
Elliott Hughes24edeb52012-06-18 15:29:46 -0700658 dirty_begin = NanoTime();
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700659 Lock();
660 thread_list->SuspendAll();
Mathieu Chartier662618f2012-06-06 12:01:47 -0700661 timings.AddSplit("ReSuspend");
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700662
663 // Re-mark root set.
664 mark_sweep.ReMarkRoots();
665 timings.AddSplit("ReMarkRoots");
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700666
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700667 // Scan dirty objects, this is required even if we are not doing a
668 // concurrent GC since we use the card table to locate image roots.
669 mark_sweep.RecursiveMarkDirtyObjects();
670 timings.AddSplit("RecursiveMarkDirtyObjects");
671 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700672
Ian Rogers30fab402012-01-23 15:43:46 -0800673 mark_sweep.ProcessReferences(clear_soft_references);
Elliott Hughes307f75d2011-10-12 18:04:40 -0700674 timings.AddSplit("ProcessReferences");
Carl Shapiro58551df2011-07-24 03:09:51 -0700675
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700676 // TODO: swap live and marked bitmaps
677 // Note: Need to be careful about image spaces if we do this since not
678 // everything image space will be marked, resulting in things not being
679 // marked as live anymore.
680
681 // Verify that we only reach marked objects from the image space
682 mark_sweep.VerifyImageRoots();
683 timings.AddSplit("VerifyImageRoots");
Carl Shapiro58551df2011-07-24 03:09:51 -0700684
685 mark_sweep.Sweep();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700686 timings.AddSplit("Sweep");
Elliott Hughesadb460d2011-10-05 17:02:34 -0700687
688 cleared_references = mark_sweep.GetClearedReferences();
Carl Shapiro58551df2011-07-24 03:09:51 -0700689 }
690
691 GrowForUtilization();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700692 timings.AddSplit("GrowForUtilization");
Elliott Hughes8d768a92011-09-14 16:35:25 -0700693 thread_list->ResumeAll();
Elliott Hughes24edeb52012-06-18 15:29:46 -0700694 dirty_end = NanoTime();
Elliott Hughesadb460d2011-10-05 17:02:34 -0700695
696 EnqueueClearedReferences(&cleared_references);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -0800697 RequestHeapTrim();
Mathieu Chartier662618f2012-06-06 12:01:47 -0700698 timings.AddSplit("Finish");
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700699
Mathieu Chartier662618f2012-06-06 12:01:47 -0700700 uint64_t t1 = NanoTime();
Ian Rogers3bb17a62012-01-27 23:56:44 -0800701 uint64_t duration_ns = t1 - t0;
Elliott Hughes8cf5bc02012-02-02 16:32:16 -0800702 bool gc_was_particularly_slow = duration_ns > MsToNs(50); // TODO: crank this down for concurrent.
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800703 if (VLOG_IS_ON(gc) || gc_was_particularly_slow) {
Ian Rogers3bb17a62012-01-27 23:56:44 -0800704 // TODO: somehow make the specific GC implementation (here MarkSweep) responsible for logging.
Mathieu Chartiera6399032012-06-11 18:49:50 -0700705 // Reason: For CMS sometimes initial_size < num_bytes_allocated_ results in overflow (3GB freed message).
Ian Rogers3bb17a62012-01-27 23:56:44 -0800706 size_t bytes_freed = initial_size - num_bytes_allocated_;
Ian Rogers3bb17a62012-01-27 23:56:44 -0800707 // lose low nanoseconds in duration. TODO: make this part of PrettyDuration
708 duration_ns = (duration_ns / 1000) * 1000;
Mathieu Chartier662618f2012-06-06 12:01:47 -0700709 if (concurrent) {
Elliott Hughes24edeb52012-06-18 15:29:46 -0700710 uint64_t pause_roots_time = (root_end - t0) / 1000 * 1000;
711 uint64_t pause_dirty_time = (dirty_end - dirty_begin) / 1000 * 1000;
Mathieu Chartier662618f2012-06-06 12:01:47 -0700712 LOG(INFO) << "GC freed " << PrettySize(bytes_freed) << ", " << GetPercentFree() << "% free, "
713 << PrettySize(num_bytes_allocated_) << "/" << PrettySize(GetTotalMemory()) << ", "
Elliott Hughes24edeb52012-06-18 15:29:46 -0700714 << "paused " << PrettyDuration(pause_roots_time) << "+" << PrettyDuration(pause_dirty_time)
Mathieu Chartier662618f2012-06-06 12:01:47 -0700715 << ", total " << PrettyDuration(duration_ns);
716 } else {
Elliott Hughes24edeb52012-06-18 15:29:46 -0700717 uint64_t markSweepTime = (dirty_end - t0) / 1000 * 1000;
Mathieu Chartier662618f2012-06-06 12:01:47 -0700718 LOG(INFO) << "GC freed " << PrettySize(bytes_freed) << ", " << GetPercentFree() << "% free, "
719 << PrettySize(num_bytes_allocated_) << "/" << PrettySize(GetTotalMemory()) << ", "
720 << "paused " << PrettyDuration(markSweepTime)
721 << ", total " << PrettyDuration(duration_ns);
722 }
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700723 }
Elliott Hughes767a1472011-10-26 18:49:02 -0700724 Dbg::GcDidFinish();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800725 if (VLOG_IS_ON(heap)) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700726 timings.Dump();
727 }
Mathieu Chartiera6399032012-06-11 18:49:50 -0700728
729 is_gc_running_ = false;
730
731 // Wake anyone who may have been waiting for the GC to complete.
732 condition_->Broadcast();
Carl Shapiro69759ea2011-07-21 18:13:35 -0700733}
734
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -0700735bool Heap::WaitForConcurrentGcToComplete() {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700736 lock_->AssertHeld();
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700737
738 // Busy wait for GC to finish
739 if (is_gc_running_) {
Mathieu Chartiera6399032012-06-11 18:49:50 -0700740 uint64_t wait_start = NanoTime();
Mathieu Chartier06f79872012-06-21 13:51:52 -0700741
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700742 do {
Mathieu Chartiera6399032012-06-11 18:49:50 -0700743 ScopedThreadStateChange tsc(Thread::Current(), kVmWait);
Mathieu Chartier06f79872012-06-21 13:51:52 -0700744 ScopedThreadListLockReleaser list_lock_releaser;
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700745 condition_->Wait(*lock_);
746 } while (is_gc_running_);
Mathieu Chartiera6399032012-06-11 18:49:50 -0700747 uint64_t wait_time = NanoTime() - wait_start;
748 if (wait_time > MsToNs(5)) {
749 LOG(INFO) << "WaitForConcurrentGcToComplete blocked for " << PrettyDuration(wait_time);
750 }
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -0700751 DCHECK(!is_gc_running_);
752 return true;
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700753 }
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -0700754 return false;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700755}
756
Elliott Hughesc967f782012-04-16 10:23:15 -0700757void Heap::DumpForSigQuit(std::ostream& os) {
758 os << "Heap: " << GetPercentFree() << "% free, "
759 << PrettySize(num_bytes_allocated_) << "/" << PrettySize(GetTotalMemory())
Elliott Hughesae80b492012-04-24 10:43:17 -0700760 << "; " << num_objects_allocated_ << " objects\n";
Elliott Hughesc967f782012-04-16 10:23:15 -0700761}
762
763size_t Heap::GetPercentFree() {
764 size_t total = GetTotalMemory();
765 return 100 - static_cast<size_t>(100.0f * static_cast<float>(num_bytes_allocated_) / total);
766}
767
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800768void Heap::SetIdealFootprint(size_t max_allowed_footprint) {
Ian Rogers30fab402012-01-23 15:43:46 -0800769 size_t alloc_space_capacity = alloc_space_->Capacity();
770 if (max_allowed_footprint > alloc_space_capacity) {
Ian Rogers3bb17a62012-01-27 23:56:44 -0800771 VLOG(gc) << "Clamp target GC heap from " << PrettySize(max_allowed_footprint)
772 << " to " << PrettySize(alloc_space_capacity);
Ian Rogers30fab402012-01-23 15:43:46 -0800773 max_allowed_footprint = alloc_space_capacity;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -0700774 }
Ian Rogers30fab402012-01-23 15:43:46 -0800775 alloc_space_->SetFootprintLimit(max_allowed_footprint);
Shih-wei Liao8c2f6412011-10-03 22:58:14 -0700776}
777
Ian Rogers3bb17a62012-01-27 23:56:44 -0800778// kHeapIdealFree is the ideal maximum free size, when we grow the heap for utilization.
Shih-wei Liao7f1caab2011-10-06 12:11:04 -0700779static const size_t kHeapIdealFree = 2 * MB;
Ian Rogers3bb17a62012-01-27 23:56:44 -0800780// kHeapMinFree guarantees that you always have at least 512 KB free, when you grow for utilization,
781// regardless of target utilization ratio.
Shih-wei Liao8c2f6412011-10-03 22:58:14 -0700782static const size_t kHeapMinFree = kHeapIdealFree / 4;
783
Carl Shapiro69759ea2011-07-21 18:13:35 -0700784void Heap::GrowForUtilization() {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700785 lock_->AssertHeld();
Shih-wei Liao8c2f6412011-10-03 22:58:14 -0700786
787 // We know what our utilization is at this moment.
788 // This doesn't actually resize any memory. It just lets the heap grow more
789 // when necessary.
Elliott Hughes362f9bc2011-10-17 18:56:41 -0700790 size_t target_size(num_bytes_allocated_ / Heap::GetTargetHeapUtilization());
Shih-wei Liao8c2f6412011-10-03 22:58:14 -0700791
792 if (target_size > num_bytes_allocated_ + kHeapIdealFree) {
793 target_size = num_bytes_allocated_ + kHeapIdealFree;
794 } else if (target_size < num_bytes_allocated_ + kHeapMinFree) {
795 target_size = num_bytes_allocated_ + kHeapMinFree;
796 }
797
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700798 // Calculate when to perform the next ConcurrentGC.
799 if (GetTotalMemory() - num_bytes_allocated_ < concurrent_min_free_) {
800 // Not enough free memory to perform concurrent GC.
801 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
802 } else {
803 concurrent_start_bytes_ = alloc_space_->GetFootprintLimit() - concurrent_start_size_;
804 }
805
Shih-wei Liao8c2f6412011-10-03 22:58:14 -0700806 SetIdealFootprint(target_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700807}
808
jeffhaoc1160702011-10-27 15:48:45 -0700809void Heap::ClearGrowthLimit() {
Elliott Hughesffb465f2012-03-01 18:46:05 -0800810 ScopedHeapLock heap_lock;
jeffhaoc1160702011-10-27 15:48:45 -0700811 WaitForConcurrentGcToComplete();
jeffhaoc1160702011-10-27 15:48:45 -0700812 alloc_space_->ClearGrowthLimit();
813}
814
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -0700815pid_t Heap::GetLockOwner() {
Elliott Hughesaccd83d2011-10-17 14:25:58 -0700816 return lock_->GetOwner();
817}
818
Elliott Hughes92b3b562011-09-08 16:32:26 -0700819void Heap::Lock() {
Elliott Hughes34e06962012-04-09 13:55:55 -0700820 // Grab the lock, but put ourselves into kVmWait if it looks
Brian Carlstromfad71432011-10-16 20:25:10 -0700821 // like we're going to have to wait on the mutex. This prevents
822 // deadlock if another thread is calling CollectGarbageInternal,
823 // since they will have the heap lock and be waiting for mutators to
824 // suspend.
825 if (!lock_->TryLock()) {
Elliott Hughes34e06962012-04-09 13:55:55 -0700826 ScopedThreadStateChange tsc(Thread::Current(), kVmWait);
Brian Carlstromfad71432011-10-16 20:25:10 -0700827 lock_->Lock();
828 }
Elliott Hughes92b3b562011-09-08 16:32:26 -0700829}
830
831void Heap::Unlock() {
832 lock_->Unlock();
833}
834
Elliott Hughesadb460d2011-10-05 17:02:34 -0700835void Heap::SetReferenceOffsets(MemberOffset reference_referent_offset,
836 MemberOffset reference_queue_offset,
837 MemberOffset reference_queueNext_offset,
838 MemberOffset reference_pendingNext_offset,
839 MemberOffset finalizer_reference_zombie_offset) {
840 reference_referent_offset_ = reference_referent_offset;
841 reference_queue_offset_ = reference_queue_offset;
842 reference_queueNext_offset_ = reference_queueNext_offset;
843 reference_pendingNext_offset_ = reference_pendingNext_offset;
844 finalizer_reference_zombie_offset_ = finalizer_reference_zombie_offset;
845 CHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
846 CHECK_NE(reference_queue_offset_.Uint32Value(), 0U);
847 CHECK_NE(reference_queueNext_offset_.Uint32Value(), 0U);
848 CHECK_NE(reference_pendingNext_offset_.Uint32Value(), 0U);
849 CHECK_NE(finalizer_reference_zombie_offset_.Uint32Value(), 0U);
850}
851
852Object* Heap::GetReferenceReferent(Object* reference) {
853 DCHECK(reference != NULL);
854 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
855 return reference->GetFieldObject<Object*>(reference_referent_offset_, true);
856}
857
858void Heap::ClearReferenceReferent(Object* reference) {
859 DCHECK(reference != NULL);
860 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
861 reference->SetFieldObject(reference_referent_offset_, NULL, true);
862}
863
864// Returns true if the reference object has not yet been enqueued.
865bool Heap::IsEnqueuable(const Object* ref) {
866 DCHECK(ref != NULL);
867 const Object* queue = ref->GetFieldObject<Object*>(reference_queue_offset_, false);
868 const Object* queue_next = ref->GetFieldObject<Object*>(reference_queueNext_offset_, false);
869 return (queue != NULL) && (queue_next == NULL);
870}
871
872void Heap::EnqueueReference(Object* ref, Object** cleared_reference_list) {
873 DCHECK(ref != NULL);
874 CHECK(ref->GetFieldObject<Object*>(reference_queue_offset_, false) != NULL);
875 CHECK(ref->GetFieldObject<Object*>(reference_queueNext_offset_, false) == NULL);
876 EnqueuePendingReference(ref, cleared_reference_list);
877}
878
879void Heap::EnqueuePendingReference(Object* ref, Object** list) {
880 DCHECK(ref != NULL);
881 DCHECK(list != NULL);
882
883 if (*list == NULL) {
884 ref->SetFieldObject(reference_pendingNext_offset_, ref, false);
885 *list = ref;
886 } else {
887 Object* head = (*list)->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
888 ref->SetFieldObject(reference_pendingNext_offset_, head, false);
889 (*list)->SetFieldObject(reference_pendingNext_offset_, ref, false);
890 }
891}
892
893Object* Heap::DequeuePendingReference(Object** list) {
894 DCHECK(list != NULL);
895 DCHECK(*list != NULL);
896 Object* head = (*list)->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
897 Object* ref;
898 if (*list == head) {
899 ref = *list;
900 *list = NULL;
901 } else {
902 Object* next = head->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
903 (*list)->SetFieldObject(reference_pendingNext_offset_, next, false);
904 ref = head;
905 }
906 ref->SetFieldObject(reference_pendingNext_offset_, NULL, false);
907 return ref;
908}
909
Ian Rogers5d4bdc22011-11-02 22:15:43 -0700910void Heap::AddFinalizerReference(Thread* self, Object* object) {
Elliott Hughes34e06962012-04-09 13:55:55 -0700911 ScopedThreadStateChange tsc(self, kRunnable);
Elliott Hughes77405792012-03-15 15:22:12 -0700912 JValue args[1];
Elliott Hughesf24d3ce2012-04-11 17:43:37 -0700913 args[0].SetL(object);
Elliott Hughesa4f94742012-05-29 16:28:38 -0700914 DecodeMethod(WellKnownClasses::java_lang_ref_FinalizerReference_add)->Invoke(self, NULL, args, NULL);
Elliott Hughesadb460d2011-10-05 17:02:34 -0700915}
916
917void Heap::EnqueueClearedReferences(Object** cleared) {
918 DCHECK(cleared != NULL);
919 if (*cleared != NULL) {
Elliott Hughesadb460d2011-10-05 17:02:34 -0700920 Thread* self = Thread::Current();
Elliott Hughes34e06962012-04-09 13:55:55 -0700921 ScopedThreadStateChange tsc(self, kRunnable);
Elliott Hughes77405792012-03-15 15:22:12 -0700922 JValue args[1];
Elliott Hughesf24d3ce2012-04-11 17:43:37 -0700923 args[0].SetL(*cleared);
Elliott Hughesa4f94742012-05-29 16:28:38 -0700924 DecodeMethod(WellKnownClasses::java_lang_ref_ReferenceQueue_add)->Invoke(self, NULL, args, NULL);
Elliott Hughesadb460d2011-10-05 17:02:34 -0700925 *cleared = NULL;
926 }
927}
928
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700929void Heap::RequestConcurrentGC() {
Mathieu Chartier069387a2012-06-18 12:01:01 -0700930 // Make sure that we can do a concurrent GC.
931 if (requesting_gc_ ||
932 !Runtime::Current()->IsFinishedStarting() ||
933 Runtime::Current()->IsShuttingDown() ||
934 !Runtime::Current()->IsConcurrentGcEnabled()) {
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700935 return;
936 }
937
938 requesting_gc_ = true;
939 JNIEnv* env = Thread::Current()->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -0700940 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
941 DCHECK(WellKnownClasses::java_lang_Daemons_requestGC != NULL);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700942 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons, WellKnownClasses::java_lang_Daemons_requestGC);
943 CHECK(!env->ExceptionCheck());
944 requesting_gc_ = false;
945}
946
947void Heap::ConcurrentGC() {
948 ScopedHeapLock heap_lock;
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -0700949 // We shouldn't need a WaitForConcurrentGcToComplete here since only
950 // concurrent GC resumes threads before the GC is completed and this function
951 // is only called within the GC daemon thread.
952 CHECK(!is_gc_running_);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700953 // Current thread needs to be runnable or else we can't suspend all threads.
954 ScopedThreadStateChange tsc(Thread::Current(), kRunnable);
955 CollectGarbageInternal(true, false);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700956}
957
958void Heap::Trim() {
Mathieu Chartier5dbf8292012-06-11 13:51:41 -0700959 lock_->AssertHeld();
Mathieu Chartiera6399032012-06-11 18:49:50 -0700960 WaitForConcurrentGcToComplete();
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700961 GetAllocSpace()->Trim();
962}
963
Elliott Hughes8cf5bc02012-02-02 16:32:16 -0800964void Heap::RequestHeapTrim() {
965 // We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
966 // because that only marks object heads, so a large array looks like lots of empty space. We
967 // don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
968 // to utilization (which is probably inversely proportional to how much benefit we can expect).
969 // We could try mincore(2) but that's only a measure of how many pages we haven't given away,
970 // not how much use we're making of those pages.
971 float utilization = static_cast<float>(num_bytes_allocated_) / alloc_space_->Size();
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700972 uint64_t ms_time = NsToMs(NanoTime());
973 if (utilization > 0.75f || ms_time - last_trim_time_ < 2 * 1000) {
974 // Don't bother trimming the heap if it's more than 75% utilized, or if a
975 // heap trim occurred in the last two seconds.
Elliott Hughes8cf5bc02012-02-02 16:32:16 -0800976 return;
977 }
Mathieu Chartiera6399032012-06-11 18:49:50 -0700978 if (!Runtime::Current()->IsFinishedStarting() || Runtime::Current()->IsShuttingDown()) {
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700979 // Heap trimming isn't supported without a Java runtime or Daemons (such as at dex2oat time)
Mathieu Chartiera6399032012-06-11 18:49:50 -0700980 // Also: we do not wish to start a heap trim if the runtime is shutting down.
Ian Rogerse1d490c2012-02-03 09:09:07 -0800981 return;
982 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700983 last_trim_time_ = ms_time;
Elliott Hughes8cf5bc02012-02-02 16:32:16 -0800984 JNIEnv* env = Thread::Current()->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -0700985 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
986 DCHECK(WellKnownClasses::java_lang_Daemons_requestHeapTrim != NULL);
Elliott Hugheseac76672012-05-24 21:56:51 -0700987 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons, WellKnownClasses::java_lang_Daemons_requestHeapTrim);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -0800988 CHECK(!env->ExceptionCheck());
989}
990
Carl Shapiro69759ea2011-07-21 18:13:35 -0700991} // namespace art