blob: 2bf137215b45a3ac6b069c03d5021f0d233f55cb [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),
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700147 sticky_gc_count_(0),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800148 num_bytes_allocated_(0),
149 num_objects_allocated_(0),
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700150 last_trim_time_(0),
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700151 try_running_gc_(false),
152 requesting_gc_(false),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800153 reference_referent_offset_(0),
154 reference_queue_offset_(0),
155 reference_queueNext_offset_(0),
156 reference_pendingNext_offset_(0),
157 finalizer_reference_zombie_offset_(0),
158 target_utilization_(0.5),
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700159 verify_objects_(false) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800160 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800161 LOG(INFO) << "Heap() entering";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700162 }
163
Ian Rogers30fab402012-01-23 15:43:46 -0800164 // Compute the bounds of all spaces for allocating live and mark bitmaps
165 // there will be at least one space (the alloc space)
166 Space* first_space = NULL;
167 Space* last_space = NULL;
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700168
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700169 live_bitmap_.reset(new HeapBitmap(this));
170 mark_bitmap_.reset(new HeapBitmap(this));
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700171
Ian Rogers30fab402012-01-23 15:43:46 -0800172 // Requested begin for the alloc space, to follow the mapped image and oat files
173 byte* requested_begin = NULL;
Brian Carlstrom5643b782012-02-05 12:32:53 -0800174 std::string image_file_name(original_image_file_name);
175 if (!image_file_name.empty()) {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700176 Space* image_space = NULL;
177
Brian Carlstrom5643b782012-02-05 12:32:53 -0800178 if (OS::FileExists(image_file_name.c_str())) {
179 // If the /system file exists, it should be up-to-date, don't try to generate
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700180 image_space = Space::CreateImageSpace(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800181 } else {
182 // If the /system file didn't exist, we need to use one from the art-cache.
183 // If the cache file exists, try to open, but if it fails, regenerate.
184 // If it does not exist, generate.
185 image_file_name = GetArtCacheFilenameOrDie(image_file_name);
186 if (OS::FileExists(image_file_name.c_str())) {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700187 image_space = Space::CreateImageSpace(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800188 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700189 if (image_space == NULL) {
Brian Carlstrom5643b782012-02-05 12:32:53 -0800190 if (!GenerateImage(image_file_name)) {
191 LOG(FATAL) << "Failed to generate image: " << image_file_name;
192 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700193 image_space = Space::CreateImageSpace(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800194 }
195 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700196 if (image_space == NULL) {
Brian Carlstrom223f20f2012-02-04 23:06:55 -0800197 LOG(FATAL) << "Failed to create space from " << image_file_name;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700198 }
Brian Carlstrom5643b782012-02-05 12:32:53 -0800199
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700200 AddSpace(image_space);
201 UpdateFirstAndLastSpace(&first_space, &last_space, image_space);
Ian Rogers30fab402012-01-23 15:43:46 -0800202 // Oat files referenced by image files immediately follow them in memory, ensure alloc space
203 // isn't going to get in the middle
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700204 byte* oat_end_addr = GetImageSpace()->GetImageHeader().GetOatEnd();
205 CHECK(oat_end_addr > GetImageSpace()->End());
Ian Rogers30fab402012-01-23 15:43:46 -0800206 if (oat_end_addr > requested_begin) {
207 requested_begin = reinterpret_cast<byte*>(RoundUp(reinterpret_cast<uintptr_t>(oat_end_addr),
208 kPageSize));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700209 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700210 }
211
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700212 UniquePtr<AllocSpace> alloc_space(Space::CreateAllocSpace(
213 "alloc space", initial_size, growth_limit, capacity, requested_begin));
214 alloc_space_ = alloc_space.release();
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700215 CHECK(alloc_space_ != NULL) << "Failed to create alloc space";
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700216 AddSpace(alloc_space_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700217
Ian Rogers30fab402012-01-23 15:43:46 -0800218 UpdateFirstAndLastSpace(&first_space, &last_space, alloc_space_);
219 byte* heap_begin = first_space->Begin();
Ian Rogers3bb17a62012-01-27 23:56:44 -0800220 size_t heap_capacity = (last_space->Begin() - first_space->Begin()) + last_space->NonGrowthLimitCapacity();
Carl Shapiro69759ea2011-07-21 18:13:35 -0700221
Ian Rogers30fab402012-01-23 15:43:46 -0800222 // Mark image objects in the live bitmap
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800223 for (size_t i = 0; i < spaces_.size(); ++i) {
Ian Rogers30fab402012-01-23 15:43:46 -0800224 Space* space = spaces_[i];
225 if (space->IsImageSpace()) {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700226 space->AsImageSpace()->RecordImageAllocations(space->GetLiveBitmap());
Ian Rogers30fab402012-01-23 15:43:46 -0800227 }
228 }
229
Elliott Hughes6c9c06d2011-11-07 16:43:47 -0800230 // Allocate the card table.
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700231 card_table_.reset(CardTable::Create(heap_begin, heap_capacity));
232 CHECK(card_table_.get() != NULL) << "Failed to create card table";
Ian Rogers5d76c432011-10-31 21:42:49 -0700233
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700234 mod_union_table_.reset(new ModUnionTableToZygoteAllocspace<ModUnionTableReferenceCache>(this));
235 CHECK(mod_union_table_.get() != NULL) << "Failed to create mod-union table";
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700236
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700237 zygote_mod_union_table_.reset(new ModUnionTableCardCache(this));
238 CHECK(zygote_mod_union_table_.get() != NULL) << "Failed to create Zygote mod-union table";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700239
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700240 num_bytes_allocated_ = 0;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700241 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
242 if ((*it)->IsImageSpace()) {
243 num_bytes_allocated_ += (*it)->AsImageSpace()->Size();
244 }
245 }
246
247 // TODO: Count objects in the image space here.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700248 num_objects_allocated_ = 0;
249
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700250 // Max stack size in bytes.
251 static const size_t max_stack_size = capacity / SpaceBitmap::kAlignment * kWordSize;
252
253 // TODO: Rename MarkStack to a more generic name?
254 mark_stack_.reset(MarkStack::Create("dalvik-mark-stack", max_stack_size));
255 allocation_stack_.reset(MarkStack::Create("dalvik-allocation-stack", max_stack_size));
256 live_stack_.reset(MarkStack::Create("dalvik-live-stack", max_stack_size));
Mathieu Chartier5301cd22012-05-31 12:11:36 -0700257
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.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700261 statistics_lock_ = new Mutex("statistics lock");
262 gc_complete_lock_ = new Mutex("GC complete lock");
263 gc_complete_cond_.reset(new ConditionVariable("GC complete condition variable"));
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700264
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800265 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800266 LOG(INFO) << "Heap() exiting";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700267 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700268}
269
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700270// Sort spaces based on begin address
271class SpaceSorter {
272 public:
273 bool operator () (const Space* a, const Space* b) const {
274 return a->Begin() < b->Begin();
275 }
276};
277
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800278void Heap::AddSpace(Space* space) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700279 WriterMutexLock mu(*GlobalSynchronization::heap_bitmap_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700280 DCHECK(space != NULL);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700281 DCHECK(space->GetLiveBitmap() != NULL);
282 live_bitmap_->AddSpaceBitmap(space->GetLiveBitmap());
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700283 DCHECK(space->GetMarkBitmap() != NULL);
284 mark_bitmap_->AddSpaceBitmap(space->GetMarkBitmap());
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800285 spaces_.push_back(space);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700286 if (space->IsAllocSpace()) {
287 alloc_space_ = space->AsAllocSpace();
288 }
289
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700290 // Ensure that spaces remain sorted in increasing order of start address (required for CMS finger)
291 std::sort(spaces_.begin(), spaces_.end(), SpaceSorter());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700292
293 // Ensure that ImageSpaces < ZygoteSpaces < AllocSpaces so that we can do address based checks to
294 // avoid redundant marking.
295 bool seen_zygote = false, seen_alloc = false;
296 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
297 Space* space = *it;
298 if (space->IsImageSpace()) {
299 DCHECK(!seen_zygote);
300 DCHECK(!seen_alloc);
301 } if (space->IsZygoteSpace()) {
302 DCHECK(!seen_alloc);
303 seen_zygote = true;
304 } else if (space->IsAllocSpace()) {
305 seen_alloc = true;
306 }
307 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800308}
309
310Heap::~Heap() {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700311 // If we don't reset then the mark stack complains in it's destructor.
312 allocation_stack_->Reset();
313 live_stack_->Reset();
314
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800315 VLOG(heap) << "~Heap()";
Elliott Hughesb3e66df2012-01-12 14:49:18 -0800316 // We can't take the heap lock here because there might be a daemon thread suspended with the
317 // heap lock held. We know though that no non-daemon threads are executing, and we know that
318 // all daemon threads are suspended, and we also know that the threads list have been deleted, so
319 // 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 -0700320 STLDeleteElements(&spaces_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700321 delete statistics_lock_;
322 delete gc_complete_lock_;
323
Carl Shapiro69759ea2011-07-21 18:13:35 -0700324}
325
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700326Space* Heap::FindSpaceFromObject(const Object* obj) const {
327 // TODO: C++0x auto
328 for (Spaces::const_iterator cur = spaces_.begin(); cur != spaces_.end(); ++cur) {
329 if ((*cur)->Contains(obj)) {
330 return *cur;
331 }
332 }
333 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
334 return NULL;
335}
336
337ImageSpace* Heap::GetImageSpace() {
338 // TODO: C++0x auto
339 for (Spaces::const_iterator cur = spaces_.begin(); cur != spaces_.end(); ++cur) {
340 if ((*cur)->IsImageSpace()) {
341 return (*cur)->AsImageSpace();
342 }
343 }
344 return NULL;
345}
346
347AllocSpace* Heap::GetAllocSpace() {
348 return alloc_space_;
349}
350
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700351static void MSpaceChunkCallback(void* start, void* end, size_t used_bytes, void* arg) {
352 size_t& max_contiguous_allocation = *reinterpret_cast<size_t*>(arg);
353
354 size_t chunk_size = static_cast<size_t>(reinterpret_cast<uint8_t*>(end) - reinterpret_cast<uint8_t*>(start));
355 size_t chunk_free_bytes = 0;
356 if (used_bytes < chunk_size) {
357 chunk_free_bytes = chunk_size - used_bytes;
358 }
359
360 if (chunk_free_bytes > max_contiguous_allocation) {
361 max_contiguous_allocation = chunk_free_bytes;
362 }
363}
364
365Object* Heap::AllocObject(Class* c, size_t byte_count) {
366 // Used in the detail message if we throw an OOME.
367 int64_t total_bytes_free;
368 size_t max_contiguous_allocation;
369
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700370 DCHECK(c == NULL || (c->IsClassClass() && byte_count >= sizeof(Class)) ||
371 (c->IsVariableSize() || c->GetObjectSize() == byte_count) ||
372 strlen(ClassHelper(c).GetDescriptor()) == 0);
373 DCHECK_GE(byte_count, sizeof(Object));
374 Object* obj = Allocate(byte_count);
375 if (obj != NULL) {
376 obj->SetClass(c);
377 if (Dbg::IsAllocTrackingEnabled()) {
378 Dbg::RecordAllocation(c, byte_count);
Elliott Hughes418dfe72011-10-06 18:56:27 -0700379 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700380 bool request_concurrent_gc;
381 {
382 MutexLock mu(*statistics_lock_);
383 request_concurrent_gc = num_bytes_allocated_ >= concurrent_start_bytes_;
384 }
385 if (request_concurrent_gc) {
386 // The SirtRef is necessary since the calls in RequestConcurrentGC are a safepoint.
387 SirtRef<Object> ref(obj);
388 RequestConcurrentGC();
389 }
390 VerifyObject(obj);
391
392 // Additional verification to ensure that we did not allocate into a zygote space.
393 DCHECK(!have_zygote_space_ || !FindSpaceFromObject(obj)->IsZygoteSpace());
394
395 return obj;
396 }
397 total_bytes_free = GetFreeMemory();
398 max_contiguous_allocation = 0;
399 // TODO: C++0x auto
400 for (Spaces::const_iterator cur = spaces_.begin(); cur != spaces_.end(); ++cur) {
401 if ((*cur)->IsAllocSpace()) {
402 (*cur)->AsAllocSpace()->Walk(MSpaceChunkCallback, &max_contiguous_allocation);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700403 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700404 }
Elliott Hughes418dfe72011-10-06 18:56:27 -0700405
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700406 std::string msg(StringPrintf("Failed to allocate a %zd-byte %s (%lld total bytes free; largest possible contiguous allocation %zd bytes)",
407 byte_count,
408 PrettyDescriptor(c).c_str(),
409 total_bytes_free, max_contiguous_allocation));
410 Thread::Current()->ThrowOutOfMemoryError(msg.c_str());
Elliott Hughes418dfe72011-10-06 18:56:27 -0700411 return NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700412}
413
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700414bool Heap::IsHeapAddress(const Object* obj) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700415 // Note: we deliberately don't take the lock here, and mustn't test anything that would
416 // require taking the lock.
Elliott Hughes88c5c352012-03-15 18:49:48 -0700417 if (obj == NULL) {
418 return true;
419 }
420 if (!IsAligned<kObjectAlignment>(obj)) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700421 return false;
422 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800423 for (size_t i = 0; i < spaces_.size(); ++i) {
Ian Rogers30fab402012-01-23 15:43:46 -0800424 if (spaces_[i]->Contains(obj)) {
425 return true;
426 }
427 }
428 return false;
Elliott Hughesa2501992011-08-26 19:39:54 -0700429}
430
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700431bool Heap::IsLiveObjectLocked(const Object* obj) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700432 GlobalSynchronization::heap_bitmap_lock_->AssertReaderHeld();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700433 return IsHeapAddress(obj) && GetLiveBitmap()->Test(obj);
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700434}
435
Elliott Hughes3e465b12011-09-02 18:26:12 -0700436#if VERIFY_OBJECT_ENABLED
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700437void Heap::VerifyObject(const Object* obj) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700438 if (obj == NULL || this == NULL || !verify_objects_ || Runtime::Current()->IsShuttingDown() ||
Ian Rogers141d6222012-04-05 12:23:06 -0700439 Thread::Current() == NULL ||
jeffhao25045522012-03-13 19:34:37 -0700440 Runtime::Current()->GetThreadList()->GetLockOwner() == Thread::Current()->GetTid()) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700441 return;
442 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700443 VerifyObjectBody(obj);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700444}
445#endif
446
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700447void Heap::DumpSpaces() {
448 // TODO: C++0x auto
449 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700450 Space* space = *it;
451 LOG(INFO) << *space;
452 LOG(INFO) << *space->GetLiveBitmap();
453 LOG(INFO) << *space->GetMarkBitmap();
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700454 }
455}
456
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700457// We want to avoid bit rotting.
458void Heap::VerifyObjectBody(const Object* obj) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700459 if (!IsAligned<kObjectAlignment>(obj)) {
460 LOG(FATAL) << "Object isn't aligned: " << obj;
461 } else if (!GetLiveBitmap()->Test(obj)) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700462 DumpSpaces();
463 LOG(FATAL) << "Object is dead: " << obj;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700464 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700465
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700466 // Ignore early dawn of the universe verifications
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700467 if (!VERIFY_OBJECT_FAST && num_objects_allocated_ > 10) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700468 const byte* raw_addr = reinterpret_cast<const byte*>(obj) +
469 Object::ClassOffset().Int32Value();
470 const Class* c = *reinterpret_cast<Class* const *>(raw_addr);
471 if (c == NULL) {
472 LOG(FATAL) << "Null class in object: " << obj;
473 } else if (!IsAligned<kObjectAlignment>(c)) {
474 LOG(FATAL) << "Class isn't aligned: " << c << " in object: " << obj;
475 } else if (!GetLiveBitmap()->Test(c)) {
476 LOG(FATAL) << "Class of object is dead: " << c << " in object: " << obj;
477 }
478 // Check obj.getClass().getClass() == obj.getClass().getClass().getClass()
479 // Note: we don't use the accessors here as they have internal sanity checks
480 // that we don't want to run
481 raw_addr = reinterpret_cast<const byte*>(c) + Object::ClassOffset().Int32Value();
482 const Class* c_c = *reinterpret_cast<Class* const *>(raw_addr);
483 raw_addr = reinterpret_cast<const byte*>(c_c) + Object::ClassOffset().Int32Value();
484 const Class* c_c_c = *reinterpret_cast<Class* const *>(raw_addr);
485 CHECK_EQ(c_c, c_c_c);
486 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700487}
488
Brian Carlstrom78128a62011-09-15 17:21:19 -0700489void Heap::VerificationCallback(Object* obj, void* arg) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700490 DCHECK(obj != NULL);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700491 reinterpret_cast<Heap*>(arg)->VerifyObjectBody(obj);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700492}
493
494void Heap::VerifyHeap() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700495 ReaderMutexLock mu(*GlobalSynchronization::heap_bitmap_lock_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700496 GetLiveBitmap()->Walk(Heap::VerificationCallback, this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700497}
498
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700499void Heap::RecordAllocation(AllocSpace* space, const Object* obj) {
500 {
501 MutexLock mu(*statistics_lock_);
502 size_t size = space->AllocationSize(obj);
503 DCHECK_GT(size, 0u);
504 num_bytes_allocated_ += size;
505 num_objects_allocated_ += 1;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700506
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700507 if (Runtime::Current()->HasStatsEnabled()) {
508 RuntimeStats* global_stats = Runtime::Current()->GetStats();
509 RuntimeStats* thread_stats = Thread::Current()->GetStats();
510 ++global_stats->allocated_objects;
511 ++thread_stats->allocated_objects;
512 global_stats->allocated_bytes += size;
513 thread_stats->allocated_bytes += size;
514 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700515 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700516
517 DCHECK(obj);
518
519 allocation_stack_->AtomicPush(obj);
520#if VERIFY_OBJECT_ENABLED
521 WriterMutexLock mu(*GlobalSynchronization::heap_bitmap_lock_);
522 // Verify objects doesn't like objects in allocation stack not being marked as live.
523 live_bitmap_->Set(obj);
524#endif
Carl Shapiro58551df2011-07-24 03:09:51 -0700525}
526
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700527void Heap::RecordFree(size_t freed_objects, size_t freed_bytes) {
528 MutexLock mu(*statistics_lock_);
Elliott Hughes307f75d2011-10-12 18:04:40 -0700529
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700530 DCHECK_LE(freed_objects, num_objects_allocated_);
531 num_objects_allocated_ -= freed_objects;
532
533 DCHECK_LE(freed_bytes, num_bytes_allocated_);
534 num_bytes_allocated_ -= freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700535
536 if (Runtime::Current()->HasStatsEnabled()) {
537 RuntimeStats* global_stats = Runtime::Current()->GetStats();
538 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700539 global_stats->freed_objects += freed_objects;
540 thread_stats->freed_objects += freed_objects;
Elliott Hughes307f75d2011-10-12 18:04:40 -0700541 global_stats->freed_bytes += freed_bytes;
542 thread_stats->freed_bytes += freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700543 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700544}
545
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700546Object* Heap::Allocate(size_t size) {
547 Object* obj = Allocate(alloc_space_, size);
Carl Shapiro58551df2011-07-24 03:09:51 -0700548 if (obj != NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700549 RecordAllocation(alloc_space_, obj);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700550 return obj;
Carl Shapiro58551df2011-07-24 03:09:51 -0700551 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700552
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700553 return NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700554}
555
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700556Object* Heap::Allocate(AllocSpace* space, size_t alloc_size) {
557 Thread* self = Thread::Current();
Ian Rogers0399dde2012-06-06 17:09:28 -0700558 // Since allocation can cause a GC which will need to SuspendAll, make sure all allocations are
559 // done in the runnable state where suspension is expected.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700560#ifndef NDEBUG
561 {
562 MutexLock mu(*GlobalSynchronization::thread_suspend_count_lock_);
563 CHECK_EQ(self->GetState(), kRunnable);
564 }
565 self->AssertThreadSuspensionIsAllowable();
566#endif
Brian Carlstromb82b6872011-10-26 17:18:07 -0700567
Ian Rogers30fab402012-01-23 15:43:46 -0800568 Object* ptr = space->AllocWithoutGrowth(alloc_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700569 if (ptr != NULL) {
570 return ptr;
571 }
572
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700573 // The allocation failed. If the GC is running, block until it completes else request a
574 // foreground partial collection.
575 if (!WaitForConcurrentGcToComplete()) {
576 // No concurrent GC so perform a foreground collection.
577 if (Runtime::Current()->HasStatsEnabled()) {
578 ++Runtime::Current()->GetStats()->gc_for_alloc_count;
579 ++Thread::Current()->GetStats()->gc_for_alloc_count;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700580 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700581 self->TransitionFromRunnableToSuspended(kWaitingPerformingGc);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700582 CollectGarbageInternal(have_zygote_space_ ? GC_PARTIAL : GC_FULL, false);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700583 self->TransitionFromSuspendedToRunnable();
Carl Shapiro69759ea2011-07-21 18:13:35 -0700584 }
585
Ian Rogers30fab402012-01-23 15:43:46 -0800586 ptr = space->AllocWithoutGrowth(alloc_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700587 if (ptr != NULL) {
588 return ptr;
589 }
590
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700591 const size_t alloc_space_size = alloc_space_->Size();
592 if (alloc_space_size > kMinAllocSpaceSizeForStickyGC &&
593 alloc_space_->Capacity() - alloc_space_size < kMinRemainingSpaceForStickyGC) {
594 // Partial GC didn't free enough memory, try a full GC.
595 if (Runtime::Current()->HasStatsEnabled()) {
596 ++Runtime::Current()->GetStats()->gc_for_alloc_count;
597 ++Thread::Current()->GetStats()->gc_for_alloc_count;
598 }
599
600 // Don't bother trying a young GC unless we have a few MB AllocSpace.
601 self->TransitionFromRunnableToSuspended(kWaitingPerformingGc);
602 CollectGarbageInternal(GC_STICKY, false);
603 self->TransitionFromSuspendedToRunnable();
604
605 ptr = space->AllocWithoutGrowth(alloc_size);
606 if (ptr != NULL) {
607 return ptr;
608 }
609 }
610
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700611 if (!have_zygote_space_) {
612 // Partial GC didn't free enough memory, try a full GC.
613 if (Runtime::Current()->HasStatsEnabled()) {
614 ++Runtime::Current()->GetStats()->gc_for_alloc_count;
615 ++Thread::Current()->GetStats()->gc_for_alloc_count;
616 }
617 self->TransitionFromRunnableToSuspended(kWaitingPerformingGc);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700618 CollectGarbageInternal(GC_PARTIAL, false);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700619 self->TransitionFromSuspendedToRunnable();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700620
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700621 ptr = space->AllocWithoutGrowth(alloc_size);
622 if (ptr != NULL) {
623 return ptr;
624 }
625 }
626
627 // Allocations have failed after GCs; this is an exceptional state.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700628 // Try harder, growing the heap if necessary.
Ian Rogers30fab402012-01-23 15:43:46 -0800629 ptr = space->AllocWithGrowth(alloc_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700630 if (ptr != NULL) {
Ian Rogers30fab402012-01-23 15:43:46 -0800631 size_t new_footprint = space->GetFootprintLimit();
Elliott Hughes418dfe72011-10-06 18:56:27 -0700632 // OLD-TODO: may want to grow a little bit more so that the amount of
Carl Shapiro58551df2011-07-24 03:09:51 -0700633 // free space is equal to the old free space + the
634 // utilization slop for the new allocation.
Ian Rogers3bb17a62012-01-27 23:56:44 -0800635 VLOG(gc) << "Grow heap (frag case) to " << PrettySize(new_footprint)
Ian Rogers162a31c2012-01-31 16:14:31 -0800636 << " for a " << PrettySize(alloc_size) << " allocation";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700637 return ptr;
638 }
639
Elliott Hughes81ff3182012-03-23 20:35:56 -0700640 // Most allocations should have succeeded by now, so the heap is really full, really fragmented,
641 // or the requested size is really big. Do another GC, collecting SoftReferences this time. The
642 // VM spec requires that all SoftReferences have been collected and cleared before throwing OOME.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700643
Elliott Hughes418dfe72011-10-06 18:56:27 -0700644 // OLD-TODO: wait for the finalizers from the previous GC to finish
Ian Rogers3bb17a62012-01-27 23:56:44 -0800645 VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size) << " allocation";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700646
647 if (Runtime::Current()->HasStatsEnabled()) {
648 ++Runtime::Current()->GetStats()->gc_for_alloc_count;
649 ++Thread::Current()->GetStats()->gc_for_alloc_count;
650 }
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -0700651 // We don't need a WaitForConcurrentGcToComplete here either.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700652 self->TransitionFromRunnableToSuspended(kWaitingPerformingGc);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700653 CollectGarbageInternal(GC_FULL, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700654 self->TransitionFromSuspendedToRunnable();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700655 return space->AllocWithGrowth(alloc_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700656}
657
Elliott Hughesbf86d042011-08-31 17:53:14 -0700658int64_t Heap::GetMaxMemory() {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700659 size_t total = 0;
660 // TODO: C++0x auto
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700661 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
662 Space* space = *it;
663 if (space->IsAllocSpace()) {
664 total += space->AsAllocSpace()->Capacity();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700665 }
666 }
667 return total;
Elliott Hughesbf86d042011-08-31 17:53:14 -0700668}
669
670int64_t Heap::GetTotalMemory() {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700671 return GetMaxMemory();
Elliott Hughesbf86d042011-08-31 17:53:14 -0700672}
673
674int64_t Heap::GetFreeMemory() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700675 MutexLock mu(*statistics_lock_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700676 return GetMaxMemory() - num_bytes_allocated_;
Elliott Hughesbf86d042011-08-31 17:53:14 -0700677}
678
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700679class InstanceCounter {
680 public:
681 InstanceCounter(Class* c, bool count_assignable)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700682 SHARED_LOCKS_REQUIRED(GlobalSynchronization::mutator_lock_)
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700683 : class_(c), count_assignable_(count_assignable), count_(0) {
684 }
685
686 size_t GetCount() {
687 return count_;
688 }
689
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700690 static void Callback(Object* o, void* arg)
691 SHARED_LOCKS_REQUIRED(GlobalSynchronization::mutator_lock_) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700692 reinterpret_cast<InstanceCounter*>(arg)->VisitInstance(o);
693 }
694
695 private:
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700696 void VisitInstance(Object* o) SHARED_LOCKS_REQUIRED(GlobalSynchronization::mutator_lock_) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700697 Class* instance_class = o->GetClass();
698 if (count_assignable_) {
699 if (instance_class == class_) {
700 ++count_;
701 }
702 } else {
703 if (instance_class != NULL && class_->IsAssignableFrom(instance_class)) {
704 ++count_;
705 }
706 }
707 }
708
709 Class* class_;
710 bool count_assignable_;
711 size_t count_;
712};
713
714int64_t Heap::CountInstances(Class* c, bool count_assignable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700715 ReaderMutexLock mu(*GlobalSynchronization::heap_bitmap_lock_);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700716 InstanceCounter counter(c, count_assignable);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700717 GetLiveBitmap()->Walk(InstanceCounter::Callback, &counter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700718 return counter.GetCount();
719}
720
Ian Rogers30fab402012-01-23 15:43:46 -0800721void Heap::CollectGarbage(bool clear_soft_references) {
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -0700722 // If we just waited for a GC to complete then we do not need to do another
723 // GC unless we clear soft references.
724 if (!WaitForConcurrentGcToComplete() || clear_soft_references) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700725 ScopedThreadStateChange tsc(Thread::Current(), kWaitingPerformingGc);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700726 CollectGarbageInternal(have_zygote_space_ ? GC_PARTIAL : GC_FULL, clear_soft_references);
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -0700727 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700728}
729
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700730void Heap::PreZygoteFork() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700731 static Mutex zygote_creation_lock_("zygote creation lock", kZygoteCreationLock);
732 MutexLock mu(zygote_creation_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700733
734 // Try to see if we have any Zygote spaces.
735 if (have_zygote_space_) {
736 return;
737 }
738
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700739 VLOG(heap) << "Starting PreZygoteFork with alloc space size " << PrettySize(alloc_space_->Size());
740
741 {
742 // Flush the alloc stack.
743 WriterMutexLock mu(*GlobalSynchronization::heap_bitmap_lock_);
744 FlushAllocStack();
745 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700746
747 // Replace the first alloc space we find with a zygote space.
748 // TODO: C++0x auto
749 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
750 if ((*it)->IsAllocSpace()) {
751 AllocSpace* zygote_space = (*it)->AsAllocSpace();
752
753 // Turns the current alloc space into a Zygote space and obtain the new alloc space composed
754 // of the remaining available heap memory.
755 alloc_space_ = zygote_space->CreateZygoteSpace();
756
757 // Change the GC retention policy of the zygote space to only collect when full.
758 zygote_space->SetGcRetentionPolicy(GCRP_FULL_COLLECT);
759 AddSpace(alloc_space_);
760 have_zygote_space_ = true;
761 break;
762 }
763 }
764}
765
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700766void Heap::FlushAllocStack() {
767 MarkStackAsLive(allocation_stack_.get());
768 allocation_stack_->Reset();
769}
770
771void Heap::MarkStackAsLive(MarkStack* alloc_stack) {
772 // We can just assume everything is inside the alloc_space_'s bitmap since we should only have
773 // fresh allocations.
774 SpaceBitmap* live_bitmap = alloc_space_->GetLiveBitmap();
775
776 // Empty the allocation stack.
777 const size_t count = alloc_stack->Size();
778 for (size_t i = 0; i < count; ++i) {
779 const Object* obj = alloc_stack->Get(i);
780 DCHECK(obj != NULL);
781 live_bitmap->Set(obj);
782 }
783}
784
785void Heap::UnMarkStack(MarkStack* alloc_stack) {
786 SpaceBitmap* mark_bitmap = alloc_space_->GetMarkBitmap();
787
788 // Clear all of the things in the AllocStack.
789 size_t count = alloc_stack->Size();
790 for (size_t i = 0;i < count;++i) {
791 const Object* obj = alloc_stack->Get(i);
792 DCHECK(obj != NULL);
793 if (mark_bitmap->Test(obj)) {
794 mark_bitmap->Clear(obj);
795 }
796 }
797}
798
799void Heap::CollectGarbageInternal(GcType gc_type, bool clear_soft_references) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700800 GlobalSynchronization::mutator_lock_->AssertNotHeld();
801#ifndef NDEBUG
802 {
803 MutexLock mu(*GlobalSynchronization::thread_suspend_count_lock_);
804 CHECK_EQ(Thread::Current()->GetState(), kWaitingPerformingGc);
805 }
806#endif
Carl Shapiro58551df2011-07-24 03:09:51 -0700807
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700808 // Ensure there is only one GC at a time.
809 bool start_collect = false;
810 while (!start_collect) {
811 {
812 MutexLock mu(*gc_complete_lock_);
813 if (!is_gc_running_) {
814 is_gc_running_ = true;
815 start_collect = true;
816 }
817 }
818 if (!start_collect) {
819 WaitForConcurrentGcToComplete();
820 // TODO: if another thread beat this one to do the GC, perhaps we should just return here?
821 // Not doing at the moment to ensure soft references are cleared.
822 }
823 }
824 gc_complete_lock_->AssertNotHeld();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700825
826 // We need to do partial GCs every now and then to avoid the heap growing too much and
827 // fragmenting.
828 if (gc_type == GC_STICKY && ++sticky_gc_count_ > kPartialGCFrequency) {
829 gc_type = GC_PARTIAL;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700830 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700831 if (gc_type != GC_STICKY) {
832 sticky_gc_count_ = 0;
833 }
834
835 uint64_t start_time = NanoTime();
836 if (true || concurrent_gc_) {
837 CollectGarbageConcurrentMarkSweepPlan(gc_type, clear_soft_references);
838 } else {
839 CollectGarbageMarkSweepPlan(gc_type, clear_soft_references);
840 }
841 const uint64_t gc_duration = NanoTime() - start_time;
842 // For particularly slow GCs lets print out another warning.
843 if (gc_duration > MsToNs(100)) {
844 LOG(WARNING) << "Slow GC took " << PrettyDuration(gc_duration);
845 }
846
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700847 gc_complete_lock_->AssertNotHeld();
848 MutexLock mu(*gc_complete_lock_);
849 is_gc_running_ = false;
850 // Wake anyone who may have been waiting for the GC to complete.
851 gc_complete_cond_->Broadcast();
852}
Mathieu Chartiera6399032012-06-11 18:49:50 -0700853
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700854void Heap::CollectGarbageMarkSweepPlan(GcType gc_type, bool clear_soft_references) {
855 TimingLogger timings("CollectGarbageInternal", true);
Mathieu Chartier662618f2012-06-06 12:01:47 -0700856
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700857 // Suspend all threads are get exclusive access to the heap.
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700858 uint64_t start_time = NanoTime();
Elliott Hughes8d768a92011-09-14 16:35:25 -0700859 ThreadList* thread_list = Runtime::Current()->GetThreadList();
860 thread_list->SuspendAll();
Mathieu Chartier662618f2012-06-06 12:01:47 -0700861 timings.AddSplit("SuspendAll");
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700862 GlobalSynchronization::mutator_lock_->AssertExclusiveHeld();
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700863
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700864 size_t bytes_freed = 0;
Elliott Hughesadb460d2011-10-05 17:02:34 -0700865 Object* cleared_references = NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700866 {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700867 MarkSweep mark_sweep(mark_stack_.get());
Carl Shapiro58551df2011-07-24 03:09:51 -0700868
869 mark_sweep.Init();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700870 timings.AddSplit("Init");
Carl Shapiro58551df2011-07-24 03:09:51 -0700871
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700872 // Make sure that the tables have the correct pointer for the mark sweep.
873 mod_union_table_->Init(&mark_sweep);
874 zygote_mod_union_table_->Init(&mark_sweep);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700875
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700876 // Swap allocation stack and live stack, enabling us to have new allocations during this GC.
877 MarkStack* temp = allocation_stack_.release();
878 allocation_stack_.reset(live_stack_.release());
879 live_stack_.reset(temp);
880
881 // We will need to know which cards were dirty for doing concurrent processing of dirty cards.
882 // TODO: Investigate using a mark stack instead of a vector.
883 std::vector<byte*> dirty_cards;
884 if (gc_type == GC_STICKY) {
885 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
886 card_table_->GetDirtyCards(*it, dirty_cards);
887 }
888 }
889
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700890 // Clear image space cards and keep track of cards we cleared in the mod-union table.
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700891 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
892 Space* space = *it;
893 if (space->IsImageSpace()) {
894 mod_union_table_->ClearCards(*it);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700895 timings.AddSplit("ClearModUnionCards");
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700896 } else if (space->GetGcRetentionPolicy() == GCRP_FULL_COLLECT) {
897 zygote_mod_union_table_->ClearCards(space);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700898 timings.AddSplit("ClearZygoteCards");
899 } else {
900 card_table_->ClearSpaceCards(space);
901 timings.AddSplit("ClearCards");
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700902 }
903 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700904
905#if VERIFY_MOD_UNION
906 mod_union_table_->Verify();
907 zygote_mod_union_table_->Verify();
908#endif
909
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700910 WriterMutexLock mu(*GlobalSynchronization::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700911 if (gc_type == GC_PARTIAL) {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700912 // Copy the mark bits over from the live bits, do this as early as possible or else we can
913 // accidentally un-mark roots.
914 // Needed for scanning dirty objects.
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700915 for (Spaces::iterator it = spaces_.begin();it != spaces_.end(); ++it) {
916 if ((*it)->GetGcRetentionPolicy() == GCRP_FULL_COLLECT) {
917 mark_sweep.CopyMarkBits(*it);
918 }
919 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700920 timings.AddSplit("CopyMarkBits");
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700921
922 // We can assume that everything < alloc_space_ start is marked at this point.
923 mark_sweep.SetCondemned(reinterpret_cast<Object*>(alloc_space_->Begin()));
924 } else if (gc_type == GC_STICKY) {
925 for (Spaces::iterator it = spaces_.begin();it != spaces_.end(); ++it) {
926 if ((*it)->GetGcRetentionPolicy() != GCRP_NEVER_COLLECT) {
927 mark_sweep.CopyMarkBits(*it);
928 }
929 }
930 timings.AddSplit("CopyMarkBits");
931
932 if (VERIFY_OBJECT_ENABLED) {
933 UnMarkStack(live_stack_.get());
934 }
935
936 mark_sweep.SetCondemned(reinterpret_cast<Object*>(alloc_space_->Begin()));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700937 }
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700938
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700939 MarkStackAsLive(live_stack_.get());
940
Carl Shapiro58551df2011-07-24 03:09:51 -0700941 mark_sweep.MarkRoots();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700942 timings.AddSplit("MarkRoots");
Carl Shapiro58551df2011-07-24 03:09:51 -0700943
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700944 // Roots are marked on the bitmap and the mark_stack is empty.
Ian Rogers5d76c432011-10-31 21:42:49 -0700945 DCHECK(mark_sweep.IsMarkStackEmpty());
Carl Shapiro58551df2011-07-24 03:09:51 -0700946
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700947 // Update zygote mod union table.
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700948 zygote_mod_union_table_->Update();
949 timings.AddSplit("UpdateZygoteModUnionTable");
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700950
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700951 zygote_mod_union_table_->MarkReferences();
952 timings.AddSplit("ZygoteMarkReferences");
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700953
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700954 // Processes the cards we cleared earlier and adds their objects into the mod-union table.
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700955 mod_union_table_->Update();
Mathieu Chartiere6e06512012-06-26 15:00:26 -0700956 timings.AddSplit("UpdateModUnionTable");
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700957
958 // Scans all objects in the mod-union table.
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700959 mod_union_table_->MarkReferences();
Mathieu Chartiere6e06512012-06-26 15:00:26 -0700960 timings.AddSplit("MarkImageToAllocSpaceReferences");
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700961
962 // Recursively mark all the non-image bits set in the mark bitmap.
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700963 if (gc_type != GC_STICKY) {
964 live_stack_->Reset();
965 mark_sweep.RecursiveMark(gc_type == GC_PARTIAL, timings);
966 } else {
967 mark_sweep.RecursiveMarkCards(card_table_.get(), dirty_cards, timings);
968 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700969
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700970 // Need to process references the swap since it uses IsMarked.
Ian Rogers30fab402012-01-23 15:43:46 -0800971 mark_sweep.ProcessReferences(clear_soft_references);
Elliott Hughes307f75d2011-10-12 18:04:40 -0700972 timings.AddSplit("ProcessReferences");
Carl Shapiro58551df2011-07-24 03:09:51 -0700973
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700974 // This doesn't work with mutators unpaused for some reason, TODO: Fix.
975 mark_sweep.SweepSystemWeaks(false);
976 timings.AddSplit("SweepSystemWeaks");
977
978 // Need to swap for VERIFY_OBJECT_ENABLED since we put things in the live bitmap after they
979 // have been allocated.
980 const bool swap = true;
981
982 if (swap) {
983 // Swap the live and mark bitmaps for each alloc space. This is needed since sweep re-swaps
984 // these bitmaps. Doing this enables us to sweep with the heap unlocked since new allocations
985 // set the live bit, but since we have the bitmaps reversed at this point, this sets the mark bit
986 // instead, resulting in no new allocated objects being incorrectly freed by sweep.
987 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
988 Space* space = *it;
989 // We only allocate into AllocSpace, so we only need to swap AllocSpaces.
990 if (space->GetGcRetentionPolicy() == GCRP_ALWAYS_COLLECT) {
991 live_bitmap_->ReplaceBitmap(space->GetLiveBitmap(), space->GetMarkBitmap());
992 mark_bitmap_->ReplaceBitmap(space->GetMarkBitmap(), space->GetLiveBitmap());
993 space->AsAllocSpace()->SwapBitmaps();
994 }
Mathieu Chartier654d3a22012-07-11 17:54:18 -0700995 }
996 }
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700997
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700998#ifndef NDEBUG
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700999 // Verify that we only reach marked objects from the image space
1000 mark_sweep.VerifyImageRoots();
1001 timings.AddSplit("VerifyImageRoots");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001002#endif
Carl Shapiro58551df2011-07-24 03:09:51 -07001003
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001004 if (gc_type != GC_STICKY) {
1005 mark_sweep.Sweep(gc_type == GC_PARTIAL, swap);
1006 } else {
1007 mark_sweep.SweepArray(timings, live_stack_.get(), swap);
1008 }
Elliott Hughes307f75d2011-10-12 18:04:40 -07001009 timings.AddSplit("Sweep");
Elliott Hughesadb460d2011-10-05 17:02:34 -07001010
1011 cleared_references = mark_sweep.GetClearedReferences();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001012 bytes_freed = mark_sweep.GetFreedBytes();
Carl Shapiro58551df2011-07-24 03:09:51 -07001013 }
1014
1015 GrowForUtilization();
Elliott Hughes307f75d2011-10-12 18:04:40 -07001016 timings.AddSplit("GrowForUtilization");
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001017
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001018 thread_list->ResumeAll();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001019 timings.AddSplit("ResumeAll");
Elliott Hughesadb460d2011-10-05 17:02:34 -07001020
1021 EnqueueClearedReferences(&cleared_references);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001022 RequestHeapTrim();
Mathieu Chartier662618f2012-06-06 12:01:47 -07001023 timings.AddSplit("Finish");
Elliott Hughes83df2ac2011-10-11 16:37:54 -07001024
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001025 // If the GC was slow, then print timings in the log.
1026 uint64_t duration = (NanoTime() - start_time) / 1000 * 1000;
1027 if (duration > MsToNs(50)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001028 MutexLock mu(*statistics_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001029 LOG(INFO) << (gc_type == GC_PARTIAL ? "Partial " : (gc_type == GC_STICKY ? "Sticky " : ""))
1030 << "GC freed " << PrettySize(bytes_freed) << ", " << GetPercentFree() << "% free, "
1031 << PrettySize(num_bytes_allocated_) << "/" << PrettySize(GetTotalMemory()) << ", "
1032 << "paused " << PrettyDuration(duration);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001033 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001034
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001035 if (VLOG_IS_ON(heap)) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001036 timings.Dump();
1037 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001038}
Mathieu Chartiera6399032012-06-11 18:49:50 -07001039
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001040void Heap::CollectGarbageConcurrentMarkSweepPlan(GcType gc_type, bool clear_soft_references) {
1041 TimingLogger timings("ConcurrentCollectGarbageInternal", true);
1042 uint64_t root_begin = NanoTime(), root_end = 0, dirty_begin = 0, dirty_end = 0;
Mathieu Chartiera6399032012-06-11 18:49:50 -07001043
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001044 // Suspend all threads are get exclusive access to the heap.
1045 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1046 thread_list->SuspendAll();
1047 timings.AddSplit("SuspendAll");
1048 GlobalSynchronization::mutator_lock_->AssertExclusiveHeld();
1049
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001050 size_t bytes_freed = 0;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001051 Object* cleared_references = NULL;
1052 {
1053 MarkSweep mark_sweep(mark_stack_.get());
1054 timings.AddSplit("ctor");
1055
1056 mark_sweep.Init();
1057 timings.AddSplit("Init");
1058
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001059 // Swap the stacks, this is safe sunce all the mutators are suspended at this point.
1060 MarkStack* temp = allocation_stack_.release();
1061 allocation_stack_.reset(live_stack_.release());
1062 live_stack_.reset(temp);
1063
1064 // We will need to know which cards were dirty for doing concurrent processing of dirty cards.
1065 // TODO: Investigate using a mark stack instead of a vector.
1066 std::vector<byte*> dirty_cards;
1067 if (gc_type == GC_STICKY) {
1068 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1069 card_table_->GetDirtyCards(*it, dirty_cards);
1070 }
1071 }
1072
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001073 // Make sure that the tables have the correct pointer for the mark sweep.
1074 mod_union_table_->Init(&mark_sweep);
1075 zygote_mod_union_table_->Init(&mark_sweep);
1076
1077 // Clear image space cards and keep track of cards we cleared in the mod-union table.
1078 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1079 Space* space = *it;
1080 if (space->IsImageSpace()) {
1081 mod_union_table_->ClearCards(*it);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001082 timings.AddSplit("ModUnionClearCards");
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001083 } else if (space->GetGcRetentionPolicy() == GCRP_FULL_COLLECT) {
1084 zygote_mod_union_table_->ClearCards(space);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001085 timings.AddSplit("ZygoteModUnionClearCards");
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001086 } else {
1087 card_table_->ClearSpaceCards(space);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001088 timings.AddSplit("ClearCards");
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001089 }
1090 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001091
1092#if VERIFY_MOD_UNION
1093 mod_union_table_->Verify();
1094 zygote_mod_union_table_->Verify();
1095#endif
1096
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001097
1098 {
1099 WriterMutexLock mu(*GlobalSynchronization::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001100
1101 if (gc_type == GC_PARTIAL) {
1102 // Copy the mark bits over from the live bits, do this as early as possible or else we can
1103 // accidentally un-mark roots.
1104 // Needed for scanning dirty objects.
1105 for (Spaces::iterator it = spaces_.begin();it != spaces_.end(); ++it) {
1106 if ((*it)->GetGcRetentionPolicy() == GCRP_FULL_COLLECT) {
1107 mark_sweep.CopyMarkBits(*it);
1108 }
1109 }
1110 timings.AddSplit("CopyMarkBits");
1111 mark_sweep.SetCondemned(reinterpret_cast<Object*>(alloc_space_->Begin()));
1112 } else if (gc_type == GC_STICKY) {
1113 for (Spaces::iterator it = spaces_.begin();it != spaces_.end(); ++it) {
1114 if ((*it)->GetGcRetentionPolicy() != GCRP_NEVER_COLLECT) {
1115 mark_sweep.CopyMarkBits(*it);
1116 }
1117 }
1118 timings.AddSplit("CopyMarkBits");
1119 // We need to unmark the new objects since we marked them as live earlier to avoid verify
1120 // objects failing.
1121 if (VERIFY_OBJECT_ENABLED) {
1122 UnMarkStack(live_stack_.get());
1123 }
1124 mark_sweep.SetCondemned(reinterpret_cast<Object*>(alloc_space_->Begin()));
1125 }
1126
1127 // TODO: Investigate whether or not this is really necessary for sticky mark bits.
1128 MarkStackAsLive(live_stack_.get());
1129
1130 if (gc_type != GC_STICKY) {
1131 live_stack_->Reset();
1132 mark_sweep.MarkRoots();
1133 timings.AddSplit("MarkRoots");
1134 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001135 }
1136
1137 // Roots are marked on the bitmap and the mark_stack is empty.
1138 DCHECK(mark_sweep.IsMarkStackEmpty());
1139
1140 // Allow mutators to go again, acquire share on mutator_lock_ to continue.
1141 thread_list->ResumeAll();
1142 {
1143 ReaderMutexLock reader_lock(*GlobalSynchronization::mutator_lock_);
1144 root_end = NanoTime();
1145 timings.AddSplit("RootEnd");
1146
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001147 WriterMutexLock mu(*GlobalSynchronization::heap_bitmap_lock_);
1148 if (gc_type != GC_STICKY) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001149 // Update zygote mod union table.
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001150 if (gc_type == GC_PARTIAL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001151 zygote_mod_union_table_->Update();
1152 timings.AddSplit("UpdateZygoteModUnionTable");
1153
1154 zygote_mod_union_table_->MarkReferences();
1155 timings.AddSplit("ZygoteMarkReferences");
1156 }
1157
1158 // Processes the cards we cleared earlier and adds their objects into the mod-union table.
1159 mod_union_table_->Update();
1160 timings.AddSplit("UpdateModUnionTable");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001161
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001162 // Scans all objects in the mod-union table.
1163 mod_union_table_->MarkReferences();
1164 timings.AddSplit("MarkImageToAllocSpaceReferences");
1165
1166 // Recursively mark all the non-image bits set in the mark bitmap.
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001167 mark_sweep.RecursiveMark(gc_type == GC_PARTIAL, timings);
1168 } else {
1169 mark_sweep.RecursiveMarkCards(card_table_.get(), dirty_cards, timings);
1170 mark_sweep.DisableFinger();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001171 }
1172 }
1173 // Release share on mutator_lock_ and then get exclusive access.
1174 dirty_begin = NanoTime();
1175 thread_list->SuspendAll();
1176 timings.AddSplit("ReSuspend");
1177 GlobalSynchronization::mutator_lock_->AssertExclusiveHeld();
1178
1179 {
1180 WriterMutexLock mu(*GlobalSynchronization::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001181
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001182 // Re-mark root set.
1183 mark_sweep.ReMarkRoots();
1184 timings.AddSplit("ReMarkRoots");
1185
1186 // Scan dirty objects, this is only required if we are not doing concurrent GC.
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001187 mark_sweep.RecursiveMarkDirtyObjects(false);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001188 timings.AddSplit("RecursiveMarkDirtyObjects");
1189 }
1190 {
1191 ReaderMutexLock mu(*GlobalSynchronization::heap_bitmap_lock_);
1192 mark_sweep.ProcessReferences(clear_soft_references);
1193 timings.AddSplit("ProcessReferences");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001194
1195 // This doesn't work with mutators unpaused for some reason, TODO: Fix.
1196 mark_sweep.SweepSystemWeaks(false);
1197 timings.AddSplit("SweepSystemWeaks");
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001198 }
1199 // Swap the live and mark bitmaps for each alloc space. This is needed since sweep re-swaps
1200 // these bitmaps. Doing this enables us to sweep with the heap unlocked since new allocations
1201 // set the live bit, but since we have the bitmaps reversed at this point, this sets the mark
1202 // bit instead, resulting in no new allocated objects being incorrectly freed by sweep.
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001203 bool swap = true;
1204 if (swap) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001205 WriterMutexLock mu(*GlobalSynchronization::heap_bitmap_lock_);
1206 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1207 Space* space = *it;
1208 // We never allocate into zygote spaces.
1209 if (space->GetGcRetentionPolicy() == GCRP_ALWAYS_COLLECT) {
1210 live_bitmap_->ReplaceBitmap(space->GetLiveBitmap(), space->GetMarkBitmap());
1211 mark_bitmap_->ReplaceBitmap(space->GetMarkBitmap(), space->GetLiveBitmap());
1212 space->AsAllocSpace()->SwapBitmaps();
1213 }
1214 }
1215 }
1216
1217 if (kIsDebugBuild) {
1218 // Verify that we only reach marked objects from the image space.
1219 ReaderMutexLock mu(*GlobalSynchronization::heap_bitmap_lock_);
1220 mark_sweep.VerifyImageRoots();
1221 timings.AddSplit("VerifyImageRoots");
1222 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001223
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001224 thread_list->ResumeAll();
1225 dirty_end = NanoTime();
1226 GlobalSynchronization::mutator_lock_->AssertNotHeld();
1227
1228 {
1229 // TODO: this lock shouldn't be necessary (it's why we did the bitmap flip above).
1230 WriterMutexLock mu(*GlobalSynchronization::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001231 if (gc_type != GC_STICKY) {
1232 mark_sweep.Sweep(gc_type == GC_PARTIAL, swap);
1233 } else {
1234 mark_sweep.SweepArray(timings, live_stack_.get(), swap);
1235 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001236 timings.AddSplit("Sweep");
1237 }
1238
1239 cleared_references = mark_sweep.GetClearedReferences();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001240 bytes_freed = mark_sweep.GetFreedBytes();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001241 }
1242
1243 GrowForUtilization();
1244 timings.AddSplit("GrowForUtilization");
1245
1246 EnqueueClearedReferences(&cleared_references);
1247 RequestHeapTrim();
1248 timings.AddSplit("Finish");
1249
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001250 // If the GC was slow, then print timings in the log.
1251 uint64_t pause_roots = (root_end - root_begin) / 1000 * 1000;
1252 uint64_t pause_dirty = (dirty_end - dirty_begin) / 1000 * 1000;
1253 if (pause_roots > MsToNs(5) || pause_dirty > MsToNs(5)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001254 MutexLock mu(*statistics_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001255 LOG(INFO) << (gc_type == GC_PARTIAL ? "Partial " : (gc_type == GC_STICKY ? "Sticky " : ""))
1256 << "Concurrent GC freed " << PrettySize(bytes_freed) << ", " << GetPercentFree()
1257 << "% free, " << PrettySize(num_bytes_allocated_) << "/"
1258 << PrettySize(GetTotalMemory()) << ", " << "paused " << PrettyDuration(pause_roots)
1259 << "+" << PrettyDuration(pause_dirty);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001260 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001261
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001262 if (VLOG_IS_ON(heap)) {
1263 timings.Dump();
1264 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001265}
1266
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -07001267bool Heap::WaitForConcurrentGcToComplete() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001268 if (concurrent_gc_) {
1269 bool do_wait = false;
1270 uint64_t wait_start;
1271 {
1272 // Check if GC is running holding gc_complete_lock_.
1273 MutexLock mu(*gc_complete_lock_);
1274 if (is_gc_running_) {
1275 wait_start = NanoTime();
1276 do_wait = true;
1277 }
Mathieu Chartiera6399032012-06-11 18:49:50 -07001278 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001279 if (do_wait) {
1280 // We must wait, change thread state then sleep on gc_complete_cond_;
1281 ScopedThreadStateChange tsc(Thread::Current(), kWaitingForGcToComplete);
1282 {
1283 MutexLock mu(*gc_complete_lock_);
1284 while (is_gc_running_) {
1285 gc_complete_cond_->Wait(*gc_complete_lock_);
1286 }
1287 }
1288 uint64_t wait_time = NanoTime() - wait_start;
1289 if (wait_time > MsToNs(5)) {
1290 LOG(INFO) << "WaitForConcurrentGcToComplete blocked for " << PrettyDuration(wait_time);
1291 }
1292 return true;
1293 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001294 }
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -07001295 return false;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001296}
1297
Elliott Hughesc967f782012-04-16 10:23:15 -07001298void Heap::DumpForSigQuit(std::ostream& os) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001299 MutexLock mu(*statistics_lock_);
Elliott Hughesc967f782012-04-16 10:23:15 -07001300 os << "Heap: " << GetPercentFree() << "% free, "
1301 << PrettySize(num_bytes_allocated_) << "/" << PrettySize(GetTotalMemory())
Elliott Hughesae80b492012-04-24 10:43:17 -07001302 << "; " << num_objects_allocated_ << " objects\n";
Elliott Hughesc967f782012-04-16 10:23:15 -07001303}
1304
1305size_t Heap::GetPercentFree() {
1306 size_t total = GetTotalMemory();
1307 return 100 - static_cast<size_t>(100.0f * static_cast<float>(num_bytes_allocated_) / total);
1308}
1309
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001310void Heap::SetIdealFootprint(size_t max_allowed_footprint) {
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001311 AllocSpace* alloc_space = alloc_space_;
1312 // TODO: Behavior for multiple alloc spaces?
1313 size_t alloc_space_capacity = alloc_space->Capacity();
1314 if (max_allowed_footprint > alloc_space_capacity) {
1315 VLOG(gc) << "Clamp target GC heap from " << PrettySize(max_allowed_footprint)
1316 << " to " << PrettySize(alloc_space_capacity);
1317 max_allowed_footprint = alloc_space_capacity;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001318 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001319 alloc_space->SetFootprintLimit(max_allowed_footprint);
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001320}
1321
Ian Rogers3bb17a62012-01-27 23:56:44 -08001322// kHeapIdealFree is the ideal maximum free size, when we grow the heap for utilization.
Shih-wei Liao7f1caab2011-10-06 12:11:04 -07001323static const size_t kHeapIdealFree = 2 * MB;
Ian Rogers3bb17a62012-01-27 23:56:44 -08001324// kHeapMinFree guarantees that you always have at least 512 KB free, when you grow for utilization,
1325// regardless of target utilization ratio.
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001326static const size_t kHeapMinFree = kHeapIdealFree / 4;
1327
Carl Shapiro69759ea2011-07-21 18:13:35 -07001328void Heap::GrowForUtilization() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001329 size_t target_size;
1330 bool use_footprint_limit = false;
1331 {
1332 MutexLock mu(*statistics_lock_);
1333 // We know what our utilization is at this moment.
1334 // This doesn't actually resize any memory. It just lets the heap grow more when necessary.
1335 target_size = num_bytes_allocated_ / Heap::GetTargetHeapUtilization();
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001336
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001337 if (target_size > num_bytes_allocated_ + kHeapIdealFree) {
1338 target_size = num_bytes_allocated_ + kHeapIdealFree;
1339 } else if (target_size < num_bytes_allocated_ + kHeapMinFree) {
1340 target_size = num_bytes_allocated_ + kHeapMinFree;
1341 }
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001342
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001343 // Calculate when to perform the next ConcurrentGC.
1344 if (GetTotalMemory() - num_bytes_allocated_ < concurrent_min_free_) {
1345 // Not enough free memory to perform concurrent GC.
1346 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
1347 } else {
1348 // Compute below to avoid holding both the statistics and the alloc space lock
1349 use_footprint_limit = true;
1350 }
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001351 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001352
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001353 if (use_footprint_limit) {
1354 size_t foot_print_limit = alloc_space_->GetFootprintLimit();
1355 MutexLock mu(*statistics_lock_);
1356 concurrent_start_bytes_ = foot_print_limit - concurrent_start_size_;
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001357 }
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001358 SetIdealFootprint(target_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001359}
1360
jeffhaoc1160702011-10-27 15:48:45 -07001361void Heap::ClearGrowthLimit() {
jeffhaoc1160702011-10-27 15:48:45 -07001362 WaitForConcurrentGcToComplete();
jeffhaoc1160702011-10-27 15:48:45 -07001363 alloc_space_->ClearGrowthLimit();
1364}
1365
Elliott Hughesadb460d2011-10-05 17:02:34 -07001366void Heap::SetReferenceOffsets(MemberOffset reference_referent_offset,
1367 MemberOffset reference_queue_offset,
1368 MemberOffset reference_queueNext_offset,
1369 MemberOffset reference_pendingNext_offset,
1370 MemberOffset finalizer_reference_zombie_offset) {
1371 reference_referent_offset_ = reference_referent_offset;
1372 reference_queue_offset_ = reference_queue_offset;
1373 reference_queueNext_offset_ = reference_queueNext_offset;
1374 reference_pendingNext_offset_ = reference_pendingNext_offset;
1375 finalizer_reference_zombie_offset_ = finalizer_reference_zombie_offset;
1376 CHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1377 CHECK_NE(reference_queue_offset_.Uint32Value(), 0U);
1378 CHECK_NE(reference_queueNext_offset_.Uint32Value(), 0U);
1379 CHECK_NE(reference_pendingNext_offset_.Uint32Value(), 0U);
1380 CHECK_NE(finalizer_reference_zombie_offset_.Uint32Value(), 0U);
1381}
1382
1383Object* Heap::GetReferenceReferent(Object* reference) {
1384 DCHECK(reference != NULL);
1385 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1386 return reference->GetFieldObject<Object*>(reference_referent_offset_, true);
1387}
1388
1389void Heap::ClearReferenceReferent(Object* reference) {
1390 DCHECK(reference != NULL);
1391 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1392 reference->SetFieldObject(reference_referent_offset_, NULL, true);
1393}
1394
1395// Returns true if the reference object has not yet been enqueued.
1396bool Heap::IsEnqueuable(const Object* ref) {
1397 DCHECK(ref != NULL);
1398 const Object* queue = ref->GetFieldObject<Object*>(reference_queue_offset_, false);
1399 const Object* queue_next = ref->GetFieldObject<Object*>(reference_queueNext_offset_, false);
1400 return (queue != NULL) && (queue_next == NULL);
1401}
1402
1403void Heap::EnqueueReference(Object* ref, Object** cleared_reference_list) {
1404 DCHECK(ref != NULL);
1405 CHECK(ref->GetFieldObject<Object*>(reference_queue_offset_, false) != NULL);
1406 CHECK(ref->GetFieldObject<Object*>(reference_queueNext_offset_, false) == NULL);
1407 EnqueuePendingReference(ref, cleared_reference_list);
1408}
1409
1410void Heap::EnqueuePendingReference(Object* ref, Object** list) {
1411 DCHECK(ref != NULL);
1412 DCHECK(list != NULL);
1413
1414 if (*list == NULL) {
1415 ref->SetFieldObject(reference_pendingNext_offset_, ref, false);
1416 *list = ref;
1417 } else {
1418 Object* head = (*list)->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
1419 ref->SetFieldObject(reference_pendingNext_offset_, head, false);
1420 (*list)->SetFieldObject(reference_pendingNext_offset_, ref, false);
1421 }
1422}
1423
1424Object* Heap::DequeuePendingReference(Object** list) {
1425 DCHECK(list != NULL);
1426 DCHECK(*list != NULL);
1427 Object* head = (*list)->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
1428 Object* ref;
1429 if (*list == head) {
1430 ref = *list;
1431 *list = NULL;
1432 } else {
1433 Object* next = head->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
1434 (*list)->SetFieldObject(reference_pendingNext_offset_, next, false);
1435 ref = head;
1436 }
1437 ref->SetFieldObject(reference_pendingNext_offset_, NULL, false);
1438 return ref;
1439}
1440
Ian Rogers5d4bdc22011-11-02 22:15:43 -07001441void Heap::AddFinalizerReference(Thread* self, Object* object) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001442 ScopedObjectAccess soa(self);
Elliott Hughes77405792012-03-15 15:22:12 -07001443 JValue args[1];
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07001444 args[0].SetL(object);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001445 soa.DecodeMethod(WellKnownClasses::java_lang_ref_FinalizerReference_add)->Invoke(self,
1446 NULL, args, NULL);
1447}
1448
1449size_t Heap::GetBytesAllocated() const {
1450 MutexLock mu(*statistics_lock_);
1451 return num_bytes_allocated_;
1452}
1453
1454size_t Heap::GetObjectsAllocated() const {
1455 MutexLock mu(*statistics_lock_);
1456 return num_objects_allocated_;
1457}
1458
1459size_t Heap::GetConcurrentStartSize() const {
1460 MutexLock mu(*statistics_lock_);
1461 return concurrent_start_size_;
1462}
1463
1464size_t Heap::GetConcurrentMinFree() const {
1465 MutexLock mu(*statistics_lock_);
1466 return concurrent_min_free_;
Elliott Hughesadb460d2011-10-05 17:02:34 -07001467}
1468
1469void Heap::EnqueueClearedReferences(Object** cleared) {
1470 DCHECK(cleared != NULL);
1471 if (*cleared != NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001472 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes77405792012-03-15 15:22:12 -07001473 JValue args[1];
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07001474 args[0].SetL(*cleared);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001475 soa.DecodeMethod(WellKnownClasses::java_lang_ref_ReferenceQueue_add)->Invoke(soa.Self(),
1476 NULL, args, NULL);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001477 *cleared = NULL;
1478 }
1479}
1480
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001481void Heap::RequestConcurrentGC() {
Mathieu Chartier069387a2012-06-18 12:01:01 -07001482 // Make sure that we can do a concurrent GC.
1483 if (requesting_gc_ ||
1484 !Runtime::Current()->IsFinishedStarting() ||
1485 Runtime::Current()->IsShuttingDown() ||
1486 !Runtime::Current()->IsConcurrentGcEnabled()) {
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001487 return;
1488 }
1489
1490 requesting_gc_ = true;
1491 JNIEnv* env = Thread::Current()->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07001492 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
1493 DCHECK(WellKnownClasses::java_lang_Daemons_requestGC != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001494 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
1495 WellKnownClasses::java_lang_Daemons_requestGC);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001496 CHECK(!env->ExceptionCheck());
1497 requesting_gc_ = false;
1498}
1499
1500void Heap::ConcurrentGC() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001501 if (Runtime::Current()->IsShuttingDown() || !concurrent_gc_) {
Mathieu Chartier2542d662012-06-21 17:14:11 -07001502 return;
1503 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001504
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001505 // TODO: We shouldn't need a WaitForConcurrentGcToComplete here since only
1506 // concurrent GC resumes threads before the GC is completed and this function
1507 // is only called within the GC daemon thread.
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001508 if (!WaitForConcurrentGcToComplete()) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001509 // Start a concurrent GC as one wasn't in progress
1510 ScopedThreadStateChange tsc(Thread::Current(), kWaitingPerformingGc);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001511 if (alloc_space_->Size() > kMinAllocSpaceSizeForStickyGC) {
1512 CollectGarbageInternal(GC_STICKY, false);
1513 } else {
1514 CollectGarbageInternal(GC_PARTIAL, false);
1515 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001516 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001517}
1518
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001519void Heap::Trim(AllocSpace* alloc_space) {
Mathieu Chartiera6399032012-06-11 18:49:50 -07001520 WaitForConcurrentGcToComplete();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001521 alloc_space->Trim();
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001522}
1523
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001524void Heap::RequestHeapTrim() {
1525 // We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
1526 // because that only marks object heads, so a large array looks like lots of empty space. We
1527 // don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
1528 // to utilization (which is probably inversely proportional to how much benefit we can expect).
1529 // We could try mincore(2) but that's only a measure of how many pages we haven't given away,
1530 // not how much use we're making of those pages.
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001531 uint64_t ms_time = NsToMs(NanoTime());
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001532 {
1533 MutexLock mu(*statistics_lock_);
1534 float utilization = static_cast<float>(num_bytes_allocated_) / alloc_space_->Size();
1535 if ((utilization > 0.75f) || ((ms_time - last_trim_time_) < 2 * 1000)) {
1536 // Don't bother trimming the heap if it's more than 75% utilized, or if a
1537 // heap trim occurred in the last two seconds.
1538 return;
1539 }
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001540 }
Mathieu Chartiera6399032012-06-11 18:49:50 -07001541 if (!Runtime::Current()->IsFinishedStarting() || Runtime::Current()->IsShuttingDown()) {
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001542 // Heap trimming isn't supported without a Java runtime or Daemons (such as at dex2oat time)
Mathieu Chartiera6399032012-06-11 18:49:50 -07001543 // Also: we do not wish to start a heap trim if the runtime is shutting down.
Ian Rogerse1d490c2012-02-03 09:09:07 -08001544 return;
1545 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001546 last_trim_time_ = ms_time;
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001547 JNIEnv* env = Thread::Current()->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07001548 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
1549 DCHECK(WellKnownClasses::java_lang_Daemons_requestHeapTrim != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001550 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
1551 WellKnownClasses::java_lang_Daemons_requestHeapTrim);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001552 CHECK(!env->ExceptionCheck());
1553}
1554
Carl Shapiro69759ea2011-07-21 18:13:35 -07001555} // namespace art