blob: c6dfdf78a8a7f31fc781f2664c193d6e9e6d2b4b [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"
Mathieu Chartierb43b7d42012-06-19 13:15:09 -070029#include "mod_union_table.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070030#include "object.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080031#include "object_utils.h"
Brian Carlstrom5643b782012-02-05 12:32:53 -080032#include "os.h"
Elliott Hughesb3bd5f02012-03-08 21:05:27 -080033#include "scoped_heap_lock.h"
Ian Rogers365c1022012-06-22 15:05:28 -070034#include "scoped_jni_thread_state.h"
Mathieu Chartier06f79872012-06-21 13:51:52 -070035#include "scoped_thread_list_lock_releaser.h"
Mathieu Chartier7664f5c2012-06-08 18:15:32 -070036#include "ScopedLocalRef.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070037#include "space.h"
Carl Shapiro58551df2011-07-24 03:09:51 -070038#include "stl_util.h"
Elliott Hughes8d768a92011-09-14 16:35:25 -070039#include "thread_list.h"
Elliott Hughes767a1472011-10-26 18:49:02 -070040#include "timing_logger.h"
41#include "UniquePtr.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070042#include "well_known_classes.h"
Carl Shapiro69759ea2011-07-21 18:13:35 -070043
44namespace art {
45
Ian Rogers30fab402012-01-23 15:43:46 -080046static void UpdateFirstAndLastSpace(Space** first_space, Space** last_space, Space* space) {
47 if (*first_space == NULL) {
48 *first_space = space;
49 *last_space = space;
50 } else {
51 if ((*first_space)->Begin() > space->Begin()) {
52 *first_space = space;
53 } else if (space->Begin() > (*last_space)->Begin()) {
54 *last_space = space;
55 }
56 }
57}
58
Elliott Hughesae80b492012-04-24 10:43:17 -070059static bool GenerateImage(const std::string& image_file_name) {
Brian Carlstroma004aa92012-02-08 18:05:09 -080060 const std::string boot_class_path_string(Runtime::Current()->GetBootClassPathString());
Brian Carlstrom5643b782012-02-05 12:32:53 -080061 std::vector<std::string> boot_class_path;
62 Split(boot_class_path_string, ':', boot_class_path);
Brian Carlstromb2793372012-03-17 18:27:16 -070063 if (boot_class_path.empty()) {
64 LOG(FATAL) << "Failed to generate image because no boot class path specified";
65 }
Brian Carlstrom5643b782012-02-05 12:32:53 -080066
67 std::vector<char*> arg_vector;
68
69 std::string dex2oat_string(GetAndroidRoot());
Elliott Hughes67d92002012-03-26 15:08:51 -070070 dex2oat_string += (kIsDebugBuild ? "/bin/dex2oatd" : "/bin/dex2oat");
Brian Carlstrom5643b782012-02-05 12:32:53 -080071 const char* dex2oat = dex2oat_string.c_str();
72 arg_vector.push_back(strdup(dex2oat));
73
74 std::string image_option_string("--image=");
75 image_option_string += image_file_name;
76 const char* image_option = image_option_string.c_str();
77 arg_vector.push_back(strdup(image_option));
78
79 arg_vector.push_back(strdup("--runtime-arg"));
80 arg_vector.push_back(strdup("-Xms64m"));
81
82 arg_vector.push_back(strdup("--runtime-arg"));
83 arg_vector.push_back(strdup("-Xmx64m"));
84
85 for (size_t i = 0; i < boot_class_path.size(); i++) {
86 std::string dex_file_option_string("--dex-file=");
87 dex_file_option_string += boot_class_path[i];
88 const char* dex_file_option = dex_file_option_string.c_str();
89 arg_vector.push_back(strdup(dex_file_option));
90 }
91
92 std::string oat_file_option_string("--oat-file=");
93 oat_file_option_string += image_file_name;
94 oat_file_option_string.erase(oat_file_option_string.size() - 3);
95 oat_file_option_string += "oat";
96 const char* oat_file_option = oat_file_option_string.c_str();
97 arg_vector.push_back(strdup(oat_file_option));
98
99 arg_vector.push_back(strdup("--base=0x60000000"));
100
Elliott Hughes48436bb2012-02-07 15:23:28 -0800101 std::string command_line(Join(arg_vector, ' '));
Brian Carlstrom5643b782012-02-05 12:32:53 -0800102 LOG(INFO) << command_line;
103
Elliott Hughes48436bb2012-02-07 15:23:28 -0800104 arg_vector.push_back(NULL);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800105 char** argv = &arg_vector[0];
106
107 // fork and exec dex2oat
108 pid_t pid = fork();
109 if (pid == 0) {
110 // no allocation allowed between fork and exec
111
112 // change process groups, so we don't get reaped by ProcessManager
113 setpgid(0, 0);
114
115 execv(dex2oat, argv);
116
117 PLOG(FATAL) << "execv(" << dex2oat << ") failed";
118 return false;
119 } else {
120 STLDeleteElements(&arg_vector);
121
122 // wait for dex2oat to finish
123 int status;
124 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
125 if (got_pid != pid) {
126 PLOG(ERROR) << "waitpid failed: wanted " << pid << ", got " << got_pid;
127 return false;
128 }
129 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
130 LOG(ERROR) << dex2oat << " failed: " << command_line;
131 return false;
132 }
133 }
134 return true;
135}
136
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800137Heap::Heap(size_t initial_size, size_t growth_limit, size_t capacity,
138 const std::string& original_image_file_name)
139 : lock_(NULL),
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700140 image_space_(NULL),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800141 alloc_space_(NULL),
142 mark_bitmap_(NULL),
143 live_bitmap_(NULL),
144 card_table_(NULL),
145 card_marking_disabled_(false),
146 is_gc_running_(false),
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700147 concurrent_start_size_(128 * KB),
148 concurrent_min_free_(256 * KB),
149 try_running_gc_(false),
150 requesting_gc_(false),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800151 num_bytes_allocated_(0),
152 num_objects_allocated_(0),
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700153 last_trim_time_(0),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800154 reference_referent_offset_(0),
155 reference_queue_offset_(0),
156 reference_queueNext_offset_(0),
157 reference_pendingNext_offset_(0),
158 finalizer_reference_zombie_offset_(0),
159 target_utilization_(0.5),
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700160 verify_objects_(false) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800161 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800162 LOG(INFO) << "Heap() entering";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700163 }
164
Ian Rogers30fab402012-01-23 15:43:46 -0800165 // Compute the bounds of all spaces for allocating live and mark bitmaps
166 // there will be at least one space (the alloc space)
167 Space* first_space = NULL;
168 Space* last_space = NULL;
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700169
Ian Rogers30fab402012-01-23 15:43:46 -0800170 // Requested begin for the alloc space, to follow the mapped image and oat files
171 byte* requested_begin = NULL;
Brian Carlstrom5643b782012-02-05 12:32:53 -0800172 std::string image_file_name(original_image_file_name);
173 if (!image_file_name.empty()) {
Brian Carlstrom5643b782012-02-05 12:32:53 -0800174 if (OS::FileExists(image_file_name.c_str())) {
175 // If the /system file exists, it should be up-to-date, don't try to generate
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700176 image_space_ = Space::CreateImageSpace(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800177 } else {
178 // If the /system file didn't exist, we need to use one from the art-cache.
179 // If the cache file exists, try to open, but if it fails, regenerate.
180 // If it does not exist, generate.
181 image_file_name = GetArtCacheFilenameOrDie(image_file_name);
182 if (OS::FileExists(image_file_name.c_str())) {
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700183 image_space_ = Space::CreateImageSpace(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800184 }
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700185 if (image_space_ == NULL) {
Brian Carlstrom5643b782012-02-05 12:32:53 -0800186 if (!GenerateImage(image_file_name)) {
187 LOG(FATAL) << "Failed to generate image: " << image_file_name;
188 }
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700189 image_space_ = Space::CreateImageSpace(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800190 }
191 }
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700192 if (image_space_ == NULL) {
Brian Carlstrom223f20f2012-02-04 23:06:55 -0800193 LOG(FATAL) << "Failed to create space from " << image_file_name;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700194 }
Brian Carlstrom5643b782012-02-05 12:32:53 -0800195
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700196 AddSpace(image_space_);
197 UpdateFirstAndLastSpace(&first_space, &last_space, image_space_);
Ian Rogers30fab402012-01-23 15:43:46 -0800198 // Oat files referenced by image files immediately follow them in memory, ensure alloc space
199 // isn't going to get in the middle
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700200 byte* oat_end_addr = image_space_->GetImageHeader().GetOatEnd();
201 CHECK(oat_end_addr > image_space_->End());
Ian Rogers30fab402012-01-23 15:43:46 -0800202 if (oat_end_addr > requested_begin) {
203 requested_begin = reinterpret_cast<byte*>(RoundUp(reinterpret_cast<uintptr_t>(oat_end_addr),
204 kPageSize));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700205 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700206 }
207
Ian Rogers30fab402012-01-23 15:43:46 -0800208 alloc_space_ = Space::CreateAllocSpace("alloc space", initial_size, growth_limit, capacity,
209 requested_begin);
Elliott Hughes307f75d2011-10-12 18:04:40 -0700210 if (alloc_space_ == NULL) {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700211 LOG(FATAL) << "Failed to create alloc space";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700212 }
Ian Rogers30fab402012-01-23 15:43:46 -0800213 AddSpace(alloc_space_);
214 UpdateFirstAndLastSpace(&first_space, &last_space, alloc_space_);
215 byte* heap_begin = first_space->Begin();
Ian Rogers3bb17a62012-01-27 23:56:44 -0800216 size_t heap_capacity = (last_space->Begin() - first_space->Begin()) + last_space->NonGrowthLimitCapacity();
Carl Shapiro69759ea2011-07-21 18:13:35 -0700217
218 // Allocate the initial live bitmap.
Ian Rogers30fab402012-01-23 15:43:46 -0800219 UniquePtr<HeapBitmap> live_bitmap(HeapBitmap::Create("dalvik-bitmap-1", heap_begin, heap_capacity));
Elliott Hughes90a33692011-08-30 13:27:07 -0700220 if (live_bitmap.get() == NULL) {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700221 LOG(FATAL) << "Failed to create live bitmap";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700222 }
223
Ian Rogers30fab402012-01-23 15:43:46 -0800224 // Mark image objects in the live bitmap
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800225 for (size_t i = 0; i < spaces_.size(); ++i) {
Ian Rogers30fab402012-01-23 15:43:46 -0800226 Space* space = spaces_[i];
227 if (space->IsImageSpace()) {
228 space->AsImageSpace()->RecordImageAllocations(live_bitmap.get());
229 }
230 }
231
Carl Shapiro69759ea2011-07-21 18:13:35 -0700232 // Allocate the initial mark bitmap.
Ian Rogers30fab402012-01-23 15:43:46 -0800233 UniquePtr<HeapBitmap> mark_bitmap(HeapBitmap::Create("dalvik-bitmap-2", heap_begin, heap_capacity));
Elliott Hughes90a33692011-08-30 13:27:07 -0700234 if (mark_bitmap.get() == NULL) {
Elliott Hughesbe759c62011-09-08 19:38:21 -0700235 LOG(FATAL) << "Failed to create mark bitmap";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700236 }
237
Elliott Hughes6c9c06d2011-11-07 16:43:47 -0800238 // Allocate the card table.
Ian Rogers30fab402012-01-23 15:43:46 -0800239 UniquePtr<CardTable> card_table(CardTable::Create(heap_begin, heap_capacity));
Ian Rogers5d76c432011-10-31 21:42:49 -0700240 if (card_table.get() == NULL) {
241 LOG(FATAL) << "Failed to create card table";
242 }
243
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700244 // Allocate the mod-union table
245 ModUnionTableBitmap* mod_union_table = new ModUnionTableBitmap(this);
246 mod_union_table->Init();
247 mod_union_table_ = mod_union_table;
248
Carl Shapiro69759ea2011-07-21 18:13:35 -0700249 live_bitmap_ = live_bitmap.release();
250 mark_bitmap_ = mark_bitmap.release();
Ian Rogers5d76c432011-10-31 21:42:49 -0700251 card_table_ = card_table.release();
Carl Shapiro69759ea2011-07-21 18:13:35 -0700252
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700253 num_bytes_allocated_ = 0;
254 num_objects_allocated_ = 0;
255
Mathieu Chartier5301cd22012-05-31 12:11:36 -0700256 mark_stack_ = MarkStack::Create();
257
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800258 // It's still too early to take a lock because there are no threads yet,
Elliott Hughes92b3b562011-09-08 16:32:26 -0700259 // but we can create the heap lock now. We don't create it earlier to
260 // make it clear that you can't use locks during heap initialization.
Elliott Hughesffb465f2012-03-01 18:46:05 -0800261 lock_ = new Mutex("Heap lock", kHeapLock);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700262 condition_ = new ConditionVariable("Heap condition variable");
263
264 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700265
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800266 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800267 LOG(INFO) << "Heap() exiting";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700268 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700269}
270
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800271void Heap::AddSpace(Space* space) {
272 spaces_.push_back(space);
273}
274
275Heap::~Heap() {
276 VLOG(heap) << "~Heap()";
Elliott Hughesb3e66df2012-01-12 14:49:18 -0800277 // We can't take the heap lock here because there might be a daemon thread suspended with the
278 // heap lock held. We know though that no non-daemon threads are executing, and we know that
279 // all daemon threads are suspended, and we also know that the threads list have been deleted, so
280 // 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 -0700281 STLDeleteElements(&spaces_);
Elliott Hughes4d6850c2012-01-18 15:55:06 -0800282 delete mark_bitmap_;
283 delete live_bitmap_;
284 delete card_table_;
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700285 delete mod_union_table_;
Mathieu Chartier5301cd22012-05-31 12:11:36 -0700286 delete mark_stack_;
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700287 delete condition_;
Elliott Hughes4d6850c2012-01-18 15:55:06 -0800288 delete lock_;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700289}
290
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700291static void MSpaceChunkCallback(void* start, void* end, size_t used_bytes, void* arg) {
292 size_t& max_contiguous_allocation = *reinterpret_cast<size_t*>(arg);
293
294 size_t chunk_size = static_cast<size_t>(reinterpret_cast<uint8_t*>(end) - reinterpret_cast<uint8_t*>(start));
295 size_t chunk_free_bytes = 0;
296 if (used_bytes < chunk_size) {
297 chunk_free_bytes = chunk_size - used_bytes;
298 }
299
300 if (chunk_free_bytes > max_contiguous_allocation) {
301 max_contiguous_allocation = chunk_free_bytes;
302 }
303}
304
305Object* Heap::AllocObject(Class* c, size_t byte_count) {
306 // Used in the detail message if we throw an OOME.
307 int64_t total_bytes_free;
308 size_t max_contiguous_allocation;
309
Elliott Hughes418dfe72011-10-06 18:56:27 -0700310 {
Elliott Hughesffb465f2012-03-01 18:46:05 -0800311 ScopedHeapLock heap_lock;
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700312 DCHECK(c == NULL || (c->IsClassClass() && byte_count >= sizeof(Class)) ||
313 (c->IsVariableSize() || c->GetObjectSize() == byte_count) ||
314 strlen(ClassHelper(c).GetDescriptor()) == 0);
Elliott Hughes418dfe72011-10-06 18:56:27 -0700315 DCHECK_GE(byte_count, sizeof(Object));
316 Object* obj = AllocateLocked(byte_count);
317 if (obj != NULL) {
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700318 obj->SetClass(c);
Elliott Hughes545a0642011-11-08 19:10:03 -0800319 if (Dbg::IsAllocTrackingEnabled()) {
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700320 Dbg::RecordAllocation(c, byte_count);
Elliott Hughes545a0642011-11-08 19:10:03 -0800321 }
Mathieu Chartiera6399032012-06-11 18:49:50 -0700322
323 if (!is_gc_running_ && num_bytes_allocated_ >= concurrent_start_bytes_) {
324 // The SirtRef is necessary since the calls in RequestConcurrentGC
325 // are a safepoint.
326 SirtRef<Object> ref(obj);
327 RequestConcurrentGC();
328 }
329 VerifyObject(obj);
Elliott Hughes418dfe72011-10-06 18:56:27 -0700330 return obj;
331 }
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700332 total_bytes_free = GetFreeMemory();
333 max_contiguous_allocation = 0;
334 GetAllocSpace()->Walk(MSpaceChunkCallback, &max_contiguous_allocation);
Carl Shapiro58551df2011-07-24 03:09:51 -0700335 }
Elliott Hughes418dfe72011-10-06 18:56:27 -0700336
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700337 std::string msg(StringPrintf("Failed to allocate a %zd-byte %s (%lld total bytes free; largest possible contiguous allocation %zd bytes)",
338 byte_count,
339 PrettyDescriptor(c).c_str(),
340 total_bytes_free, max_contiguous_allocation));
341 Thread::Current()->ThrowOutOfMemoryError(msg.c_str());
Elliott Hughes418dfe72011-10-06 18:56:27 -0700342 return NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700343}
344
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700345bool Heap::IsHeapAddress(const Object* obj) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700346 // Note: we deliberately don't take the lock here, and mustn't test anything that would
347 // require taking the lock.
Elliott Hughes88c5c352012-03-15 18:49:48 -0700348 if (obj == NULL) {
349 return true;
350 }
351 if (!IsAligned<kObjectAlignment>(obj)) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700352 return false;
353 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800354 for (size_t i = 0; i < spaces_.size(); ++i) {
Ian Rogers30fab402012-01-23 15:43:46 -0800355 if (spaces_[i]->Contains(obj)) {
356 return true;
357 }
358 }
359 return false;
Elliott Hughesa2501992011-08-26 19:39:54 -0700360}
361
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700362bool Heap::IsLiveObjectLocked(const Object* obj) {
363 lock_->AssertHeld();
364 return IsHeapAddress(obj) && live_bitmap_->Test(obj);
365}
366
Elliott Hughes3e465b12011-09-02 18:26:12 -0700367#if VERIFY_OBJECT_ENABLED
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700368void Heap::VerifyObject(const Object* obj) {
jeffhao25045522012-03-13 19:34:37 -0700369 if (this == NULL || !verify_objects_ || Runtime::Current()->IsShuttingDown() ||
Ian Rogers141d6222012-04-05 12:23:06 -0700370 Thread::Current() == NULL ||
jeffhao25045522012-03-13 19:34:37 -0700371 Runtime::Current()->GetThreadList()->GetLockOwner() == Thread::Current()->GetTid()) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700372 return;
373 }
Elliott Hughesffb465f2012-03-01 18:46:05 -0800374 ScopedHeapLock heap_lock;
Elliott Hughes92b3b562011-09-08 16:32:26 -0700375 Heap::VerifyObjectLocked(obj);
376}
377#endif
378
379void Heap::VerifyObjectLocked(const Object* obj) {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700380 lock_->AssertHeld();
Elliott Hughes85d15452011-09-16 17:33:01 -0700381 if (obj != NULL) {
Elliott Hughes06b37d92011-10-16 11:51:29 -0700382 if (!IsAligned<kObjectAlignment>(obj)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700383 LOG(FATAL) << "Object isn't aligned: " << obj;
384 } else if (!live_bitmap_->Test(obj)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700385 LOG(FATAL) << "Object is dead: " << obj;
386 }
387 // Ignore early dawn of the universe verifications
Brian Carlstromdbc05252011-09-09 01:59:59 -0700388 if (num_objects_allocated_ > 10) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700389 const byte* raw_addr = reinterpret_cast<const byte*>(obj) +
390 Object::ClassOffset().Int32Value();
391 const Class* c = *reinterpret_cast<Class* const *>(raw_addr);
392 if (c == NULL) {
Elliott Hughes5d78d392011-12-13 16:53:05 -0800393 LOG(FATAL) << "Null class in object: " << obj;
Elliott Hughes06b37d92011-10-16 11:51:29 -0700394 } else if (!IsAligned<kObjectAlignment>(c)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700395 LOG(FATAL) << "Class isn't aligned: " << c << " in object: " << obj;
396 } else if (!live_bitmap_->Test(c)) {
397 LOG(FATAL) << "Class of object is dead: " << c << " in object: " << obj;
398 }
399 // Check obj.getClass().getClass() == obj.getClass().getClass().getClass()
Ian Rogersad25ac52011-10-04 19:13:33 -0700400 // Note: we don't use the accessors here as they have internal sanity checks
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700401 // that we don't want to run
Ian Rogers30fab402012-01-23 15:43:46 -0800402 raw_addr = reinterpret_cast<const byte*>(c) + Object::ClassOffset().Int32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700403 const Class* c_c = *reinterpret_cast<Class* const *>(raw_addr);
Ian Rogers30fab402012-01-23 15:43:46 -0800404 raw_addr = reinterpret_cast<const byte*>(c_c) + Object::ClassOffset().Int32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700405 const Class* c_c_c = *reinterpret_cast<Class* const *>(raw_addr);
406 CHECK_EQ(c_c, c_c_c);
407 }
408 }
409}
410
Brian Carlstrom78128a62011-09-15 17:21:19 -0700411void Heap::VerificationCallback(Object* obj, void* arg) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700412 DCHECK(obj != NULL);
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800413 reinterpret_cast<Heap*>(arg)->VerifyObjectLocked(obj);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700414}
415
416void Heap::VerifyHeap() {
Elliott Hughesffb465f2012-03-01 18:46:05 -0800417 ScopedHeapLock heap_lock;
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800418 live_bitmap_->Walk(Heap::VerificationCallback, this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700419}
420
Ian Rogers30fab402012-01-23 15:43:46 -0800421void Heap::RecordAllocationLocked(AllocSpace* space, const Object* obj) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700422#ifndef NDEBUG
423 if (Runtime::Current()->IsStarted()) {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700424 lock_->AssertHeld();
Elliott Hughes92b3b562011-09-08 16:32:26 -0700425 }
426#endif
Carl Shapiro58551df2011-07-24 03:09:51 -0700427 size_t size = space->AllocationSize(obj);
Elliott Hughes5d78d392011-12-13 16:53:05 -0800428 DCHECK_GT(size, 0u);
Carl Shapiro58551df2011-07-24 03:09:51 -0700429 num_bytes_allocated_ += size;
430 num_objects_allocated_ += 1;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700431
432 if (Runtime::Current()->HasStatsEnabled()) {
433 RuntimeStats* global_stats = Runtime::Current()->GetStats();
434 RuntimeStats* thread_stats = Thread::Current()->GetStats();
435 ++global_stats->allocated_objects;
436 ++thread_stats->allocated_objects;
437 global_stats->allocated_bytes += size;
438 thread_stats->allocated_bytes += size;
439 }
440
Carl Shapiro58551df2011-07-24 03:09:51 -0700441 live_bitmap_->Set(obj);
442}
443
Elliott Hughes307f75d2011-10-12 18:04:40 -0700444void Heap::RecordFreeLocked(size_t freed_objects, size_t freed_bytes) {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700445 lock_->AssertHeld();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700446
447 if (freed_objects < num_objects_allocated_) {
448 num_objects_allocated_ -= freed_objects;
449 } else {
450 num_objects_allocated_ = 0;
451 }
452 if (freed_bytes < num_bytes_allocated_) {
453 num_bytes_allocated_ -= freed_bytes;
Carl Shapiro58551df2011-07-24 03:09:51 -0700454 } else {
455 num_bytes_allocated_ = 0;
456 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700457
458 if (Runtime::Current()->HasStatsEnabled()) {
459 RuntimeStats* global_stats = Runtime::Current()->GetStats();
460 RuntimeStats* thread_stats = Thread::Current()->GetStats();
461 ++global_stats->freed_objects;
462 ++thread_stats->freed_objects;
Elliott Hughes307f75d2011-10-12 18:04:40 -0700463 global_stats->freed_bytes += freed_bytes;
464 thread_stats->freed_bytes += freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700465 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700466}
467
Elliott Hughes92b3b562011-09-08 16:32:26 -0700468Object* Heap::AllocateLocked(size_t size) {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700469 lock_->AssertHeld();
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700470 DCHECK(alloc_space_ != NULL);
Ian Rogers30fab402012-01-23 15:43:46 -0800471 AllocSpace* space = alloc_space_;
Elliott Hughes92b3b562011-09-08 16:32:26 -0700472 Object* obj = AllocateLocked(space, size);
Carl Shapiro58551df2011-07-24 03:09:51 -0700473 if (obj != NULL) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700474 RecordAllocationLocked(space, obj);
Carl Shapiro58551df2011-07-24 03:09:51 -0700475 }
476 return obj;
477}
478
Ian Rogers30fab402012-01-23 15:43:46 -0800479Object* Heap::AllocateLocked(AllocSpace* space, size_t alloc_size) {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700480 lock_->AssertHeld();
Elliott Hughes92b3b562011-09-08 16:32:26 -0700481
Ian Rogers0399dde2012-06-06 17:09:28 -0700482 // Since allocation can cause a GC which will need to SuspendAll, make sure all allocations are
483 // done in the runnable state where suspension is expected.
484 DCHECK_EQ(Thread::Current()->GetState(), kRunnable);
485 Thread::Current()->AssertThreadSuspensionIsAllowable();
Brian Carlstromb82b6872011-10-26 17:18:07 -0700486
Ian Rogers30fab402012-01-23 15:43:46 -0800487 // Fail impossible allocations
488 if (alloc_size > space->Capacity()) {
489 // On failure collect soft references
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -0700490 WaitForConcurrentGcToComplete();
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700491 CollectGarbageInternal(false, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700492 return NULL;
493 }
494
Ian Rogers30fab402012-01-23 15:43:46 -0800495 Object* ptr = space->AllocWithoutGrowth(alloc_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700496 if (ptr != NULL) {
497 return ptr;
498 }
499
Ian Rogers30fab402012-01-23 15:43:46 -0800500 // The allocation failed. If the GC is running, block until it completes and retry.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700501 if (is_gc_running_) {
Ian Rogers30fab402012-01-23 15:43:46 -0800502 // The GC is concurrently tracing the heap. Release the heap lock, wait for the GC to
503 // complete, and retrying allocating.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700504 WaitForConcurrentGcToComplete();
Ian Rogers30fab402012-01-23 15:43:46 -0800505 ptr = space->AllocWithoutGrowth(alloc_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700506 if (ptr != NULL) {
507 return ptr;
508 }
509 }
510
511 // Another failure. Our thread was starved or there may be too many
512 // live objects. Try a foreground GC. This will have no effect if
513 // the concurrent GC is already running.
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700514 if (Runtime::Current()->HasStatsEnabled()) {
515 ++Runtime::Current()->GetStats()->gc_for_alloc_count;
516 ++Thread::Current()->GetStats()->gc_for_alloc_count;
517 }
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -0700518 // We don't need a WaitForConcurrentGcToComplete here since we checked
519 // is_gc_running_ earlier and we are in a heap lock.
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700520 CollectGarbageInternal(false, false);
Ian Rogers30fab402012-01-23 15:43:46 -0800521 ptr = space->AllocWithoutGrowth(alloc_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700522 if (ptr != NULL) {
523 return ptr;
524 }
525
526 // Even that didn't work; this is an exceptional state.
527 // Try harder, growing the heap if necessary.
Ian Rogers30fab402012-01-23 15:43:46 -0800528 ptr = space->AllocWithGrowth(alloc_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700529 if (ptr != NULL) {
Ian Rogers30fab402012-01-23 15:43:46 -0800530 size_t new_footprint = space->GetFootprintLimit();
Elliott Hughes418dfe72011-10-06 18:56:27 -0700531 // OLD-TODO: may want to grow a little bit more so that the amount of
Carl Shapiro58551df2011-07-24 03:09:51 -0700532 // free space is equal to the old free space + the
533 // utilization slop for the new allocation.
Ian Rogers3bb17a62012-01-27 23:56:44 -0800534 VLOG(gc) << "Grow heap (frag case) to " << PrettySize(new_footprint)
Ian Rogers162a31c2012-01-31 16:14:31 -0800535 << " for a " << PrettySize(alloc_size) << " allocation";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700536 return ptr;
537 }
538
Elliott Hughes81ff3182012-03-23 20:35:56 -0700539 // Most allocations should have succeeded by now, so the heap is really full, really fragmented,
540 // or the requested size is really big. Do another GC, collecting SoftReferences this time. The
541 // VM spec requires that all SoftReferences have been collected and cleared before throwing OOME.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700542
Elliott Hughes418dfe72011-10-06 18:56:27 -0700543 // OLD-TODO: wait for the finalizers from the previous GC to finish
Ian Rogers3bb17a62012-01-27 23:56:44 -0800544 VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size) << " allocation";
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -0700545 // We don't need a WaitForConcurrentGcToComplete here either.
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700546 CollectGarbageInternal(false, true);
Ian Rogers30fab402012-01-23 15:43:46 -0800547 ptr = space->AllocWithGrowth(alloc_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700548 if (ptr != NULL) {
549 return ptr;
550 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700551
Carl Shapiro69759ea2011-07-21 18:13:35 -0700552 return NULL;
553}
554
Elliott Hughesbf86d042011-08-31 17:53:14 -0700555int64_t Heap::GetMaxMemory() {
Ian Rogers30fab402012-01-23 15:43:46 -0800556 return alloc_space_->Capacity();
Elliott Hughesbf86d042011-08-31 17:53:14 -0700557}
558
559int64_t Heap::GetTotalMemory() {
Ian Rogers30fab402012-01-23 15:43:46 -0800560 return alloc_space_->Capacity();
Elliott Hughesbf86d042011-08-31 17:53:14 -0700561}
562
563int64_t Heap::GetFreeMemory() {
Ian Rogers30fab402012-01-23 15:43:46 -0800564 return alloc_space_->Capacity() - num_bytes_allocated_;
Elliott Hughesbf86d042011-08-31 17:53:14 -0700565}
566
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700567class InstanceCounter {
568 public:
569 InstanceCounter(Class* c, bool count_assignable)
570 : class_(c), count_assignable_(count_assignable), count_(0) {
571 }
572
573 size_t GetCount() {
574 return count_;
575 }
576
577 static void Callback(Object* o, void* arg) {
578 reinterpret_cast<InstanceCounter*>(arg)->VisitInstance(o);
579 }
580
581 private:
582 void VisitInstance(Object* o) {
583 Class* instance_class = o->GetClass();
584 if (count_assignable_) {
585 if (instance_class == class_) {
586 ++count_;
587 }
588 } else {
589 if (instance_class != NULL && class_->IsAssignableFrom(instance_class)) {
590 ++count_;
591 }
592 }
593 }
594
595 Class* class_;
596 bool count_assignable_;
597 size_t count_;
598};
599
600int64_t Heap::CountInstances(Class* c, bool count_assignable) {
Elliott Hughesffb465f2012-03-01 18:46:05 -0800601 ScopedHeapLock heap_lock;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700602 InstanceCounter counter(c, count_assignable);
603 live_bitmap_->Walk(InstanceCounter::Callback, &counter);
604 return counter.GetCount();
605}
606
Ian Rogers30fab402012-01-23 15:43:46 -0800607void Heap::CollectGarbage(bool clear_soft_references) {
Elliott Hughesffb465f2012-03-01 18:46:05 -0800608 ScopedHeapLock heap_lock;
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -0700609 // If we just waited for a GC to complete then we do not need to do another
610 // GC unless we clear soft references.
611 if (!WaitForConcurrentGcToComplete() || clear_soft_references) {
612 CollectGarbageInternal(false, clear_soft_references);
613 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700614}
615
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700616void Heap::CollectGarbageInternal(bool concurrent, bool clear_soft_references) {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700617 lock_->AssertHeld();
Carl Shapiro58551df2011-07-24 03:09:51 -0700618
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700619 CHECK(!is_gc_running_);
Mathieu Chartiera6399032012-06-11 18:49:50 -0700620 is_gc_running_ = true;
621
Mathieu Chartier662618f2012-06-06 12:01:47 -0700622 TimingLogger timings("CollectGarbageInternal");
Elliott Hughes24edeb52012-06-18 15:29:46 -0700623 uint64_t t0 = NanoTime(), root_end = 0, dirty_begin = 0, dirty_end = 0;
Mathieu Chartier662618f2012-06-06 12:01:47 -0700624
Elliott Hughes8d768a92011-09-14 16:35:25 -0700625 ThreadList* thread_list = Runtime::Current()->GetThreadList();
626 thread_list->SuspendAll();
Mathieu Chartier662618f2012-06-06 12:01:47 -0700627 timings.AddSplit("SuspendAll");
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700628
629 size_t initial_size = num_bytes_allocated_;
Elliott Hughesadb460d2011-10-05 17:02:34 -0700630 Object* cleared_references = NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700631 {
Mathieu Chartier5301cd22012-05-31 12:11:36 -0700632 MarkSweep mark_sweep(mark_stack_);
Elliott Hughes307f75d2011-10-12 18:04:40 -0700633 timings.AddSplit("ctor");
Carl Shapiro58551df2011-07-24 03:09:51 -0700634
635 mark_sweep.Init();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700636 timings.AddSplit("Init");
Carl Shapiro58551df2011-07-24 03:09:51 -0700637
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700638 if (concurrent) {
639 card_table_->ClearNonImageSpaceCards(this);
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700640 timings.AddSplit("ClearNonImageSpaceCards");
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700641 }
642
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700643 // Clear image space cards and keep track of cards we cleared in the mod-union table.
644 mod_union_table_->ClearCards();
645
Carl Shapiro58551df2011-07-24 03:09:51 -0700646 mark_sweep.MarkRoots();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700647 timings.AddSplit("MarkRoots");
Carl Shapiro58551df2011-07-24 03:09:51 -0700648
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700649 // Roots are marked on the bitmap and the mark_stack is empty.
Ian Rogers5d76c432011-10-31 21:42:49 -0700650 DCHECK(mark_sweep.IsMarkStackEmpty());
Carl Shapiro58551df2011-07-24 03:09:51 -0700651
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700652 if (concurrent) {
Mathieu Chartiera6399032012-06-11 18:49:50 -0700653 // We need to resume before unlocking or else a thread waiting for the
654 // heap lock would re-suspend since we have not yet called ResumeAll.
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700655 thread_list->ResumeAll();
Mathieu Chartiera6399032012-06-11 18:49:50 -0700656 Unlock();
Elliott Hughes24edeb52012-06-18 15:29:46 -0700657 root_end = NanoTime();
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700658 timings.AddSplit("RootEnd");
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700659 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700660
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700661 // Processes the cards we cleared earlier and adds their objects into the mod-union table.
662 mod_union_table_->Update(&mark_sweep);
663 timings.AddSplit("UpdateModUnionBitmap");
664
665 // Scans all objects in the mod-union table.
666 mod_union_table_->MarkReferences(&mark_sweep);
667 timings.AddSplit("ProcessModUnionBitmap");
668
669 // Recursively mark all the non-image bits set in the mark bitmap.
Carl Shapiro58551df2011-07-24 03:09:51 -0700670 mark_sweep.RecursiveMark();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700671 timings.AddSplit("RecursiveMark");
Carl Shapiro58551df2011-07-24 03:09:51 -0700672
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700673 if (concurrent) {
Elliott Hughes24edeb52012-06-18 15:29:46 -0700674 dirty_begin = NanoTime();
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700675 Lock();
676 thread_list->SuspendAll();
Mathieu Chartier662618f2012-06-06 12:01:47 -0700677 timings.AddSplit("ReSuspend");
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700678
679 // Re-mark root set.
680 mark_sweep.ReMarkRoots();
681 timings.AddSplit("ReMarkRoots");
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700682
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700683 // Scan dirty objects, this is only required if we are not doing concurrent GC.
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700684 mark_sweep.RecursiveMarkDirtyObjects();
685 timings.AddSplit("RecursiveMarkDirtyObjects");
686 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700687
Ian Rogers30fab402012-01-23 15:43:46 -0800688 mark_sweep.ProcessReferences(clear_soft_references);
Elliott Hughes307f75d2011-10-12 18:04:40 -0700689 timings.AddSplit("ProcessReferences");
Carl Shapiro58551df2011-07-24 03:09:51 -0700690
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700691 // TODO: swap live and marked bitmaps
692 // Note: Need to be careful about image spaces if we do this since not
693 // everything image space will be marked, resulting in things not being
694 // marked as live anymore.
695
696 // Verify that we only reach marked objects from the image space
697 mark_sweep.VerifyImageRoots();
698 timings.AddSplit("VerifyImageRoots");
Carl Shapiro58551df2011-07-24 03:09:51 -0700699
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700700 if (concurrent) {
701 thread_list->ResumeAll();
702 dirty_end = NanoTime();
703 }
704
Carl Shapiro58551df2011-07-24 03:09:51 -0700705 mark_sweep.Sweep();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700706 timings.AddSplit("Sweep");
Elliott Hughesadb460d2011-10-05 17:02:34 -0700707
708 cleared_references = mark_sweep.GetClearedReferences();
Carl Shapiro58551df2011-07-24 03:09:51 -0700709 }
710
711 GrowForUtilization();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700712 timings.AddSplit("GrowForUtilization");
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700713
714 if (!concurrent) {
715 thread_list->ResumeAll();
716 dirty_end = NanoTime();
717 }
Elliott Hughesadb460d2011-10-05 17:02:34 -0700718
719 EnqueueClearedReferences(&cleared_references);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -0800720 RequestHeapTrim();
Mathieu Chartier662618f2012-06-06 12:01:47 -0700721 timings.AddSplit("Finish");
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700722
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700723 if (VLOG_IS_ON(gc)) {
724 uint64_t t1 = NanoTime();
725
Ian Rogers3bb17a62012-01-27 23:56:44 -0800726 // TODO: somehow make the specific GC implementation (here MarkSweep) responsible for logging.
Mathieu Chartiera6399032012-06-11 18:49:50 -0700727 // Reason: For CMS sometimes initial_size < num_bytes_allocated_ results in overflow (3GB freed message).
Ian Rogers3bb17a62012-01-27 23:56:44 -0800728 size_t bytes_freed = initial_size - num_bytes_allocated_;
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700729 uint64_t duration_ns = t1 - t0;
730 duration_ns -= duration_ns % 1000;
731
732 // If the GC was slow, then print timings in the log.
Mathieu Chartier662618f2012-06-06 12:01:47 -0700733 if (concurrent) {
Elliott Hughes24edeb52012-06-18 15:29:46 -0700734 uint64_t pause_roots_time = (root_end - t0) / 1000 * 1000;
735 uint64_t pause_dirty_time = (dirty_end - dirty_begin) / 1000 * 1000;
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700736 if (pause_roots_time > MsToNs(5) || pause_dirty_time > MsToNs(5)) {
737 LOG(INFO) << "GC freed " << PrettySize(bytes_freed) << ", " << GetPercentFree() << "% free, "
738 << PrettySize(num_bytes_allocated_) << "/" << PrettySize(GetTotalMemory()) << ", "
739 << "paused " << PrettyDuration(pause_roots_time) << "+" << PrettyDuration(pause_dirty_time)
740 << ", total " << PrettyDuration(duration_ns);
741 }
Mathieu Chartier662618f2012-06-06 12:01:47 -0700742 } else {
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700743 if (duration_ns > MsToNs(50)) {
744 uint64_t markSweepTime = (dirty_end - t0) / 1000 * 1000;
745 LOG(INFO) << "GC freed " << PrettySize(bytes_freed) << ", " << GetPercentFree() << "% free, "
746 << PrettySize(num_bytes_allocated_) << "/" << PrettySize(GetTotalMemory()) << ", "
747 << "paused " << PrettyDuration(markSweepTime)
748 << ", total " << PrettyDuration(duration_ns);
749 }
Mathieu Chartier662618f2012-06-06 12:01:47 -0700750 }
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700751 }
Elliott Hughes767a1472011-10-26 18:49:02 -0700752 Dbg::GcDidFinish();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800753 if (VLOG_IS_ON(heap)) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700754 timings.Dump();
755 }
Mathieu Chartiera6399032012-06-11 18:49:50 -0700756
757 is_gc_running_ = false;
758
759 // Wake anyone who may have been waiting for the GC to complete.
760 condition_->Broadcast();
Carl Shapiro69759ea2011-07-21 18:13:35 -0700761}
762
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -0700763bool Heap::WaitForConcurrentGcToComplete() {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700764 lock_->AssertHeld();
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700765
766 // Busy wait for GC to finish
767 if (is_gc_running_) {
Mathieu Chartiera6399032012-06-11 18:49:50 -0700768 uint64_t wait_start = NanoTime();
Mathieu Chartier06f79872012-06-21 13:51:52 -0700769
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700770 do {
Mathieu Chartiera6399032012-06-11 18:49:50 -0700771 ScopedThreadStateChange tsc(Thread::Current(), kVmWait);
Mathieu Chartier06f79872012-06-21 13:51:52 -0700772 ScopedThreadListLockReleaser list_lock_releaser;
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700773 condition_->Wait(*lock_);
774 } while (is_gc_running_);
Mathieu Chartiera6399032012-06-11 18:49:50 -0700775 uint64_t wait_time = NanoTime() - wait_start;
776 if (wait_time > MsToNs(5)) {
777 LOG(INFO) << "WaitForConcurrentGcToComplete blocked for " << PrettyDuration(wait_time);
778 }
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -0700779 DCHECK(!is_gc_running_);
780 return true;
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700781 }
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -0700782 return false;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700783}
784
Elliott Hughesc967f782012-04-16 10:23:15 -0700785void Heap::DumpForSigQuit(std::ostream& os) {
786 os << "Heap: " << GetPercentFree() << "% free, "
787 << PrettySize(num_bytes_allocated_) << "/" << PrettySize(GetTotalMemory())
Elliott Hughesae80b492012-04-24 10:43:17 -0700788 << "; " << num_objects_allocated_ << " objects\n";
Elliott Hughesc967f782012-04-16 10:23:15 -0700789}
790
791size_t Heap::GetPercentFree() {
792 size_t total = GetTotalMemory();
793 return 100 - static_cast<size_t>(100.0f * static_cast<float>(num_bytes_allocated_) / total);
794}
795
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800796void Heap::SetIdealFootprint(size_t max_allowed_footprint) {
Ian Rogers30fab402012-01-23 15:43:46 -0800797 size_t alloc_space_capacity = alloc_space_->Capacity();
798 if (max_allowed_footprint > alloc_space_capacity) {
Ian Rogers3bb17a62012-01-27 23:56:44 -0800799 VLOG(gc) << "Clamp target GC heap from " << PrettySize(max_allowed_footprint)
800 << " to " << PrettySize(alloc_space_capacity);
Ian Rogers30fab402012-01-23 15:43:46 -0800801 max_allowed_footprint = alloc_space_capacity;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -0700802 }
Ian Rogers30fab402012-01-23 15:43:46 -0800803 alloc_space_->SetFootprintLimit(max_allowed_footprint);
Shih-wei Liao8c2f6412011-10-03 22:58:14 -0700804}
805
Ian Rogers3bb17a62012-01-27 23:56:44 -0800806// kHeapIdealFree is the ideal maximum free size, when we grow the heap for utilization.
Shih-wei Liao7f1caab2011-10-06 12:11:04 -0700807static const size_t kHeapIdealFree = 2 * MB;
Ian Rogers3bb17a62012-01-27 23:56:44 -0800808// kHeapMinFree guarantees that you always have at least 512 KB free, when you grow for utilization,
809// regardless of target utilization ratio.
Shih-wei Liao8c2f6412011-10-03 22:58:14 -0700810static const size_t kHeapMinFree = kHeapIdealFree / 4;
811
Carl Shapiro69759ea2011-07-21 18:13:35 -0700812void Heap::GrowForUtilization() {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700813 lock_->AssertHeld();
Shih-wei Liao8c2f6412011-10-03 22:58:14 -0700814
815 // We know what our utilization is at this moment.
816 // This doesn't actually resize any memory. It just lets the heap grow more
817 // when necessary.
Elliott Hughes362f9bc2011-10-17 18:56:41 -0700818 size_t target_size(num_bytes_allocated_ / Heap::GetTargetHeapUtilization());
Shih-wei Liao8c2f6412011-10-03 22:58:14 -0700819
820 if (target_size > num_bytes_allocated_ + kHeapIdealFree) {
821 target_size = num_bytes_allocated_ + kHeapIdealFree;
822 } else if (target_size < num_bytes_allocated_ + kHeapMinFree) {
823 target_size = num_bytes_allocated_ + kHeapMinFree;
824 }
825
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700826 // Calculate when to perform the next ConcurrentGC.
827 if (GetTotalMemory() - num_bytes_allocated_ < concurrent_min_free_) {
828 // Not enough free memory to perform concurrent GC.
829 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
830 } else {
831 concurrent_start_bytes_ = alloc_space_->GetFootprintLimit() - concurrent_start_size_;
832 }
833
Shih-wei Liao8c2f6412011-10-03 22:58:14 -0700834 SetIdealFootprint(target_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700835}
836
jeffhaoc1160702011-10-27 15:48:45 -0700837void Heap::ClearGrowthLimit() {
Elliott Hughesffb465f2012-03-01 18:46:05 -0800838 ScopedHeapLock heap_lock;
jeffhaoc1160702011-10-27 15:48:45 -0700839 WaitForConcurrentGcToComplete();
jeffhaoc1160702011-10-27 15:48:45 -0700840 alloc_space_->ClearGrowthLimit();
841}
842
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -0700843pid_t Heap::GetLockOwner() {
Elliott Hughesaccd83d2011-10-17 14:25:58 -0700844 return lock_->GetOwner();
845}
846
Elliott Hughes92b3b562011-09-08 16:32:26 -0700847void Heap::Lock() {
Elliott Hughes34e06962012-04-09 13:55:55 -0700848 // Grab the lock, but put ourselves into kVmWait if it looks
Brian Carlstromfad71432011-10-16 20:25:10 -0700849 // like we're going to have to wait on the mutex. This prevents
850 // deadlock if another thread is calling CollectGarbageInternal,
851 // since they will have the heap lock and be waiting for mutators to
852 // suspend.
853 if (!lock_->TryLock()) {
Elliott Hughes34e06962012-04-09 13:55:55 -0700854 ScopedThreadStateChange tsc(Thread::Current(), kVmWait);
Brian Carlstromfad71432011-10-16 20:25:10 -0700855 lock_->Lock();
856 }
Elliott Hughes92b3b562011-09-08 16:32:26 -0700857}
858
859void Heap::Unlock() {
860 lock_->Unlock();
861}
862
Elliott Hughesadb460d2011-10-05 17:02:34 -0700863void Heap::SetReferenceOffsets(MemberOffset reference_referent_offset,
864 MemberOffset reference_queue_offset,
865 MemberOffset reference_queueNext_offset,
866 MemberOffset reference_pendingNext_offset,
867 MemberOffset finalizer_reference_zombie_offset) {
868 reference_referent_offset_ = reference_referent_offset;
869 reference_queue_offset_ = reference_queue_offset;
870 reference_queueNext_offset_ = reference_queueNext_offset;
871 reference_pendingNext_offset_ = reference_pendingNext_offset;
872 finalizer_reference_zombie_offset_ = finalizer_reference_zombie_offset;
873 CHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
874 CHECK_NE(reference_queue_offset_.Uint32Value(), 0U);
875 CHECK_NE(reference_queueNext_offset_.Uint32Value(), 0U);
876 CHECK_NE(reference_pendingNext_offset_.Uint32Value(), 0U);
877 CHECK_NE(finalizer_reference_zombie_offset_.Uint32Value(), 0U);
878}
879
880Object* Heap::GetReferenceReferent(Object* reference) {
881 DCHECK(reference != NULL);
882 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
883 return reference->GetFieldObject<Object*>(reference_referent_offset_, true);
884}
885
886void Heap::ClearReferenceReferent(Object* reference) {
887 DCHECK(reference != NULL);
888 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
889 reference->SetFieldObject(reference_referent_offset_, NULL, true);
890}
891
892// Returns true if the reference object has not yet been enqueued.
893bool Heap::IsEnqueuable(const Object* ref) {
894 DCHECK(ref != NULL);
895 const Object* queue = ref->GetFieldObject<Object*>(reference_queue_offset_, false);
896 const Object* queue_next = ref->GetFieldObject<Object*>(reference_queueNext_offset_, false);
897 return (queue != NULL) && (queue_next == NULL);
898}
899
900void Heap::EnqueueReference(Object* ref, Object** cleared_reference_list) {
901 DCHECK(ref != NULL);
902 CHECK(ref->GetFieldObject<Object*>(reference_queue_offset_, false) != NULL);
903 CHECK(ref->GetFieldObject<Object*>(reference_queueNext_offset_, false) == NULL);
904 EnqueuePendingReference(ref, cleared_reference_list);
905}
906
907void Heap::EnqueuePendingReference(Object* ref, Object** list) {
908 DCHECK(ref != NULL);
909 DCHECK(list != NULL);
910
911 if (*list == NULL) {
912 ref->SetFieldObject(reference_pendingNext_offset_, ref, false);
913 *list = ref;
914 } else {
915 Object* head = (*list)->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
916 ref->SetFieldObject(reference_pendingNext_offset_, head, false);
917 (*list)->SetFieldObject(reference_pendingNext_offset_, ref, false);
918 }
919}
920
921Object* Heap::DequeuePendingReference(Object** list) {
922 DCHECK(list != NULL);
923 DCHECK(*list != NULL);
924 Object* head = (*list)->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
925 Object* ref;
926 if (*list == head) {
927 ref = *list;
928 *list = NULL;
929 } else {
930 Object* next = head->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
931 (*list)->SetFieldObject(reference_pendingNext_offset_, next, false);
932 ref = head;
933 }
934 ref->SetFieldObject(reference_pendingNext_offset_, NULL, false);
935 return ref;
936}
937
Ian Rogers5d4bdc22011-11-02 22:15:43 -0700938void Heap::AddFinalizerReference(Thread* self, Object* object) {
Ian Rogers365c1022012-06-22 15:05:28 -0700939 ScopedJniThreadState ts(self);
Elliott Hughes77405792012-03-15 15:22:12 -0700940 JValue args[1];
Elliott Hughesf24d3ce2012-04-11 17:43:37 -0700941 args[0].SetL(object);
Ian Rogers365c1022012-06-22 15:05:28 -0700942 ts.DecodeMethod(WellKnownClasses::java_lang_ref_FinalizerReference_add)->Invoke(self, NULL, args, NULL);
Elliott Hughesadb460d2011-10-05 17:02:34 -0700943}
944
945void Heap::EnqueueClearedReferences(Object** cleared) {
946 DCHECK(cleared != NULL);
947 if (*cleared != NULL) {
Ian Rogers365c1022012-06-22 15:05:28 -0700948 ScopedJniThreadState ts(Thread::Current());
Elliott Hughes77405792012-03-15 15:22:12 -0700949 JValue args[1];
Elliott Hughesf24d3ce2012-04-11 17:43:37 -0700950 args[0].SetL(*cleared);
Ian Rogers365c1022012-06-22 15:05:28 -0700951 ts.DecodeMethod(WellKnownClasses::java_lang_ref_ReferenceQueue_add)->Invoke(ts.Self(), NULL, args, NULL);
Elliott Hughesadb460d2011-10-05 17:02:34 -0700952 *cleared = NULL;
953 }
954}
955
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700956void Heap::RequestConcurrentGC() {
Mathieu Chartier069387a2012-06-18 12:01:01 -0700957 // Make sure that we can do a concurrent GC.
958 if (requesting_gc_ ||
959 !Runtime::Current()->IsFinishedStarting() ||
960 Runtime::Current()->IsShuttingDown() ||
961 !Runtime::Current()->IsConcurrentGcEnabled()) {
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700962 return;
963 }
964
965 requesting_gc_ = true;
966 JNIEnv* env = Thread::Current()->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -0700967 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
968 DCHECK(WellKnownClasses::java_lang_Daemons_requestGC != NULL);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700969 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons, WellKnownClasses::java_lang_Daemons_requestGC);
970 CHECK(!env->ExceptionCheck());
971 requesting_gc_ = false;
972}
973
974void Heap::ConcurrentGC() {
Mathieu Chartier2542d662012-06-21 17:14:11 -0700975 if (Runtime::Current()->IsShuttingDown()) {
976 return;
977 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700978 ScopedHeapLock heap_lock;
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -0700979 // We shouldn't need a WaitForConcurrentGcToComplete here since only
980 // concurrent GC resumes threads before the GC is completed and this function
981 // is only called within the GC daemon thread.
982 CHECK(!is_gc_running_);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700983 // Current thread needs to be runnable or else we can't suspend all threads.
984 ScopedThreadStateChange tsc(Thread::Current(), kRunnable);
985 CollectGarbageInternal(true, false);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700986}
987
988void Heap::Trim() {
Mathieu Chartier5dbf8292012-06-11 13:51:41 -0700989 lock_->AssertHeld();
Mathieu Chartiera6399032012-06-11 18:49:50 -0700990 WaitForConcurrentGcToComplete();
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700991 GetAllocSpace()->Trim();
992}
993
Elliott Hughes8cf5bc02012-02-02 16:32:16 -0800994void Heap::RequestHeapTrim() {
995 // We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
996 // because that only marks object heads, so a large array looks like lots of empty space. We
997 // don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
998 // to utilization (which is probably inversely proportional to how much benefit we can expect).
999 // We could try mincore(2) but that's only a measure of how many pages we haven't given away,
1000 // not how much use we're making of those pages.
1001 float utilization = static_cast<float>(num_bytes_allocated_) / alloc_space_->Size();
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001002 uint64_t ms_time = NsToMs(NanoTime());
1003 if (utilization > 0.75f || ms_time - last_trim_time_ < 2 * 1000) {
1004 // Don't bother trimming the heap if it's more than 75% utilized, or if a
1005 // heap trim occurred in the last two seconds.
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001006 return;
1007 }
Mathieu Chartiera6399032012-06-11 18:49:50 -07001008 if (!Runtime::Current()->IsFinishedStarting() || Runtime::Current()->IsShuttingDown()) {
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001009 // Heap trimming isn't supported without a Java runtime or Daemons (such as at dex2oat time)
Mathieu Chartiera6399032012-06-11 18:49:50 -07001010 // Also: we do not wish to start a heap trim if the runtime is shutting down.
Ian Rogerse1d490c2012-02-03 09:09:07 -08001011 return;
1012 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001013 last_trim_time_ = ms_time;
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001014 JNIEnv* env = Thread::Current()->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07001015 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
1016 DCHECK(WellKnownClasses::java_lang_Daemons_requestHeapTrim != NULL);
Elliott Hugheseac76672012-05-24 21:56:51 -07001017 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons, WellKnownClasses::java_lang_Daemons_requestHeapTrim);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001018 CHECK(!env->ExceptionCheck());
1019}
1020
Carl Shapiro69759ea2011-07-21 18:13:35 -07001021} // namespace art