blob: 658755e2937b151808d8c46a7709932fdda7c83c [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"
Mathieu Chartiercc236d72012-07-20 10:29:05 -070027#include "heap_bitmap.h"
Brian Carlstrom9cff8e12011-08-18 16:47:29 -070028#include "image.h"
Carl Shapiro58551df2011-07-24 03:09:51 -070029#include "mark_sweep.h"
Mathieu Chartierb43b7d42012-06-19 13:15:09 -070030#include "mod_union_table.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070031#include "object.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080032#include "object_utils.h"
Brian Carlstrom5643b782012-02-05 12:32:53 -080033#include "os.h"
Mathieu Chartier7664f5c2012-06-08 18:15:32 -070034#include "ScopedLocalRef.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070035#include "scoped_thread_state_change.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070036#include "space.h"
Carl Shapiro58551df2011-07-24 03:09:51 -070037#include "stl_util.h"
Elliott Hughes8d768a92011-09-14 16:35:25 -070038#include "thread_list.h"
Elliott Hughes767a1472011-10-26 18:49:02 -070039#include "timing_logger.h"
40#include "UniquePtr.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070041#include "well_known_classes.h"
Carl Shapiro69759ea2011-07-21 18:13:35 -070042
43namespace art {
44
Ian Rogers30fab402012-01-23 15:43:46 -080045static void UpdateFirstAndLastSpace(Space** first_space, Space** last_space, Space* space) {
46 if (*first_space == NULL) {
47 *first_space = space;
48 *last_space = space;
49 } else {
50 if ((*first_space)->Begin() > space->Begin()) {
51 *first_space = space;
52 } else if (space->Begin() > (*last_space)->Begin()) {
53 *last_space = space;
54 }
55 }
56}
57
Elliott Hughesae80b492012-04-24 10:43:17 -070058static bool GenerateImage(const std::string& image_file_name) {
Brian Carlstroma004aa92012-02-08 18:05:09 -080059 const std::string boot_class_path_string(Runtime::Current()->GetBootClassPathString());
Brian Carlstrom5643b782012-02-05 12:32:53 -080060 std::vector<std::string> boot_class_path;
61 Split(boot_class_path_string, ':', boot_class_path);
Brian Carlstromb2793372012-03-17 18:27:16 -070062 if (boot_class_path.empty()) {
63 LOG(FATAL) << "Failed to generate image because no boot class path specified";
64 }
Brian Carlstrom5643b782012-02-05 12:32:53 -080065
66 std::vector<char*> arg_vector;
67
68 std::string dex2oat_string(GetAndroidRoot());
Elliott Hughes67d92002012-03-26 15:08:51 -070069 dex2oat_string += (kIsDebugBuild ? "/bin/dex2oatd" : "/bin/dex2oat");
Brian Carlstrom5643b782012-02-05 12:32:53 -080070 const char* dex2oat = dex2oat_string.c_str();
71 arg_vector.push_back(strdup(dex2oat));
72
73 std::string image_option_string("--image=");
74 image_option_string += image_file_name;
75 const char* image_option = image_option_string.c_str();
76 arg_vector.push_back(strdup(image_option));
77
78 arg_vector.push_back(strdup("--runtime-arg"));
79 arg_vector.push_back(strdup("-Xms64m"));
80
81 arg_vector.push_back(strdup("--runtime-arg"));
82 arg_vector.push_back(strdup("-Xmx64m"));
83
84 for (size_t i = 0; i < boot_class_path.size(); i++) {
85 std::string dex_file_option_string("--dex-file=");
86 dex_file_option_string += boot_class_path[i];
87 const char* dex_file_option = dex_file_option_string.c_str();
88 arg_vector.push_back(strdup(dex_file_option));
89 }
90
91 std::string oat_file_option_string("--oat-file=");
92 oat_file_option_string += image_file_name;
93 oat_file_option_string.erase(oat_file_option_string.size() - 3);
94 oat_file_option_string += "oat";
95 const char* oat_file_option = oat_file_option_string.c_str();
96 arg_vector.push_back(strdup(oat_file_option));
97
98 arg_vector.push_back(strdup("--base=0x60000000"));
99
Elliott Hughes48436bb2012-02-07 15:23:28 -0800100 std::string command_line(Join(arg_vector, ' '));
Brian Carlstrom5643b782012-02-05 12:32:53 -0800101 LOG(INFO) << command_line;
102
Elliott Hughes48436bb2012-02-07 15:23:28 -0800103 arg_vector.push_back(NULL);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800104 char** argv = &arg_vector[0];
105
106 // fork and exec dex2oat
107 pid_t pid = fork();
108 if (pid == 0) {
109 // no allocation allowed between fork and exec
110
111 // change process groups, so we don't get reaped by ProcessManager
112 setpgid(0, 0);
113
114 execv(dex2oat, argv);
115
116 PLOG(FATAL) << "execv(" << dex2oat << ") failed";
117 return false;
118 } else {
119 STLDeleteElements(&arg_vector);
120
121 // wait for dex2oat to finish
122 int status;
123 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
124 if (got_pid != pid) {
125 PLOG(ERROR) << "waitpid failed: wanted " << pid << ", got " << got_pid;
126 return false;
127 }
128 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
129 LOG(ERROR) << dex2oat << " failed: " << command_line;
130 return false;
131 }
132 }
133 return true;
134}
135
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800136Heap::Heap(size_t initial_size, size_t growth_limit, size_t capacity,
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700137 const std::string& original_image_file_name, bool concurrent_gc)
138 : alloc_space_(NULL),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800139 card_table_(NULL),
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700140 concurrent_gc_(concurrent_gc),
141 have_zygote_space_(false),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800142 card_marking_disabled_(false),
143 is_gc_running_(false),
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700144 concurrent_start_bytes_(std::numeric_limits<size_t>::max()),
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700145 concurrent_start_size_(128 * KB),
146 concurrent_min_free_(256 * KB),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800147 num_bytes_allocated_(0),
148 num_objects_allocated_(0),
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700149 last_trim_time_(0),
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700150 try_running_gc_(false),
151 requesting_gc_(false),
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
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700168 live_bitmap_.reset(new HeapBitmap(this));
169 mark_bitmap_.reset(new HeapBitmap(this));
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700170
Ian Rogers30fab402012-01-23 15:43:46 -0800171 // Requested begin for the alloc space, to follow the mapped image and oat files
172 byte* requested_begin = NULL;
Brian Carlstrom5643b782012-02-05 12:32:53 -0800173 std::string image_file_name(original_image_file_name);
174 if (!image_file_name.empty()) {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700175 Space* image_space = NULL;
176
Brian Carlstrom5643b782012-02-05 12:32:53 -0800177 if (OS::FileExists(image_file_name.c_str())) {
178 // If the /system file exists, it should be up-to-date, don't try to generate
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700179 image_space = Space::CreateImageSpace(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800180 } else {
181 // If the /system file didn't exist, we need to use one from the art-cache.
182 // If the cache file exists, try to open, but if it fails, regenerate.
183 // If it does not exist, generate.
184 image_file_name = GetArtCacheFilenameOrDie(image_file_name);
185 if (OS::FileExists(image_file_name.c_str())) {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700186 image_space = Space::CreateImageSpace(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800187 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700188 if (image_space == NULL) {
Brian Carlstrom5643b782012-02-05 12:32:53 -0800189 if (!GenerateImage(image_file_name)) {
190 LOG(FATAL) << "Failed to generate image: " << image_file_name;
191 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700192 image_space = Space::CreateImageSpace(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800193 }
194 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700195 if (image_space == NULL) {
Brian Carlstrom223f20f2012-02-04 23:06:55 -0800196 LOG(FATAL) << "Failed to create space from " << image_file_name;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700197 }
Brian Carlstrom5643b782012-02-05 12:32:53 -0800198
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700199 AddSpace(image_space);
200 UpdateFirstAndLastSpace(&first_space, &last_space, image_space);
Ian Rogers30fab402012-01-23 15:43:46 -0800201 // Oat files referenced by image files immediately follow them in memory, ensure alloc space
202 // isn't going to get in the middle
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700203 byte* oat_end_addr = GetImageSpace()->GetImageHeader().GetOatEnd();
204 CHECK(oat_end_addr > GetImageSpace()->End());
Ian Rogers30fab402012-01-23 15:43:46 -0800205 if (oat_end_addr > requested_begin) {
206 requested_begin = reinterpret_cast<byte*>(RoundUp(reinterpret_cast<uintptr_t>(oat_end_addr),
207 kPageSize));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700208 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700209 }
210
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700211 UniquePtr<AllocSpace> alloc_space(Space::CreateAllocSpace(
212 "alloc space", initial_size, growth_limit, capacity, requested_begin));
213 alloc_space_ = alloc_space.release();
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700214 CHECK(alloc_space_ != NULL) << "Failed to create alloc space";
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700215 AddSpace(alloc_space_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700216
Ian Rogers30fab402012-01-23 15:43:46 -0800217 UpdateFirstAndLastSpace(&first_space, &last_space, alloc_space_);
218 byte* heap_begin = first_space->Begin();
Ian Rogers3bb17a62012-01-27 23:56:44 -0800219 size_t heap_capacity = (last_space->Begin() - first_space->Begin()) + last_space->NonGrowthLimitCapacity();
Carl Shapiro69759ea2011-07-21 18:13:35 -0700220
Ian Rogers30fab402012-01-23 15:43:46 -0800221 // Mark image objects in the live bitmap
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800222 for (size_t i = 0; i < spaces_.size(); ++i) {
Ian Rogers30fab402012-01-23 15:43:46 -0800223 Space* space = spaces_[i];
224 if (space->IsImageSpace()) {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700225 space->AsImageSpace()->RecordImageAllocations(space->GetLiveBitmap());
Ian Rogers30fab402012-01-23 15:43:46 -0800226 }
227 }
228
Elliott Hughes6c9c06d2011-11-07 16:43:47 -0800229 // Allocate the card table.
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700230 card_table_.reset(CardTable::Create(heap_begin, heap_capacity));
231 CHECK(card_table_.get() != NULL) << "Failed to create card table";
Ian Rogers5d76c432011-10-31 21:42:49 -0700232
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700233 mod_union_table_.reset(new ModUnionTableToZygoteAllocspace<ModUnionTableReferenceCache>(this));
234 CHECK(mod_union_table_.get() != NULL) << "Failed to create mod-union table";
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700235
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700236 zygote_mod_union_table_.reset(new ModUnionTableCardCache(this));
237 CHECK(zygote_mod_union_table_.get() != NULL) << "Failed to create Zygote mod-union table";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700238
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700239 num_bytes_allocated_ = 0;
240 num_objects_allocated_ = 0;
241
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700242 mark_stack_.reset(MarkStack::Create());
Mathieu Chartier5301cd22012-05-31 12:11:36 -0700243
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800244 // It's still too early to take a lock because there are no threads yet,
Elliott Hughes92b3b562011-09-08 16:32:26 -0700245 // but we can create the heap lock now. We don't create it earlier to
246 // make it clear that you can't use locks during heap initialization.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700247 statistics_lock_ = new Mutex("statistics lock");
248 gc_complete_lock_ = new Mutex("GC complete lock");
249 gc_complete_cond_.reset(new ConditionVariable("GC complete condition variable"));
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700250
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800251 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800252 LOG(INFO) << "Heap() exiting";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700253 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700254}
255
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700256// Sort spaces based on begin address
257class SpaceSorter {
258 public:
259 bool operator () (const Space* a, const Space* b) const {
260 return a->Begin() < b->Begin();
261 }
262};
263
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800264void Heap::AddSpace(Space* space) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700265 WriterMutexLock mu(*GlobalSynchronization::heap_bitmap_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700266 DCHECK(space != NULL);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700267 DCHECK(space->GetLiveBitmap() != NULL);
268 live_bitmap_->AddSpaceBitmap(space->GetLiveBitmap());
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700269 DCHECK(space->GetMarkBitmap() != NULL);
270 mark_bitmap_->AddSpaceBitmap(space->GetMarkBitmap());
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800271 spaces_.push_back(space);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700272 // Ensure that spaces remain sorted in increasing order of start address (required for CMS finger)
273 std::sort(spaces_.begin(), spaces_.end(), SpaceSorter());
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800274}
275
276Heap::~Heap() {
277 VLOG(heap) << "~Heap()";
Elliott Hughesb3e66df2012-01-12 14:49:18 -0800278 // We can't take the heap lock here because there might be a daemon thread suspended with the
279 // heap lock held. We know though that no non-daemon threads are executing, and we know that
280 // all daemon threads are suspended, and we also know that the threads list have been deleted, so
281 // 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 -0700282 STLDeleteElements(&spaces_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700283 delete statistics_lock_;
284 delete gc_complete_lock_;
285
Carl Shapiro69759ea2011-07-21 18:13:35 -0700286}
287
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700288Space* Heap::FindSpaceFromObject(const Object* obj) const {
289 // TODO: C++0x auto
290 for (Spaces::const_iterator cur = spaces_.begin(); cur != spaces_.end(); ++cur) {
291 if ((*cur)->Contains(obj)) {
292 return *cur;
293 }
294 }
295 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
296 return NULL;
297}
298
299ImageSpace* Heap::GetImageSpace() {
300 // TODO: C++0x auto
301 for (Spaces::const_iterator cur = spaces_.begin(); cur != spaces_.end(); ++cur) {
302 if ((*cur)->IsImageSpace()) {
303 return (*cur)->AsImageSpace();
304 }
305 }
306 return NULL;
307}
308
309AllocSpace* Heap::GetAllocSpace() {
310 return alloc_space_;
311}
312
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700313static void MSpaceChunkCallback(void* start, void* end, size_t used_bytes, void* arg) {
314 size_t& max_contiguous_allocation = *reinterpret_cast<size_t*>(arg);
315
316 size_t chunk_size = static_cast<size_t>(reinterpret_cast<uint8_t*>(end) - reinterpret_cast<uint8_t*>(start));
317 size_t chunk_free_bytes = 0;
318 if (used_bytes < chunk_size) {
319 chunk_free_bytes = chunk_size - used_bytes;
320 }
321
322 if (chunk_free_bytes > max_contiguous_allocation) {
323 max_contiguous_allocation = chunk_free_bytes;
324 }
325}
326
327Object* Heap::AllocObject(Class* c, size_t byte_count) {
328 // Used in the detail message if we throw an OOME.
329 int64_t total_bytes_free;
330 size_t max_contiguous_allocation;
331
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700332 DCHECK(c == NULL || (c->IsClassClass() && byte_count >= sizeof(Class)) ||
333 (c->IsVariableSize() || c->GetObjectSize() == byte_count) ||
334 strlen(ClassHelper(c).GetDescriptor()) == 0);
335 DCHECK_GE(byte_count, sizeof(Object));
336 Object* obj = Allocate(byte_count);
337 if (obj != NULL) {
338 obj->SetClass(c);
339 if (Dbg::IsAllocTrackingEnabled()) {
340 Dbg::RecordAllocation(c, byte_count);
Elliott Hughes418dfe72011-10-06 18:56:27 -0700341 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700342 bool request_concurrent_gc;
343 {
344 MutexLock mu(*statistics_lock_);
345 request_concurrent_gc = num_bytes_allocated_ >= concurrent_start_bytes_;
346 }
347 if (request_concurrent_gc) {
348 // The SirtRef is necessary since the calls in RequestConcurrentGC are a safepoint.
349 SirtRef<Object> ref(obj);
350 RequestConcurrentGC();
351 }
352 VerifyObject(obj);
353
354 // Additional verification to ensure that we did not allocate into a zygote space.
355 DCHECK(!have_zygote_space_ || !FindSpaceFromObject(obj)->IsZygoteSpace());
356
357 return obj;
358 }
359 total_bytes_free = GetFreeMemory();
360 max_contiguous_allocation = 0;
361 // TODO: C++0x auto
362 for (Spaces::const_iterator cur = spaces_.begin(); cur != spaces_.end(); ++cur) {
363 if ((*cur)->IsAllocSpace()) {
364 (*cur)->AsAllocSpace()->Walk(MSpaceChunkCallback, &max_contiguous_allocation);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700365 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700366 }
Elliott Hughes418dfe72011-10-06 18:56:27 -0700367
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700368 std::string msg(StringPrintf("Failed to allocate a %zd-byte %s (%lld total bytes free; largest possible contiguous allocation %zd bytes)",
369 byte_count,
370 PrettyDescriptor(c).c_str(),
371 total_bytes_free, max_contiguous_allocation));
372 Thread::Current()->ThrowOutOfMemoryError(msg.c_str());
Elliott Hughes418dfe72011-10-06 18:56:27 -0700373 return NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700374}
375
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700376bool Heap::IsHeapAddress(const Object* obj) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700377 // Note: we deliberately don't take the lock here, and mustn't test anything that would
378 // require taking the lock.
Elliott Hughes88c5c352012-03-15 18:49:48 -0700379 if (obj == NULL) {
380 return true;
381 }
382 if (!IsAligned<kObjectAlignment>(obj)) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700383 return false;
384 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800385 for (size_t i = 0; i < spaces_.size(); ++i) {
Ian Rogers30fab402012-01-23 15:43:46 -0800386 if (spaces_[i]->Contains(obj)) {
387 return true;
388 }
389 }
390 return false;
Elliott Hughesa2501992011-08-26 19:39:54 -0700391}
392
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700393bool Heap::IsLiveObjectLocked(const Object* obj) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700394 GlobalSynchronization::heap_bitmap_lock_->AssertReaderHeld();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700395 return IsHeapAddress(obj) && GetLiveBitmap()->Test(obj);
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700396}
397
Elliott Hughes3e465b12011-09-02 18:26:12 -0700398#if VERIFY_OBJECT_ENABLED
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700399void Heap::VerifyObject(const Object* obj) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700400 if (obj == NULL || this == NULL || !verify_objects_ || Runtime::Current()->IsShuttingDown() ||
Ian Rogers141d6222012-04-05 12:23:06 -0700401 Thread::Current() == NULL ||
jeffhao25045522012-03-13 19:34:37 -0700402 Runtime::Current()->GetThreadList()->GetLockOwner() == Thread::Current()->GetTid()) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700403 return;
404 }
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700405 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700406 ReaderMutexLock mu(GlobalSynchronization::heap_bitmap_lock_);
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700407 Heap::VerifyObjectLocked(obj);
408 }
Elliott Hughes92b3b562011-09-08 16:32:26 -0700409}
410#endif
411
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700412void Heap::DumpSpaces() {
413 // TODO: C++0x auto
414 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
415 LOG(INFO) << **it;
416 }
417}
418
Elliott Hughes92b3b562011-09-08 16:32:26 -0700419void Heap::VerifyObjectLocked(const Object* obj) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700420 GlobalSynchronization::heap_bitmap_lock_->AssertReaderHeld();
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700421 if (!IsAligned<kObjectAlignment>(obj)) {
422 LOG(FATAL) << "Object isn't aligned: " << obj;
423 } else if (!GetLiveBitmap()->Test(obj)) {
424 Space* space = FindSpaceFromObject(obj);
425 if (space == NULL) {
426 DumpSpaces();
427 LOG(FATAL) << "Object " << obj << " is not contained in any space";
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700428 }
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700429 LOG(FATAL) << "Object is dead: " << obj << " in space " << *space;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700430 }
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700431#if !VERIFY_OBJECT_FAST
432 // Ignore early dawn of the universe verifications
433 if (num_objects_allocated_ > 10) {
434 const byte* raw_addr = reinterpret_cast<const byte*>(obj) +
435 Object::ClassOffset().Int32Value();
436 const Class* c = *reinterpret_cast<Class* const *>(raw_addr);
437 if (c == NULL) {
438 LOG(FATAL) << "Null class in object: " << obj;
439 } else if (!IsAligned<kObjectAlignment>(c)) {
440 LOG(FATAL) << "Class isn't aligned: " << c << " in object: " << obj;
441 } else if (!GetLiveBitmap()->Test(c)) {
442 LOG(FATAL) << "Class of object is dead: " << c << " in object: " << obj;
443 }
444 // Check obj.getClass().getClass() == obj.getClass().getClass().getClass()
445 // Note: we don't use the accessors here as they have internal sanity checks
446 // that we don't want to run
447 raw_addr = reinterpret_cast<const byte*>(c) + Object::ClassOffset().Int32Value();
448 const Class* c_c = *reinterpret_cast<Class* const *>(raw_addr);
449 raw_addr = reinterpret_cast<const byte*>(c_c) + Object::ClassOffset().Int32Value();
450 const Class* c_c_c = *reinterpret_cast<Class* const *>(raw_addr);
451 CHECK_EQ(c_c, c_c_c);
452 }
453#endif
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700454}
455
Brian Carlstrom78128a62011-09-15 17:21:19 -0700456void Heap::VerificationCallback(Object* obj, void* arg) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700457 DCHECK(obj != NULL);
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800458 reinterpret_cast<Heap*>(arg)->VerifyObjectLocked(obj);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700459}
460
461void Heap::VerifyHeap() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700462 ReaderMutexLock mu(*GlobalSynchronization::heap_bitmap_lock_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700463 GetLiveBitmap()->Walk(Heap::VerificationCallback, this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700464}
465
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700466void Heap::RecordAllocation(AllocSpace* space, const Object* obj) {
467 {
468 MutexLock mu(*statistics_lock_);
469 size_t size = space->AllocationSize(obj);
470 DCHECK_GT(size, 0u);
471 num_bytes_allocated_ += size;
472 num_objects_allocated_ += 1;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700473
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700474 if (Runtime::Current()->HasStatsEnabled()) {
475 RuntimeStats* global_stats = Runtime::Current()->GetStats();
476 RuntimeStats* thread_stats = Thread::Current()->GetStats();
477 ++global_stats->allocated_objects;
478 ++thread_stats->allocated_objects;
479 global_stats->allocated_bytes += size;
480 thread_stats->allocated_bytes += size;
481 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700482 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700483 {
484 WriterMutexLock mu(*GlobalSynchronization::heap_bitmap_lock_);
485 live_bitmap_->Set(obj);
486 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700487}
488
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700489void Heap::RecordFree(size_t freed_objects, size_t freed_bytes) {
490 MutexLock mu(*statistics_lock_);
Elliott Hughes307f75d2011-10-12 18:04:40 -0700491
492 if (freed_objects < num_objects_allocated_) {
493 num_objects_allocated_ -= freed_objects;
494 } else {
495 num_objects_allocated_ = 0;
496 }
497 if (freed_bytes < num_bytes_allocated_) {
498 num_bytes_allocated_ -= freed_bytes;
Carl Shapiro58551df2011-07-24 03:09:51 -0700499 } else {
500 num_bytes_allocated_ = 0;
501 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700502
503 if (Runtime::Current()->HasStatsEnabled()) {
504 RuntimeStats* global_stats = Runtime::Current()->GetStats();
505 RuntimeStats* thread_stats = Thread::Current()->GetStats();
506 ++global_stats->freed_objects;
507 ++thread_stats->freed_objects;
Elliott Hughes307f75d2011-10-12 18:04:40 -0700508 global_stats->freed_bytes += freed_bytes;
509 thread_stats->freed_bytes += freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700510 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700511}
512
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700513Object* Heap::Allocate(size_t size) {
514 Object* obj = Allocate(alloc_space_, size);
Carl Shapiro58551df2011-07-24 03:09:51 -0700515 if (obj != NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700516 RecordAllocation(alloc_space_, obj);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700517 return obj;
Carl Shapiro58551df2011-07-24 03:09:51 -0700518 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700519
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700520 return NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700521}
522
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700523Object* Heap::Allocate(AllocSpace* space, size_t alloc_size) {
524 Thread* self = Thread::Current();
Ian Rogers0399dde2012-06-06 17:09:28 -0700525 // Since allocation can cause a GC which will need to SuspendAll, make sure all allocations are
526 // done in the runnable state where suspension is expected.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700527#ifndef NDEBUG
528 {
529 MutexLock mu(*GlobalSynchronization::thread_suspend_count_lock_);
530 CHECK_EQ(self->GetState(), kRunnable);
531 }
532 self->AssertThreadSuspensionIsAllowable();
533#endif
Brian Carlstromb82b6872011-10-26 17:18:07 -0700534
Ian Rogers30fab402012-01-23 15:43:46 -0800535 // Fail impossible allocations
536 if (alloc_size > space->Capacity()) {
537 // On failure collect soft references
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -0700538 WaitForConcurrentGcToComplete();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700539 if (Runtime::Current()->HasStatsEnabled()) {
540 ++Runtime::Current()->GetStats()->gc_for_alloc_count;
541 ++Thread::Current()->GetStats()->gc_for_alloc_count;
542 }
543 self->TransitionFromRunnableToSuspended(kWaitingPerformingGc);
544 CollectGarbageInternal(false, true);
545 self->TransitionFromSuspendedToRunnable();
Carl Shapiro69759ea2011-07-21 18:13:35 -0700546 return NULL;
547 }
548
Ian Rogers30fab402012-01-23 15:43:46 -0800549 Object* ptr = space->AllocWithoutGrowth(alloc_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700550 if (ptr != NULL) {
551 return ptr;
552 }
553
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700554 // The allocation failed. If the GC is running, block until it completes else request a
555 // foreground partial collection.
556 if (!WaitForConcurrentGcToComplete()) {
557 // No concurrent GC so perform a foreground collection.
558 if (Runtime::Current()->HasStatsEnabled()) {
559 ++Runtime::Current()->GetStats()->gc_for_alloc_count;
560 ++Thread::Current()->GetStats()->gc_for_alloc_count;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700561 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700562 self->TransitionFromRunnableToSuspended(kWaitingPerformingGc);
563 CollectGarbageInternal(have_zygote_space_, false);
564 self->TransitionFromSuspendedToRunnable();
Carl Shapiro69759ea2011-07-21 18:13:35 -0700565 }
566
Ian Rogers30fab402012-01-23 15:43:46 -0800567 ptr = space->AllocWithoutGrowth(alloc_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700568 if (ptr != NULL) {
569 return ptr;
570 }
571
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700572 if (!have_zygote_space_) {
573 // Partial GC didn't free enough memory, try a full GC.
574 if (Runtime::Current()->HasStatsEnabled()) {
575 ++Runtime::Current()->GetStats()->gc_for_alloc_count;
576 ++Thread::Current()->GetStats()->gc_for_alloc_count;
577 }
578 self->TransitionFromRunnableToSuspended(kWaitingPerformingGc);
579 CollectGarbageInternal(false, false);
580 self->TransitionFromSuspendedToRunnable();
581 ptr = space->AllocWithoutGrowth(alloc_size);
582 if (ptr != NULL) {
583 return ptr;
584 }
585 }
586
587 // Allocations have failed after GCs; this is an exceptional state.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700588 // Try harder, growing the heap if necessary.
Ian Rogers30fab402012-01-23 15:43:46 -0800589 ptr = space->AllocWithGrowth(alloc_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700590 if (ptr != NULL) {
Ian Rogers30fab402012-01-23 15:43:46 -0800591 size_t new_footprint = space->GetFootprintLimit();
Elliott Hughes418dfe72011-10-06 18:56:27 -0700592 // OLD-TODO: may want to grow a little bit more so that the amount of
Carl Shapiro58551df2011-07-24 03:09:51 -0700593 // free space is equal to the old free space + the
594 // utilization slop for the new allocation.
Ian Rogers3bb17a62012-01-27 23:56:44 -0800595 VLOG(gc) << "Grow heap (frag case) to " << PrettySize(new_footprint)
Ian Rogers162a31c2012-01-31 16:14:31 -0800596 << " for a " << PrettySize(alloc_size) << " allocation";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700597 return ptr;
598 }
599
Elliott Hughes81ff3182012-03-23 20:35:56 -0700600 // Most allocations should have succeeded by now, so the heap is really full, really fragmented,
601 // or the requested size is really big. Do another GC, collecting SoftReferences this time. The
602 // VM spec requires that all SoftReferences have been collected and cleared before throwing OOME.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700603
Elliott Hughes418dfe72011-10-06 18:56:27 -0700604 // OLD-TODO: wait for the finalizers from the previous GC to finish
Ian Rogers3bb17a62012-01-27 23:56:44 -0800605 VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size) << " allocation";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700606
607 if (Runtime::Current()->HasStatsEnabled()) {
608 ++Runtime::Current()->GetStats()->gc_for_alloc_count;
609 ++Thread::Current()->GetStats()->gc_for_alloc_count;
610 }
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -0700611 // We don't need a WaitForConcurrentGcToComplete here either.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700612 self->TransitionFromRunnableToSuspended(kWaitingPerformingGc);
613 CollectGarbageInternal(false, true);
614 self->TransitionFromSuspendedToRunnable();
Ian Rogers30fab402012-01-23 15:43:46 -0800615 ptr = space->AllocWithGrowth(alloc_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700616 if (ptr != NULL) {
617 return ptr;
618 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700619 // Allocation failed.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700620 return NULL;
621}
622
Elliott Hughesbf86d042011-08-31 17:53:14 -0700623int64_t Heap::GetMaxMemory() {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700624 size_t total = 0;
625 // TODO: C++0x auto
626 for (Spaces::const_iterator cur = spaces_.begin(); cur != spaces_.end(); ++cur) {
627 if ((*cur)->IsAllocSpace()) {
628 total += (*cur)->AsAllocSpace()->Capacity();
629 }
630 }
631 return total;
Elliott Hughesbf86d042011-08-31 17:53:14 -0700632}
633
634int64_t Heap::GetTotalMemory() {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700635 return GetMaxMemory();
Elliott Hughesbf86d042011-08-31 17:53:14 -0700636}
637
638int64_t Heap::GetFreeMemory() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700639 MutexLock mu(*statistics_lock_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700640 return GetMaxMemory() - num_bytes_allocated_;
Elliott Hughesbf86d042011-08-31 17:53:14 -0700641}
642
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700643class InstanceCounter {
644 public:
645 InstanceCounter(Class* c, bool count_assignable)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700646 SHARED_LOCKS_REQUIRED(GlobalSynchronization::mutator_lock_)
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700647 : class_(c), count_assignable_(count_assignable), count_(0) {
648 }
649
650 size_t GetCount() {
651 return count_;
652 }
653
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700654 static void Callback(Object* o, void* arg)
655 SHARED_LOCKS_REQUIRED(GlobalSynchronization::mutator_lock_) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700656 reinterpret_cast<InstanceCounter*>(arg)->VisitInstance(o);
657 }
658
659 private:
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700660 void VisitInstance(Object* o) SHARED_LOCKS_REQUIRED(GlobalSynchronization::mutator_lock_) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700661 Class* instance_class = o->GetClass();
662 if (count_assignable_) {
663 if (instance_class == class_) {
664 ++count_;
665 }
666 } else {
667 if (instance_class != NULL && class_->IsAssignableFrom(instance_class)) {
668 ++count_;
669 }
670 }
671 }
672
673 Class* class_;
674 bool count_assignable_;
675 size_t count_;
676};
677
678int64_t Heap::CountInstances(Class* c, bool count_assignable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700679 ReaderMutexLock mu(*GlobalSynchronization::heap_bitmap_lock_);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700680 InstanceCounter counter(c, count_assignable);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700681 GetLiveBitmap()->Walk(InstanceCounter::Callback, &counter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700682 return counter.GetCount();
683}
684
Ian Rogers30fab402012-01-23 15:43:46 -0800685void Heap::CollectGarbage(bool clear_soft_references) {
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -0700686 // If we just waited for a GC to complete then we do not need to do another
687 // GC unless we clear soft references.
688 if (!WaitForConcurrentGcToComplete() || clear_soft_references) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700689 ScopedThreadStateChange tsc(Thread::Current(), kWaitingPerformingGc);
690 CollectGarbageInternal(have_zygote_space_, clear_soft_references);
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -0700691 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700692}
693
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700694void Heap::PreZygoteFork() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700695 static Mutex zygote_creation_lock_("zygote creation lock", kZygoteCreationLock);
696 MutexLock mu(zygote_creation_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700697
698 // Try to see if we have any Zygote spaces.
699 if (have_zygote_space_) {
700 return;
701 }
702
703 VLOG(heap) << "Starting PreZygoteFork with alloc space size " << PrettySize(GetBytesAllocated());
704
705 // Replace the first alloc space we find with a zygote space.
706 // TODO: C++0x auto
707 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
708 if ((*it)->IsAllocSpace()) {
709 AllocSpace* zygote_space = (*it)->AsAllocSpace();
710
711 // Turns the current alloc space into a Zygote space and obtain the new alloc space composed
712 // of the remaining available heap memory.
713 alloc_space_ = zygote_space->CreateZygoteSpace();
714
715 // Change the GC retention policy of the zygote space to only collect when full.
716 zygote_space->SetGcRetentionPolicy(GCRP_FULL_COLLECT);
717 AddSpace(alloc_space_);
718 have_zygote_space_ = true;
719 break;
720 }
721 }
722}
723
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700724void Heap::CollectGarbageInternal(bool partial_gc, bool clear_soft_references) {
725 GlobalSynchronization::mutator_lock_->AssertNotHeld();
726#ifndef NDEBUG
727 {
728 MutexLock mu(*GlobalSynchronization::thread_suspend_count_lock_);
729 CHECK_EQ(Thread::Current()->GetState(), kWaitingPerformingGc);
730 }
731#endif
Carl Shapiro58551df2011-07-24 03:09:51 -0700732
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700733 // Ensure there is only one GC at a time.
734 bool start_collect = false;
735 while (!start_collect) {
736 {
737 MutexLock mu(*gc_complete_lock_);
738 if (!is_gc_running_) {
739 is_gc_running_ = true;
740 start_collect = true;
741 }
742 }
743 if (!start_collect) {
744 WaitForConcurrentGcToComplete();
745 // TODO: if another thread beat this one to do the GC, perhaps we should just return here?
746 // Not doing at the moment to ensure soft references are cleared.
747 }
748 }
749 gc_complete_lock_->AssertNotHeld();
750 if (concurrent_gc_) {
751 CollectGarbageConcurrentMarkSweepPlan(partial_gc, clear_soft_references);
752 } else {
753 CollectGarbageMarkSweepPlan(partial_gc, clear_soft_references);
754 }
755 gc_complete_lock_->AssertNotHeld();
756 MutexLock mu(*gc_complete_lock_);
757 is_gc_running_ = false;
758 // Wake anyone who may have been waiting for the GC to complete.
759 gc_complete_cond_->Broadcast();
760}
Mathieu Chartiera6399032012-06-11 18:49:50 -0700761
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700762void Heap::CollectGarbageMarkSweepPlan(bool partial_gc, bool clear_soft_references) {
Mathieu Chartier662618f2012-06-06 12:01:47 -0700763 TimingLogger timings("CollectGarbageInternal");
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700764 uint64_t t0 = NanoTime(), dirty_end = 0;
Mathieu Chartier662618f2012-06-06 12:01:47 -0700765
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700766 // Suspend all threads are get exclusive access to the heap.
Elliott Hughes8d768a92011-09-14 16:35:25 -0700767 ThreadList* thread_list = Runtime::Current()->GetThreadList();
768 thread_list->SuspendAll();
Mathieu Chartier662618f2012-06-06 12:01:47 -0700769 timings.AddSplit("SuspendAll");
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700770 GlobalSynchronization::mutator_lock_->AssertExclusiveHeld();
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700771
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700772 size_t initial_size;
773 {
774 MutexLock mu(*statistics_lock_);
775 initial_size = num_bytes_allocated_;
776 }
Elliott Hughesadb460d2011-10-05 17:02:34 -0700777 Object* cleared_references = NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700778 {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700779 MarkSweep mark_sweep(mark_stack_.get());
Elliott Hughes307f75d2011-10-12 18:04:40 -0700780 timings.AddSplit("ctor");
Carl Shapiro58551df2011-07-24 03:09:51 -0700781
782 mark_sweep.Init();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700783 timings.AddSplit("Init");
Carl Shapiro58551df2011-07-24 03:09:51 -0700784
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700785 // Make sure that the tables have the correct pointer for the mark sweep.
786 mod_union_table_->Init(&mark_sweep);
787 zygote_mod_union_table_->Init(&mark_sweep);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700788
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700789 // Clear image space cards and keep track of cards we cleared in the mod-union table.
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700790 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
791 Space* space = *it;
792 if (space->IsImageSpace()) {
793 mod_union_table_->ClearCards(*it);
794 } else if (space->GetGcRetentionPolicy() == GCRP_FULL_COLLECT) {
795 zygote_mod_union_table_->ClearCards(space);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700796 }
797 }
798 timings.AddSplit("ClearCards");
799
800#if VERIFY_MOD_UNION
801 mod_union_table_->Verify();
802 zygote_mod_union_table_->Verify();
803#endif
804
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700805 WriterMutexLock mu(*GlobalSynchronization::heap_bitmap_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700806 if (partial_gc) {
807 // Copy the mark bits over from the live bits, do this as early as possible or else we can
808 // accidentally un-mark roots.
809 // Needed for scanning dirty objects.
810 mark_sweep.CopyMarkBits();
811 timings.AddSplit("CopyMarkBits");
812 }
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700813
Carl Shapiro58551df2011-07-24 03:09:51 -0700814 mark_sweep.MarkRoots();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700815 timings.AddSplit("MarkRoots");
Carl Shapiro58551df2011-07-24 03:09:51 -0700816
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700817 // Roots are marked on the bitmap and the mark_stack is empty.
Ian Rogers5d76c432011-10-31 21:42:49 -0700818 DCHECK(mark_sweep.IsMarkStackEmpty());
Carl Shapiro58551df2011-07-24 03:09:51 -0700819
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700820 // Update zygote mod union table.
821 if (partial_gc) {
822 zygote_mod_union_table_->Update();
823 timings.AddSplit("UpdateZygoteModUnionTable");
824
825 zygote_mod_union_table_->MarkReferences();
826 timings.AddSplit("ZygoteMarkReferences");
827 }
828
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700829 // Processes the cards we cleared earlier and adds their objects into the mod-union table.
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700830 mod_union_table_->Update();
Mathieu Chartiere6e06512012-06-26 15:00:26 -0700831 timings.AddSplit("UpdateModUnionTable");
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700832
833 // Scans all objects in the mod-union table.
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700834 mod_union_table_->MarkReferences();
Mathieu Chartiere6e06512012-06-26 15:00:26 -0700835 timings.AddSplit("MarkImageToAllocSpaceReferences");
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700836
837 // Recursively mark all the non-image bits set in the mark bitmap.
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700838 mark_sweep.RecursiveMark(partial_gc);
839 timings.AddSplit(partial_gc ? "PartialMark" : "RecursiveMark");
Carl Shapiro58551df2011-07-24 03:09:51 -0700840
Ian Rogers30fab402012-01-23 15:43:46 -0800841 mark_sweep.ProcessReferences(clear_soft_references);
Elliott Hughes307f75d2011-10-12 18:04:40 -0700842 timings.AddSplit("ProcessReferences");
Carl Shapiro58551df2011-07-24 03:09:51 -0700843
Mathieu Chartier654d3a22012-07-11 17:54:18 -0700844 // Swap the live and mark bitmaps for each alloc space. This is needed since sweep re-swaps
845 // these bitmaps. Doing this enables us to sweep with the heap unlocked since new allocations
846 // set the live bit, but since we have the bitmaps reversed at this point, this sets the mark bit
847 // instead, resulting in no new allocated objects being incorrectly freed by sweep.
848 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
849 Space* space = *it;
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700850 // We never allocate into zygote spaces.
851 if (space->GetGcRetentionPolicy() == GCRP_ALWAYS_COLLECT) {
Mathieu Chartier654d3a22012-07-11 17:54:18 -0700852 live_bitmap_->ReplaceBitmap(space->GetLiveBitmap(), space->GetMarkBitmap());
853 mark_bitmap_->ReplaceBitmap(space->GetMarkBitmap(), space->GetLiveBitmap());
854 space->AsAllocSpace()->SwapBitmaps();
855 }
856 }
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700857
858 // Verify that we only reach marked objects from the image space
859 mark_sweep.VerifyImageRoots();
860 timings.AddSplit("VerifyImageRoots");
Carl Shapiro58551df2011-07-24 03:09:51 -0700861
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700862 mark_sweep.Sweep(partial_gc);
Elliott Hughes307f75d2011-10-12 18:04:40 -0700863 timings.AddSplit("Sweep");
Elliott Hughesadb460d2011-10-05 17:02:34 -0700864
865 cleared_references = mark_sweep.GetClearedReferences();
Carl Shapiro58551df2011-07-24 03:09:51 -0700866 }
867
868 GrowForUtilization();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700869 timings.AddSplit("GrowForUtilization");
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700870
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700871 thread_list->ResumeAll();
872 dirty_end = NanoTime();
Elliott Hughesadb460d2011-10-05 17:02:34 -0700873
874 EnqueueClearedReferences(&cleared_references);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -0800875 RequestHeapTrim();
Mathieu Chartier662618f2012-06-06 12:01:47 -0700876 timings.AddSplit("Finish");
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700877
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700878 if (VLOG_IS_ON(gc)) {
879 uint64_t t1 = NanoTime();
880
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700881 MutexLock mu(*statistics_lock_);
Ian Rogers3bb17a62012-01-27 23:56:44 -0800882 // TODO: somehow make the specific GC implementation (here MarkSweep) responsible for logging.
Mathieu Chartiera6399032012-06-11 18:49:50 -0700883 // Reason: For CMS sometimes initial_size < num_bytes_allocated_ results in overflow (3GB freed message).
Ian Rogers3bb17a62012-01-27 23:56:44 -0800884 size_t bytes_freed = initial_size - num_bytes_allocated_;
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700885 uint64_t duration_ns = t1 - t0;
886 duration_ns -= duration_ns % 1000;
887
888 // If the GC was slow, then print timings in the log.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700889 if (duration_ns > MsToNs(50)) {
890 uint64_t markSweepTime = (dirty_end - t0) / 1000 * 1000;
891 LOG(INFO) << (partial_gc ? "Partial " : "")
892 << "GC freed " << PrettySize(bytes_freed) << ", " << GetPercentFree() << "% free, "
893 << PrettySize(num_bytes_allocated_) << "/" << PrettySize(GetTotalMemory()) << ", "
894 << "paused " << PrettyDuration(markSweepTime)
895 << ", total " << PrettyDuration(duration_ns);
Mathieu Chartier662618f2012-06-06 12:01:47 -0700896 }
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700897 }
Elliott Hughes767a1472011-10-26 18:49:02 -0700898 Dbg::GcDidFinish();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800899 if (VLOG_IS_ON(heap)) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700900 timings.Dump();
901 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700902}
Mathieu Chartiera6399032012-06-11 18:49:50 -0700903
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700904void Heap::CollectGarbageConcurrentMarkSweepPlan(bool partial_gc, bool clear_soft_references) {
905 TimingLogger timings("CollectGarbageInternal");
906 uint64_t t0 = NanoTime(), root_end = 0, dirty_begin = 0, dirty_end = 0;
Mathieu Chartiera6399032012-06-11 18:49:50 -0700907
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700908 // Suspend all threads are get exclusive access to the heap.
909 ThreadList* thread_list = Runtime::Current()->GetThreadList();
910 thread_list->SuspendAll();
911 timings.AddSplit("SuspendAll");
912 GlobalSynchronization::mutator_lock_->AssertExclusiveHeld();
913
914 size_t initial_size;
915 {
916 MutexLock mu(*statistics_lock_);
917 initial_size = num_bytes_allocated_;
918 }
919 Object* cleared_references = NULL;
920 {
921 MarkSweep mark_sweep(mark_stack_.get());
922 timings.AddSplit("ctor");
923
924 mark_sweep.Init();
925 timings.AddSplit("Init");
926
927 // Make sure that the tables have the correct pointer for the mark sweep.
928 mod_union_table_->Init(&mark_sweep);
929 zygote_mod_union_table_->Init(&mark_sweep);
930
931 // Clear image space cards and keep track of cards we cleared in the mod-union table.
932 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
933 Space* space = *it;
934 if (space->IsImageSpace()) {
935 mod_union_table_->ClearCards(*it);
936 } else if (space->GetGcRetentionPolicy() == GCRP_FULL_COLLECT) {
937 zygote_mod_union_table_->ClearCards(space);
938 } else {
939 card_table_->ClearSpaceCards(space);
940 }
941 }
942 timings.AddSplit("ClearCards");
943
944#if VERIFY_MOD_UNION
945 mod_union_table_->Verify();
946 zygote_mod_union_table_->Verify();
947#endif
948
949 if (partial_gc) {
950 // Copy the mark bits over from the live bits, do this as early as possible or else we can
951 // accidentally un-mark roots.
952 // Needed for scanning dirty objects.
953 mark_sweep.CopyMarkBits();
954 timings.AddSplit("CopyMarkBits");
955 }
956
957 {
958 WriterMutexLock mu(*GlobalSynchronization::heap_bitmap_lock_);
959 mark_sweep.MarkRoots();
960 timings.AddSplit("MarkRoots");
961 }
962
963 // Roots are marked on the bitmap and the mark_stack is empty.
964 DCHECK(mark_sweep.IsMarkStackEmpty());
965
966 // Allow mutators to go again, acquire share on mutator_lock_ to continue.
967 thread_list->ResumeAll();
968 {
969 ReaderMutexLock reader_lock(*GlobalSynchronization::mutator_lock_);
970 root_end = NanoTime();
971 timings.AddSplit("RootEnd");
972
973 {
974 ReaderMutexLock mu(*GlobalSynchronization::heap_bitmap_lock_);
975 // Update zygote mod union table.
976 if (partial_gc) {
977 zygote_mod_union_table_->Update();
978 timings.AddSplit("UpdateZygoteModUnionTable");
979
980 zygote_mod_union_table_->MarkReferences();
981 timings.AddSplit("ZygoteMarkReferences");
982 }
983
984 // Processes the cards we cleared earlier and adds their objects into the mod-union table.
985 mod_union_table_->Update();
986 timings.AddSplit("UpdateModUnionTable");
987 }
988 {
989 WriterMutexLock mu(*GlobalSynchronization::heap_bitmap_lock_);
990 // Scans all objects in the mod-union table.
991 mod_union_table_->MarkReferences();
992 timings.AddSplit("MarkImageToAllocSpaceReferences");
993
994 // Recursively mark all the non-image bits set in the mark bitmap.
995 mark_sweep.RecursiveMark(partial_gc);
996 timings.AddSplit(partial_gc ? "PartialMark" : "RecursiveMark");
997 }
998 }
999 // Release share on mutator_lock_ and then get exclusive access.
1000 dirty_begin = NanoTime();
1001 thread_list->SuspendAll();
1002 timings.AddSplit("ReSuspend");
1003 GlobalSynchronization::mutator_lock_->AssertExclusiveHeld();
1004
1005 {
1006 WriterMutexLock mu(*GlobalSynchronization::heap_bitmap_lock_);
1007 // Re-mark root set.
1008 mark_sweep.ReMarkRoots();
1009 timings.AddSplit("ReMarkRoots");
1010
1011 // Scan dirty objects, this is only required if we are not doing concurrent GC.
1012 mark_sweep.RecursiveMarkDirtyObjects();
1013 timings.AddSplit("RecursiveMarkDirtyObjects");
1014 }
1015 {
1016 ReaderMutexLock mu(*GlobalSynchronization::heap_bitmap_lock_);
1017 mark_sweep.ProcessReferences(clear_soft_references);
1018 timings.AddSplit("ProcessReferences");
1019 }
1020 // Swap the live and mark bitmaps for each alloc space. This is needed since sweep re-swaps
1021 // these bitmaps. Doing this enables us to sweep with the heap unlocked since new allocations
1022 // set the live bit, but since we have the bitmaps reversed at this point, this sets the mark
1023 // bit instead, resulting in no new allocated objects being incorrectly freed by sweep.
1024 {
1025 WriterMutexLock mu(*GlobalSynchronization::heap_bitmap_lock_);
1026 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1027 Space* space = *it;
1028 // We never allocate into zygote spaces.
1029 if (space->GetGcRetentionPolicy() == GCRP_ALWAYS_COLLECT) {
1030 live_bitmap_->ReplaceBitmap(space->GetLiveBitmap(), space->GetMarkBitmap());
1031 mark_bitmap_->ReplaceBitmap(space->GetMarkBitmap(), space->GetLiveBitmap());
1032 space->AsAllocSpace()->SwapBitmaps();
1033 }
1034 }
1035 }
1036
1037 if (kIsDebugBuild) {
1038 // Verify that we only reach marked objects from the image space.
1039 ReaderMutexLock mu(*GlobalSynchronization::heap_bitmap_lock_);
1040 mark_sweep.VerifyImageRoots();
1041 timings.AddSplit("VerifyImageRoots");
1042 }
1043 thread_list->ResumeAll();
1044 dirty_end = NanoTime();
1045 GlobalSynchronization::mutator_lock_->AssertNotHeld();
1046
1047 {
1048 // TODO: this lock shouldn't be necessary (it's why we did the bitmap flip above).
1049 WriterMutexLock mu(*GlobalSynchronization::heap_bitmap_lock_);
1050 mark_sweep.Sweep(partial_gc);
1051 timings.AddSplit("Sweep");
1052 }
1053
1054 cleared_references = mark_sweep.GetClearedReferences();
1055 }
1056
1057 GrowForUtilization();
1058 timings.AddSplit("GrowForUtilization");
1059
1060 EnqueueClearedReferences(&cleared_references);
1061 RequestHeapTrim();
1062 timings.AddSplit("Finish");
1063
1064 if (VLOG_IS_ON(gc)) {
1065 uint64_t t1 = NanoTime();
1066
1067 MutexLock mu(*statistics_lock_);
1068 // TODO: somehow make the specific GC implementation (here MarkSweep) responsible for logging.
1069 // Reason: For CMS sometimes initial_size < num_bytes_allocated_ results in overflow (3GB freed message).
1070 size_t bytes_freed = initial_size - num_bytes_allocated_;
1071 uint64_t duration_ns = t1 - t0;
1072 duration_ns -= duration_ns % 1000;
1073
1074 // If the GC was slow, then print timings in the log.
1075 uint64_t pause_roots = (root_end - t0) / 1000 * 1000;
1076 uint64_t pause_dirty = (dirty_end - dirty_begin) / 1000 * 1000;
1077 if (pause_roots > MsToNs(5) || pause_dirty > MsToNs(5)) {
1078 LOG(INFO) << (partial_gc ? "Partial " : "")
1079 << "GC freed " << PrettySize(bytes_freed) << ", " << GetPercentFree() << "% free, "
1080 << PrettySize(num_bytes_allocated_) << "/" << PrettySize(GetTotalMemory()) << ", "
1081 << "paused " << PrettyDuration(pause_roots) << "+" << PrettyDuration(pause_dirty)
1082 << ", total " << PrettyDuration(duration_ns);
1083 }
1084 }
1085 Dbg::GcDidFinish();
1086 if (VLOG_IS_ON(heap)) {
1087 timings.Dump();
1088 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001089}
1090
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -07001091bool Heap::WaitForConcurrentGcToComplete() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001092 if (concurrent_gc_) {
1093 bool do_wait = false;
1094 uint64_t wait_start;
1095 {
1096 // Check if GC is running holding gc_complete_lock_.
1097 MutexLock mu(*gc_complete_lock_);
1098 if (is_gc_running_) {
1099 wait_start = NanoTime();
1100 do_wait = true;
1101 }
Mathieu Chartiera6399032012-06-11 18:49:50 -07001102 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001103 if (do_wait) {
1104 // We must wait, change thread state then sleep on gc_complete_cond_;
1105 ScopedThreadStateChange tsc(Thread::Current(), kWaitingForGcToComplete);
1106 {
1107 MutexLock mu(*gc_complete_lock_);
1108 while (is_gc_running_) {
1109 gc_complete_cond_->Wait(*gc_complete_lock_);
1110 }
1111 }
1112 uint64_t wait_time = NanoTime() - wait_start;
1113 if (wait_time > MsToNs(5)) {
1114 LOG(INFO) << "WaitForConcurrentGcToComplete blocked for " << PrettyDuration(wait_time);
1115 }
1116 return true;
1117 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001118 }
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -07001119 return false;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001120}
1121
Elliott Hughesc967f782012-04-16 10:23:15 -07001122void Heap::DumpForSigQuit(std::ostream& os) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001123 MutexLock mu(*statistics_lock_);
Elliott Hughesc967f782012-04-16 10:23:15 -07001124 os << "Heap: " << GetPercentFree() << "% free, "
1125 << PrettySize(num_bytes_allocated_) << "/" << PrettySize(GetTotalMemory())
Elliott Hughesae80b492012-04-24 10:43:17 -07001126 << "; " << num_objects_allocated_ << " objects\n";
Elliott Hughesc967f782012-04-16 10:23:15 -07001127}
1128
1129size_t Heap::GetPercentFree() {
1130 size_t total = GetTotalMemory();
1131 return 100 - static_cast<size_t>(100.0f * static_cast<float>(num_bytes_allocated_) / total);
1132}
1133
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001134void Heap::SetIdealFootprint(size_t max_allowed_footprint) {
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001135 AllocSpace* alloc_space = alloc_space_;
1136 // TODO: Behavior for multiple alloc spaces?
1137 size_t alloc_space_capacity = alloc_space->Capacity();
1138 if (max_allowed_footprint > alloc_space_capacity) {
1139 VLOG(gc) << "Clamp target GC heap from " << PrettySize(max_allowed_footprint)
1140 << " to " << PrettySize(alloc_space_capacity);
1141 max_allowed_footprint = alloc_space_capacity;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001142 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001143 alloc_space->SetFootprintLimit(max_allowed_footprint);
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001144}
1145
Ian Rogers3bb17a62012-01-27 23:56:44 -08001146// kHeapIdealFree is the ideal maximum free size, when we grow the heap for utilization.
Shih-wei Liao7f1caab2011-10-06 12:11:04 -07001147static const size_t kHeapIdealFree = 2 * MB;
Ian Rogers3bb17a62012-01-27 23:56:44 -08001148// kHeapMinFree guarantees that you always have at least 512 KB free, when you grow for utilization,
1149// regardless of target utilization ratio.
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001150static const size_t kHeapMinFree = kHeapIdealFree / 4;
1151
Carl Shapiro69759ea2011-07-21 18:13:35 -07001152void Heap::GrowForUtilization() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001153 size_t target_size;
1154 bool use_footprint_limit = false;
1155 {
1156 MutexLock mu(*statistics_lock_);
1157 // We know what our utilization is at this moment.
1158 // This doesn't actually resize any memory. It just lets the heap grow more when necessary.
1159 target_size = num_bytes_allocated_ / Heap::GetTargetHeapUtilization();
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001160
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001161 if (target_size > num_bytes_allocated_ + kHeapIdealFree) {
1162 target_size = num_bytes_allocated_ + kHeapIdealFree;
1163 } else if (target_size < num_bytes_allocated_ + kHeapMinFree) {
1164 target_size = num_bytes_allocated_ + kHeapMinFree;
1165 }
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001166
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001167 // Calculate when to perform the next ConcurrentGC.
1168 if (GetTotalMemory() - num_bytes_allocated_ < concurrent_min_free_) {
1169 // Not enough free memory to perform concurrent GC.
1170 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
1171 } else {
1172 // Compute below to avoid holding both the statistics and the alloc space lock
1173 use_footprint_limit = true;
1174 }
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001175 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001176 if (use_footprint_limit) {
1177 size_t foot_print_limit = alloc_space_->GetFootprintLimit();
1178 MutexLock mu(*statistics_lock_);
1179 concurrent_start_bytes_ = foot_print_limit - concurrent_start_size_;
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001180 }
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001181 SetIdealFootprint(target_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001182}
1183
jeffhaoc1160702011-10-27 15:48:45 -07001184void Heap::ClearGrowthLimit() {
jeffhaoc1160702011-10-27 15:48:45 -07001185 WaitForConcurrentGcToComplete();
jeffhaoc1160702011-10-27 15:48:45 -07001186 alloc_space_->ClearGrowthLimit();
1187}
1188
Elliott Hughesadb460d2011-10-05 17:02:34 -07001189void Heap::SetReferenceOffsets(MemberOffset reference_referent_offset,
1190 MemberOffset reference_queue_offset,
1191 MemberOffset reference_queueNext_offset,
1192 MemberOffset reference_pendingNext_offset,
1193 MemberOffset finalizer_reference_zombie_offset) {
1194 reference_referent_offset_ = reference_referent_offset;
1195 reference_queue_offset_ = reference_queue_offset;
1196 reference_queueNext_offset_ = reference_queueNext_offset;
1197 reference_pendingNext_offset_ = reference_pendingNext_offset;
1198 finalizer_reference_zombie_offset_ = finalizer_reference_zombie_offset;
1199 CHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1200 CHECK_NE(reference_queue_offset_.Uint32Value(), 0U);
1201 CHECK_NE(reference_queueNext_offset_.Uint32Value(), 0U);
1202 CHECK_NE(reference_pendingNext_offset_.Uint32Value(), 0U);
1203 CHECK_NE(finalizer_reference_zombie_offset_.Uint32Value(), 0U);
1204}
1205
1206Object* Heap::GetReferenceReferent(Object* reference) {
1207 DCHECK(reference != NULL);
1208 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1209 return reference->GetFieldObject<Object*>(reference_referent_offset_, true);
1210}
1211
1212void Heap::ClearReferenceReferent(Object* reference) {
1213 DCHECK(reference != NULL);
1214 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1215 reference->SetFieldObject(reference_referent_offset_, NULL, true);
1216}
1217
1218// Returns true if the reference object has not yet been enqueued.
1219bool Heap::IsEnqueuable(const Object* ref) {
1220 DCHECK(ref != NULL);
1221 const Object* queue = ref->GetFieldObject<Object*>(reference_queue_offset_, false);
1222 const Object* queue_next = ref->GetFieldObject<Object*>(reference_queueNext_offset_, false);
1223 return (queue != NULL) && (queue_next == NULL);
1224}
1225
1226void Heap::EnqueueReference(Object* ref, Object** cleared_reference_list) {
1227 DCHECK(ref != NULL);
1228 CHECK(ref->GetFieldObject<Object*>(reference_queue_offset_, false) != NULL);
1229 CHECK(ref->GetFieldObject<Object*>(reference_queueNext_offset_, false) == NULL);
1230 EnqueuePendingReference(ref, cleared_reference_list);
1231}
1232
1233void Heap::EnqueuePendingReference(Object* ref, Object** list) {
1234 DCHECK(ref != NULL);
1235 DCHECK(list != NULL);
1236
1237 if (*list == NULL) {
1238 ref->SetFieldObject(reference_pendingNext_offset_, ref, false);
1239 *list = ref;
1240 } else {
1241 Object* head = (*list)->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
1242 ref->SetFieldObject(reference_pendingNext_offset_, head, false);
1243 (*list)->SetFieldObject(reference_pendingNext_offset_, ref, false);
1244 }
1245}
1246
1247Object* Heap::DequeuePendingReference(Object** list) {
1248 DCHECK(list != NULL);
1249 DCHECK(*list != NULL);
1250 Object* head = (*list)->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
1251 Object* ref;
1252 if (*list == head) {
1253 ref = *list;
1254 *list = NULL;
1255 } else {
1256 Object* next = head->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
1257 (*list)->SetFieldObject(reference_pendingNext_offset_, next, false);
1258 ref = head;
1259 }
1260 ref->SetFieldObject(reference_pendingNext_offset_, NULL, false);
1261 return ref;
1262}
1263
Ian Rogers5d4bdc22011-11-02 22:15:43 -07001264void Heap::AddFinalizerReference(Thread* self, Object* object) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001265 ScopedObjectAccess soa(self);
Elliott Hughes77405792012-03-15 15:22:12 -07001266 JValue args[1];
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07001267 args[0].SetL(object);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001268 soa.DecodeMethod(WellKnownClasses::java_lang_ref_FinalizerReference_add)->Invoke(self,
1269 NULL, args, NULL);
1270}
1271
1272size_t Heap::GetBytesAllocated() const {
1273 MutexLock mu(*statistics_lock_);
1274 return num_bytes_allocated_;
1275}
1276
1277size_t Heap::GetObjectsAllocated() const {
1278 MutexLock mu(*statistics_lock_);
1279 return num_objects_allocated_;
1280}
1281
1282size_t Heap::GetConcurrentStartSize() const {
1283 MutexLock mu(*statistics_lock_);
1284 return concurrent_start_size_;
1285}
1286
1287size_t Heap::GetConcurrentMinFree() const {
1288 MutexLock mu(*statistics_lock_);
1289 return concurrent_min_free_;
Elliott Hughesadb460d2011-10-05 17:02:34 -07001290}
1291
1292void Heap::EnqueueClearedReferences(Object** cleared) {
1293 DCHECK(cleared != NULL);
1294 if (*cleared != NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001295 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes77405792012-03-15 15:22:12 -07001296 JValue args[1];
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07001297 args[0].SetL(*cleared);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001298 soa.DecodeMethod(WellKnownClasses::java_lang_ref_ReferenceQueue_add)->Invoke(soa.Self(),
1299 NULL, args, NULL);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001300 *cleared = NULL;
1301 }
1302}
1303
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001304void Heap::RequestConcurrentGC() {
Mathieu Chartier069387a2012-06-18 12:01:01 -07001305 // Make sure that we can do a concurrent GC.
1306 if (requesting_gc_ ||
1307 !Runtime::Current()->IsFinishedStarting() ||
1308 Runtime::Current()->IsShuttingDown() ||
1309 !Runtime::Current()->IsConcurrentGcEnabled()) {
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001310 return;
1311 }
1312
1313 requesting_gc_ = true;
1314 JNIEnv* env = Thread::Current()->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07001315 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
1316 DCHECK(WellKnownClasses::java_lang_Daemons_requestGC != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001317 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
1318 WellKnownClasses::java_lang_Daemons_requestGC);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001319 CHECK(!env->ExceptionCheck());
1320 requesting_gc_ = false;
1321}
1322
1323void Heap::ConcurrentGC() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001324 if (Runtime::Current()->IsShuttingDown() || !concurrent_gc_) {
Mathieu Chartier2542d662012-06-21 17:14:11 -07001325 return;
1326 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001327 // TODO: We shouldn't need a WaitForConcurrentGcToComplete here since only
1328 // concurrent GC resumes threads before the GC is completed and this function
1329 // is only called within the GC daemon thread.
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001330 if (!WaitForConcurrentGcToComplete()) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001331 // Start a concurrent GC as one wasn't in progress
1332 ScopedThreadStateChange tsc(Thread::Current(), kWaitingPerformingGc);
1333 CollectGarbageInternal(have_zygote_space_, false);
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001334 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001335}
1336
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001337void Heap::Trim(AllocSpace* alloc_space) {
Mathieu Chartiera6399032012-06-11 18:49:50 -07001338 WaitForConcurrentGcToComplete();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001339 alloc_space->Trim();
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001340}
1341
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001342void Heap::RequestHeapTrim() {
1343 // We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
1344 // because that only marks object heads, so a large array looks like lots of empty space. We
1345 // don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
1346 // to utilization (which is probably inversely proportional to how much benefit we can expect).
1347 // We could try mincore(2) but that's only a measure of how many pages we haven't given away,
1348 // not how much use we're making of those pages.
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001349 uint64_t ms_time = NsToMs(NanoTime());
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001350 {
1351 MutexLock mu(*statistics_lock_);
1352 float utilization = static_cast<float>(num_bytes_allocated_) / alloc_space_->Size();
1353 if ((utilization > 0.75f) || ((ms_time - last_trim_time_) < 2 * 1000)) {
1354 // Don't bother trimming the heap if it's more than 75% utilized, or if a
1355 // heap trim occurred in the last two seconds.
1356 return;
1357 }
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001358 }
Mathieu Chartiera6399032012-06-11 18:49:50 -07001359 if (!Runtime::Current()->IsFinishedStarting() || Runtime::Current()->IsShuttingDown()) {
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001360 // Heap trimming isn't supported without a Java runtime or Daemons (such as at dex2oat time)
Mathieu Chartiera6399032012-06-11 18:49:50 -07001361 // Also: we do not wish to start a heap trim if the runtime is shutting down.
Ian Rogerse1d490c2012-02-03 09:09:07 -08001362 return;
1363 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001364 last_trim_time_ = ms_time;
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001365 JNIEnv* env = Thread::Current()->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07001366 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
1367 DCHECK(WellKnownClasses::java_lang_Daemons_requestHeapTrim != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001368 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
1369 WellKnownClasses::java_lang_Daemons_requestHeapTrim);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001370 CHECK(!env->ExceptionCheck());
1371}
1372
Carl Shapiro69759ea2011-07-21 18:13:35 -07001373} // namespace art