blob: 2f7e519b06f7df4a00a7b8b3a6cd7a9f3c0a2821 [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
Mathieu Chartier637e3482012-08-17 10:41:32 -070025#include "atomic.h"
Ian Rogers5d76c432011-10-31 21:42:49 -070026#include "card_table.h"
Elliott Hughes767a1472011-10-26 18:49:02 -070027#include "debugger.h"
Mathieu Chartiercc236d72012-07-20 10:29:05 -070028#include "heap_bitmap.h"
Brian Carlstrom9cff8e12011-08-18 16:47:29 -070029#include "image.h"
Carl Shapiro58551df2011-07-24 03:09:51 -070030#include "mark_sweep.h"
Mathieu Chartierb43b7d42012-06-19 13:15:09 -070031#include "mod_union_table.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070032#include "object.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080033#include "object_utils.h"
Brian Carlstrom5643b782012-02-05 12:32:53 -080034#include "os.h"
Mathieu Chartier7664f5c2012-06-08 18:15:32 -070035#include "ScopedLocalRef.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070036#include "scoped_thread_state_change.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070037#include "space.h"
Carl Shapiro58551df2011-07-24 03:09:51 -070038#include "stl_util.h"
Elliott Hughes8d768a92011-09-14 16:35:25 -070039#include "thread_list.h"
Elliott Hughes767a1472011-10-26 18:49:02 -070040#include "timing_logger.h"
41#include "UniquePtr.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070042#include "well_known_classes.h"
Carl Shapiro69759ea2011-07-21 18:13:35 -070043
44namespace art {
45
Ian Rogers30fab402012-01-23 15:43:46 -080046static void UpdateFirstAndLastSpace(Space** first_space, Space** last_space, Space* space) {
47 if (*first_space == NULL) {
48 *first_space = space;
49 *last_space = space;
50 } else {
51 if ((*first_space)->Begin() > space->Begin()) {
52 *first_space = space;
53 } else if (space->Begin() > (*last_space)->Begin()) {
54 *last_space = space;
55 }
56 }
57}
58
Elliott Hughesae80b492012-04-24 10:43:17 -070059static bool GenerateImage(const std::string& image_file_name) {
Brian Carlstroma004aa92012-02-08 18:05:09 -080060 const std::string boot_class_path_string(Runtime::Current()->GetBootClassPathString());
Brian Carlstrom5643b782012-02-05 12:32:53 -080061 std::vector<std::string> boot_class_path;
62 Split(boot_class_path_string, ':', boot_class_path);
Brian Carlstromb2793372012-03-17 18:27:16 -070063 if (boot_class_path.empty()) {
64 LOG(FATAL) << "Failed to generate image because no boot class path specified";
65 }
Brian Carlstrom5643b782012-02-05 12:32:53 -080066
67 std::vector<char*> arg_vector;
68
69 std::string dex2oat_string(GetAndroidRoot());
Elliott Hughes67d92002012-03-26 15:08:51 -070070 dex2oat_string += (kIsDebugBuild ? "/bin/dex2oatd" : "/bin/dex2oat");
Brian Carlstrom5643b782012-02-05 12:32:53 -080071 const char* dex2oat = dex2oat_string.c_str();
72 arg_vector.push_back(strdup(dex2oat));
73
74 std::string image_option_string("--image=");
75 image_option_string += image_file_name;
76 const char* image_option = image_option_string.c_str();
77 arg_vector.push_back(strdup(image_option));
78
79 arg_vector.push_back(strdup("--runtime-arg"));
80 arg_vector.push_back(strdup("-Xms64m"));
81
82 arg_vector.push_back(strdup("--runtime-arg"));
83 arg_vector.push_back(strdup("-Xmx64m"));
84
85 for (size_t i = 0; i < boot_class_path.size(); i++) {
86 std::string dex_file_option_string("--dex-file=");
87 dex_file_option_string += boot_class_path[i];
88 const char* dex_file_option = dex_file_option_string.c_str();
89 arg_vector.push_back(strdup(dex_file_option));
90 }
91
92 std::string oat_file_option_string("--oat-file=");
93 oat_file_option_string += image_file_name;
94 oat_file_option_string.erase(oat_file_option_string.size() - 3);
95 oat_file_option_string += "oat";
96 const char* oat_file_option = oat_file_option_string.c_str();
97 arg_vector.push_back(strdup(oat_file_option));
98
99 arg_vector.push_back(strdup("--base=0x60000000"));
100
Elliott Hughes48436bb2012-02-07 15:23:28 -0800101 std::string command_line(Join(arg_vector, ' '));
Brian Carlstrom5643b782012-02-05 12:32:53 -0800102 LOG(INFO) << command_line;
103
Elliott Hughes48436bb2012-02-07 15:23:28 -0800104 arg_vector.push_back(NULL);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800105 char** argv = &arg_vector[0];
106
107 // fork and exec dex2oat
108 pid_t pid = fork();
109 if (pid == 0) {
110 // no allocation allowed between fork and exec
111
112 // change process groups, so we don't get reaped by ProcessManager
113 setpgid(0, 0);
114
115 execv(dex2oat, argv);
116
117 PLOG(FATAL) << "execv(" << dex2oat << ") failed";
118 return false;
119 } else {
120 STLDeleteElements(&arg_vector);
121
122 // wait for dex2oat to finish
123 int status;
124 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
125 if (got_pid != pid) {
126 PLOG(ERROR) << "waitpid failed: wanted " << pid << ", got " << got_pid;
127 return false;
128 }
129 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
130 LOG(ERROR) << dex2oat << " failed: " << command_line;
131 return false;
132 }
133 }
134 return true;
135}
136
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800137Heap::Heap(size_t initial_size, size_t growth_limit, size_t capacity,
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700138 const std::string& original_image_file_name, bool concurrent_gc)
139 : alloc_space_(NULL),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800140 card_table_(NULL),
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700141 concurrent_gc_(concurrent_gc),
142 have_zygote_space_(false),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800143 card_marking_disabled_(false),
144 is_gc_running_(false),
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700145 concurrent_start_bytes_(std::numeric_limits<size_t>::max()),
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700146 concurrent_start_size_(128 * KB),
147 concurrent_min_free_(256 * KB),
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700148 sticky_gc_count_(0),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800149 num_bytes_allocated_(0),
150 num_objects_allocated_(0),
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700151 last_trim_time_(0),
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700152 try_running_gc_(false),
153 requesting_gc_(false),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800154 reference_referent_offset_(0),
155 reference_queue_offset_(0),
156 reference_queueNext_offset_(0),
157 reference_pendingNext_offset_(0),
158 finalizer_reference_zombie_offset_(0),
159 target_utilization_(0.5),
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700160 verify_objects_(false) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800161 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800162 LOG(INFO) << "Heap() entering";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700163 }
164
Ian Rogers30fab402012-01-23 15:43:46 -0800165 // Compute the bounds of all spaces for allocating live and mark bitmaps
166 // there will be at least one space (the alloc space)
167 Space* first_space = NULL;
168 Space* last_space = NULL;
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700169
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700170 live_bitmap_.reset(new HeapBitmap(this));
171 mark_bitmap_.reset(new HeapBitmap(this));
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700172
Ian Rogers30fab402012-01-23 15:43:46 -0800173 // Requested begin for the alloc space, to follow the mapped image and oat files
174 byte* requested_begin = NULL;
Brian Carlstrom5643b782012-02-05 12:32:53 -0800175 std::string image_file_name(original_image_file_name);
176 if (!image_file_name.empty()) {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700177 Space* image_space = NULL;
178
Brian Carlstrom5643b782012-02-05 12:32:53 -0800179 if (OS::FileExists(image_file_name.c_str())) {
180 // If the /system file exists, it should be up-to-date, don't try to generate
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700181 image_space = Space::CreateImageSpace(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800182 } else {
183 // If the /system file didn't exist, we need to use one from the art-cache.
184 // If the cache file exists, try to open, but if it fails, regenerate.
185 // If it does not exist, generate.
186 image_file_name = GetArtCacheFilenameOrDie(image_file_name);
187 if (OS::FileExists(image_file_name.c_str())) {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700188 image_space = Space::CreateImageSpace(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800189 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700190 if (image_space == NULL) {
Brian Carlstrom5643b782012-02-05 12:32:53 -0800191 if (!GenerateImage(image_file_name)) {
192 LOG(FATAL) << "Failed to generate image: " << image_file_name;
193 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700194 image_space = Space::CreateImageSpace(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800195 }
196 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700197 if (image_space == NULL) {
Brian Carlstrom223f20f2012-02-04 23:06:55 -0800198 LOG(FATAL) << "Failed to create space from " << image_file_name;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700199 }
Brian Carlstrom5643b782012-02-05 12:32:53 -0800200
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700201 AddSpace(image_space);
202 UpdateFirstAndLastSpace(&first_space, &last_space, image_space);
Ian Rogers30fab402012-01-23 15:43:46 -0800203 // Oat files referenced by image files immediately follow them in memory, ensure alloc space
204 // isn't going to get in the middle
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700205 byte* oat_end_addr = GetImageSpace()->GetImageHeader().GetOatEnd();
206 CHECK(oat_end_addr > GetImageSpace()->End());
Ian Rogers30fab402012-01-23 15:43:46 -0800207 if (oat_end_addr > requested_begin) {
208 requested_begin = reinterpret_cast<byte*>(RoundUp(reinterpret_cast<uintptr_t>(oat_end_addr),
209 kPageSize));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700210 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700211 }
212
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700213 UniquePtr<AllocSpace> alloc_space(Space::CreateAllocSpace(
214 "alloc space", initial_size, growth_limit, capacity, requested_begin));
215 alloc_space_ = alloc_space.release();
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700216 CHECK(alloc_space_ != NULL) << "Failed to create alloc space";
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700217 AddSpace(alloc_space_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700218
Ian Rogers30fab402012-01-23 15:43:46 -0800219 UpdateFirstAndLastSpace(&first_space, &last_space, alloc_space_);
220 byte* heap_begin = first_space->Begin();
Ian Rogers3bb17a62012-01-27 23:56:44 -0800221 size_t heap_capacity = (last_space->Begin() - first_space->Begin()) + last_space->NonGrowthLimitCapacity();
Carl Shapiro69759ea2011-07-21 18:13:35 -0700222
Ian Rogers30fab402012-01-23 15:43:46 -0800223 // Mark image objects in the live bitmap
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800224 for (size_t i = 0; i < spaces_.size(); ++i) {
Ian Rogers30fab402012-01-23 15:43:46 -0800225 Space* space = spaces_[i];
226 if (space->IsImageSpace()) {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700227 space->AsImageSpace()->RecordImageAllocations(space->GetLiveBitmap());
Ian Rogers30fab402012-01-23 15:43:46 -0800228 }
229 }
230
Elliott Hughes6c9c06d2011-11-07 16:43:47 -0800231 // Allocate the card table.
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700232 card_table_.reset(CardTable::Create(heap_begin, heap_capacity));
233 CHECK(card_table_.get() != NULL) << "Failed to create card table";
Ian Rogers5d76c432011-10-31 21:42:49 -0700234
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700235 mod_union_table_.reset(new ModUnionTableToZygoteAllocspace<ModUnionTableReferenceCache>(this));
236 CHECK(mod_union_table_.get() != NULL) << "Failed to create mod-union table";
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700237
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700238 zygote_mod_union_table_.reset(new ModUnionTableCardCache(this));
239 CHECK(zygote_mod_union_table_.get() != NULL) << "Failed to create Zygote mod-union table";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700240
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700241 // TODO: Count objects in the image space here.
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700242 num_bytes_allocated_ = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700243 num_objects_allocated_ = 0;
244
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700245 // Max stack size in bytes.
246 static const size_t max_stack_size = capacity / SpaceBitmap::kAlignment * kWordSize;
247
248 // TODO: Rename MarkStack to a more generic name?
249 mark_stack_.reset(MarkStack::Create("dalvik-mark-stack", max_stack_size));
250 allocation_stack_.reset(MarkStack::Create("dalvik-allocation-stack", max_stack_size));
251 live_stack_.reset(MarkStack::Create("dalvik-live-stack", max_stack_size));
Mathieu Chartier5301cd22012-05-31 12:11:36 -0700252
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800253 // It's still too early to take a lock because there are no threads yet,
Elliott Hughes92b3b562011-09-08 16:32:26 -0700254 // but we can create the heap lock now. We don't create it earlier to
255 // make it clear that you can't use locks during heap initialization.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700256 gc_complete_lock_ = new Mutex("GC complete lock");
257 gc_complete_cond_.reset(new ConditionVariable("GC complete condition variable"));
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700258
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800259 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800260 LOG(INFO) << "Heap() exiting";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700261 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700262}
263
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700264// Sort spaces based on begin address
265class SpaceSorter {
266 public:
267 bool operator () (const Space* a, const Space* b) const {
268 return a->Begin() < b->Begin();
269 }
270};
271
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800272void Heap::AddSpace(Space* space) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700273 WriterMutexLock mu(*GlobalSynchronization::heap_bitmap_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700274 DCHECK(space != NULL);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700275 DCHECK(space->GetLiveBitmap() != NULL);
276 live_bitmap_->AddSpaceBitmap(space->GetLiveBitmap());
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700277 DCHECK(space->GetMarkBitmap() != NULL);
278 mark_bitmap_->AddSpaceBitmap(space->GetMarkBitmap());
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800279 spaces_.push_back(space);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700280 if (space->IsAllocSpace()) {
281 alloc_space_ = space->AsAllocSpace();
282 }
283
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700284 // Ensure that spaces remain sorted in increasing order of start address (required for CMS finger)
285 std::sort(spaces_.begin(), spaces_.end(), SpaceSorter());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700286
287 // Ensure that ImageSpaces < ZygoteSpaces < AllocSpaces so that we can do address based checks to
288 // avoid redundant marking.
289 bool seen_zygote = false, seen_alloc = false;
290 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
291 Space* space = *it;
292 if (space->IsImageSpace()) {
293 DCHECK(!seen_zygote);
294 DCHECK(!seen_alloc);
295 } if (space->IsZygoteSpace()) {
296 DCHECK(!seen_alloc);
297 seen_zygote = true;
298 } else if (space->IsAllocSpace()) {
299 seen_alloc = true;
300 }
301 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800302}
303
304Heap::~Heap() {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700305 // If we don't reset then the mark stack complains in it's destructor.
306 allocation_stack_->Reset();
307 live_stack_->Reset();
308
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800309 VLOG(heap) << "~Heap()";
Elliott Hughesb3e66df2012-01-12 14:49:18 -0800310 // We can't take the heap lock here because there might be a daemon thread suspended with the
311 // heap lock held. We know though that no non-daemon threads are executing, and we know that
312 // all daemon threads are suspended, and we also know that the threads list have been deleted, so
313 // 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 -0700314 STLDeleteElements(&spaces_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700315 delete gc_complete_lock_;
316
Carl Shapiro69759ea2011-07-21 18:13:35 -0700317}
318
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700319Space* Heap::FindSpaceFromObject(const Object* obj) const {
320 // TODO: C++0x auto
321 for (Spaces::const_iterator cur = spaces_.begin(); cur != spaces_.end(); ++cur) {
322 if ((*cur)->Contains(obj)) {
323 return *cur;
324 }
325 }
326 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
327 return NULL;
328}
329
330ImageSpace* Heap::GetImageSpace() {
331 // TODO: C++0x auto
332 for (Spaces::const_iterator cur = spaces_.begin(); cur != spaces_.end(); ++cur) {
333 if ((*cur)->IsImageSpace()) {
334 return (*cur)->AsImageSpace();
335 }
336 }
337 return NULL;
338}
339
340AllocSpace* Heap::GetAllocSpace() {
341 return alloc_space_;
342}
343
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700344static void MSpaceChunkCallback(void* start, void* end, size_t used_bytes, void* arg) {
345 size_t& max_contiguous_allocation = *reinterpret_cast<size_t*>(arg);
346
347 size_t chunk_size = static_cast<size_t>(reinterpret_cast<uint8_t*>(end) - reinterpret_cast<uint8_t*>(start));
348 size_t chunk_free_bytes = 0;
349 if (used_bytes < chunk_size) {
350 chunk_free_bytes = chunk_size - used_bytes;
351 }
352
353 if (chunk_free_bytes > max_contiguous_allocation) {
354 max_contiguous_allocation = chunk_free_bytes;
355 }
356}
357
358Object* Heap::AllocObject(Class* c, size_t byte_count) {
359 // Used in the detail message if we throw an OOME.
360 int64_t total_bytes_free;
361 size_t max_contiguous_allocation;
362
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700363 DCHECK(c == NULL || (c->IsClassClass() && byte_count >= sizeof(Class)) ||
364 (c->IsVariableSize() || c->GetObjectSize() == byte_count) ||
365 strlen(ClassHelper(c).GetDescriptor()) == 0);
366 DCHECK_GE(byte_count, sizeof(Object));
367 Object* obj = Allocate(byte_count);
368 if (obj != NULL) {
369 obj->SetClass(c);
370 if (Dbg::IsAllocTrackingEnabled()) {
371 Dbg::RecordAllocation(c, byte_count);
Elliott Hughes418dfe72011-10-06 18:56:27 -0700372 }
Mathieu Chartier637e3482012-08-17 10:41:32 -0700373 const bool request_concurrent_gc = num_bytes_allocated_ >= concurrent_start_bytes_;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700374 if (request_concurrent_gc) {
375 // The SirtRef is necessary since the calls in RequestConcurrentGC are a safepoint.
376 SirtRef<Object> ref(obj);
377 RequestConcurrentGC();
378 }
379 VerifyObject(obj);
380
381 // Additional verification to ensure that we did not allocate into a zygote space.
382 DCHECK(!have_zygote_space_ || !FindSpaceFromObject(obj)->IsZygoteSpace());
383
384 return obj;
385 }
386 total_bytes_free = GetFreeMemory();
387 max_contiguous_allocation = 0;
388 // TODO: C++0x auto
389 for (Spaces::const_iterator cur = spaces_.begin(); cur != spaces_.end(); ++cur) {
390 if ((*cur)->IsAllocSpace()) {
391 (*cur)->AsAllocSpace()->Walk(MSpaceChunkCallback, &max_contiguous_allocation);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700392 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700393 }
Elliott Hughes418dfe72011-10-06 18:56:27 -0700394
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700395 std::string msg(StringPrintf("Failed to allocate a %zd-byte %s (%lld total bytes free; largest possible contiguous allocation %zd bytes)",
396 byte_count,
397 PrettyDescriptor(c).c_str(),
398 total_bytes_free, max_contiguous_allocation));
399 Thread::Current()->ThrowOutOfMemoryError(msg.c_str());
Elliott Hughes418dfe72011-10-06 18:56:27 -0700400 return NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700401}
402
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700403bool Heap::IsHeapAddress(const Object* obj) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700404 // Note: we deliberately don't take the lock here, and mustn't test anything that would
405 // require taking the lock.
Elliott Hughes88c5c352012-03-15 18:49:48 -0700406 if (obj == NULL) {
407 return true;
408 }
409 if (!IsAligned<kObjectAlignment>(obj)) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700410 return false;
411 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800412 for (size_t i = 0; i < spaces_.size(); ++i) {
Ian Rogers30fab402012-01-23 15:43:46 -0800413 if (spaces_[i]->Contains(obj)) {
414 return true;
415 }
416 }
417 return false;
Elliott Hughesa2501992011-08-26 19:39:54 -0700418}
419
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700420bool Heap::IsLiveObjectLocked(const Object* obj) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700421 GlobalSynchronization::heap_bitmap_lock_->AssertReaderHeld();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700422 return IsHeapAddress(obj) && GetLiveBitmap()->Test(obj);
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700423}
424
Elliott Hughes3e465b12011-09-02 18:26:12 -0700425#if VERIFY_OBJECT_ENABLED
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700426void Heap::VerifyObject(const Object* obj) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700427 if (obj == NULL || this == NULL || !verify_objects_ || Runtime::Current()->IsShuttingDown() ||
Ian Rogers141d6222012-04-05 12:23:06 -0700428 Thread::Current() == NULL ||
jeffhao25045522012-03-13 19:34:37 -0700429 Runtime::Current()->GetThreadList()->GetLockOwner() == Thread::Current()->GetTid()) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700430 return;
431 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700432 VerifyObjectBody(obj);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700433}
434#endif
435
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700436void Heap::DumpSpaces() {
437 // TODO: C++0x auto
438 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700439 Space* space = *it;
440 LOG(INFO) << *space;
441 LOG(INFO) << *space->GetLiveBitmap();
442 LOG(INFO) << *space->GetMarkBitmap();
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700443 }
444}
445
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700446// We want to avoid bit rotting.
447void Heap::VerifyObjectBody(const Object* obj) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700448 if (!IsAligned<kObjectAlignment>(obj)) {
449 LOG(FATAL) << "Object isn't aligned: " << obj;
450 } else if (!GetLiveBitmap()->Test(obj)) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700451 DumpSpaces();
452 LOG(FATAL) << "Object is dead: " << obj;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700453 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700454
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700455 // Ignore early dawn of the universe verifications
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700456 if (!VERIFY_OBJECT_FAST && num_objects_allocated_ > 10) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700457 const byte* raw_addr = reinterpret_cast<const byte*>(obj) +
458 Object::ClassOffset().Int32Value();
459 const Class* c = *reinterpret_cast<Class* const *>(raw_addr);
460 if (c == NULL) {
461 LOG(FATAL) << "Null class in object: " << obj;
462 } else if (!IsAligned<kObjectAlignment>(c)) {
463 LOG(FATAL) << "Class isn't aligned: " << c << " in object: " << obj;
464 } else if (!GetLiveBitmap()->Test(c)) {
465 LOG(FATAL) << "Class of object is dead: " << c << " in object: " << obj;
466 }
467 // Check obj.getClass().getClass() == obj.getClass().getClass().getClass()
468 // Note: we don't use the accessors here as they have internal sanity checks
469 // that we don't want to run
470 raw_addr = reinterpret_cast<const byte*>(c) + Object::ClassOffset().Int32Value();
471 const Class* c_c = *reinterpret_cast<Class* const *>(raw_addr);
472 raw_addr = reinterpret_cast<const byte*>(c_c) + Object::ClassOffset().Int32Value();
473 const Class* c_c_c = *reinterpret_cast<Class* const *>(raw_addr);
474 CHECK_EQ(c_c, c_c_c);
475 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700476}
477
Brian Carlstrom78128a62011-09-15 17:21:19 -0700478void Heap::VerificationCallback(Object* obj, void* arg) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700479 DCHECK(obj != NULL);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700480 reinterpret_cast<Heap*>(arg)->VerifyObjectBody(obj);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700481}
482
483void Heap::VerifyHeap() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700484 ReaderMutexLock mu(*GlobalSynchronization::heap_bitmap_lock_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700485 GetLiveBitmap()->Walk(Heap::VerificationCallback, this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700486}
487
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700488void Heap::RecordAllocation(AllocSpace* space, const Object* obj) {
489 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700490 size_t size = space->AllocationSize(obj);
491 DCHECK_GT(size, 0u);
Mathieu Chartier637e3482012-08-17 10:41:32 -0700492 COMPILE_ASSERT(sizeof(size_t) == sizeof(int32_t),
493 int32_t_must_be_same_size_as_size_t_for_used_atomic_operations);
Mathieu Chartier556fad32012-08-20 16:13:20 -0700494 android_atomic_add(size, reinterpret_cast<volatile int32_t*>(
495 reinterpret_cast<size_t>(&num_bytes_allocated_)));
496 android_atomic_add(1, reinterpret_cast<volatile int32_t*>(
497 reinterpret_cast<size_t>(&num_objects_allocated_)));
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700498
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700499 if (Runtime::Current()->HasStatsEnabled()) {
500 RuntimeStats* global_stats = Runtime::Current()->GetStats();
501 RuntimeStats* thread_stats = Thread::Current()->GetStats();
502 ++global_stats->allocated_objects;
503 ++thread_stats->allocated_objects;
504 global_stats->allocated_bytes += size;
505 thread_stats->allocated_bytes += size;
506 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700507 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700508
509 DCHECK(obj);
510
511 allocation_stack_->AtomicPush(obj);
512#if VERIFY_OBJECT_ENABLED
513 WriterMutexLock mu(*GlobalSynchronization::heap_bitmap_lock_);
514 // Verify objects doesn't like objects in allocation stack not being marked as live.
515 live_bitmap_->Set(obj);
516#endif
Carl Shapiro58551df2011-07-24 03:09:51 -0700517}
518
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700519void Heap::RecordFree(size_t freed_objects, size_t freed_bytes) {
Mathieu Chartier637e3482012-08-17 10:41:32 -0700520 COMPILE_ASSERT(sizeof(size_t) == sizeof(int32_t),
521 int32_t_must_be_same_size_as_size_t_for_used_atomic_operations);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700522 DCHECK_LE(freed_objects, num_objects_allocated_);
Mathieu Chartier637e3482012-08-17 10:41:32 -0700523 android_atomic_add(-static_cast<int32_t>(freed_objects),
Mathieu Chartier556fad32012-08-20 16:13:20 -0700524 reinterpret_cast<volatile int32_t*>(
525 reinterpret_cast<size_t>(&num_objects_allocated_)));
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700526
527 DCHECK_LE(freed_bytes, num_bytes_allocated_);
Mathieu Chartier637e3482012-08-17 10:41:32 -0700528 android_atomic_add(-static_cast<int32_t>(freed_bytes),
Mathieu Chartier556fad32012-08-20 16:13:20 -0700529 reinterpret_cast<volatile int32_t*>(
530 reinterpret_cast<size_t>(&num_bytes_allocated_)));
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700531
532 if (Runtime::Current()->HasStatsEnabled()) {
533 RuntimeStats* global_stats = Runtime::Current()->GetStats();
534 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700535 global_stats->freed_objects += freed_objects;
536 thread_stats->freed_objects += freed_objects;
Elliott Hughes307f75d2011-10-12 18:04:40 -0700537 global_stats->freed_bytes += freed_bytes;
538 thread_stats->freed_bytes += freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700539 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700540}
541
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700542Object* Heap::Allocate(size_t size) {
543 Object* obj = Allocate(alloc_space_, size);
Carl Shapiro58551df2011-07-24 03:09:51 -0700544 if (obj != NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700545 RecordAllocation(alloc_space_, obj);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700546 return obj;
Carl Shapiro58551df2011-07-24 03:09:51 -0700547 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700548
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700549 return NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700550}
551
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700552Object* Heap::Allocate(AllocSpace* space, size_t alloc_size) {
553 Thread* self = Thread::Current();
Ian Rogers0399dde2012-06-06 17:09:28 -0700554 // Since allocation can cause a GC which will need to SuspendAll, make sure all allocations are
555 // done in the runnable state where suspension is expected.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700556#ifndef NDEBUG
557 {
558 MutexLock mu(*GlobalSynchronization::thread_suspend_count_lock_);
559 CHECK_EQ(self->GetState(), kRunnable);
560 }
561 self->AssertThreadSuspensionIsAllowable();
562#endif
Brian Carlstromb82b6872011-10-26 17:18:07 -0700563
Ian Rogers30fab402012-01-23 15:43:46 -0800564 Object* ptr = space->AllocWithoutGrowth(alloc_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700565 if (ptr != NULL) {
566 return ptr;
567 }
568
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700569 // The allocation failed. If the GC is running, block until it completes else request a
570 // foreground partial collection.
571 if (!WaitForConcurrentGcToComplete()) {
572 // No concurrent GC so perform a foreground collection.
573 if (Runtime::Current()->HasStatsEnabled()) {
574 ++Runtime::Current()->GetStats()->gc_for_alloc_count;
575 ++Thread::Current()->GetStats()->gc_for_alloc_count;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700576 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700577 self->TransitionFromRunnableToSuspended(kWaitingPerformingGc);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700578 CollectGarbageInternal(have_zygote_space_ ? GC_PARTIAL : GC_FULL, false);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700579 self->TransitionFromSuspendedToRunnable();
Carl Shapiro69759ea2011-07-21 18:13:35 -0700580 }
581
Ian Rogers30fab402012-01-23 15:43:46 -0800582 ptr = space->AllocWithoutGrowth(alloc_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700583 if (ptr != NULL) {
584 return ptr;
585 }
586
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700587 const size_t alloc_space_size = alloc_space_->Size();
588 if (alloc_space_size > kMinAllocSpaceSizeForStickyGC &&
589 alloc_space_->Capacity() - alloc_space_size < kMinRemainingSpaceForStickyGC) {
590 // Partial GC didn't free enough memory, try a full GC.
591 if (Runtime::Current()->HasStatsEnabled()) {
592 ++Runtime::Current()->GetStats()->gc_for_alloc_count;
593 ++Thread::Current()->GetStats()->gc_for_alloc_count;
594 }
595
596 // Don't bother trying a young GC unless we have a few MB AllocSpace.
597 self->TransitionFromRunnableToSuspended(kWaitingPerformingGc);
598 CollectGarbageInternal(GC_STICKY, false);
599 self->TransitionFromSuspendedToRunnable();
600
601 ptr = space->AllocWithoutGrowth(alloc_size);
602 if (ptr != NULL) {
603 return ptr;
604 }
605 }
606
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700607 if (!have_zygote_space_) {
608 // Partial GC didn't free enough memory, try a full GC.
609 if (Runtime::Current()->HasStatsEnabled()) {
610 ++Runtime::Current()->GetStats()->gc_for_alloc_count;
611 ++Thread::Current()->GetStats()->gc_for_alloc_count;
612 }
613 self->TransitionFromRunnableToSuspended(kWaitingPerformingGc);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700614 CollectGarbageInternal(GC_PARTIAL, false);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700615 self->TransitionFromSuspendedToRunnable();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700616
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700617 ptr = space->AllocWithoutGrowth(alloc_size);
618 if (ptr != NULL) {
619 return ptr;
620 }
621 }
622
623 // Allocations have failed after GCs; this is an exceptional state.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700624 // Try harder, growing the heap if necessary.
Ian Rogers30fab402012-01-23 15:43:46 -0800625 ptr = space->AllocWithGrowth(alloc_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700626 if (ptr != NULL) {
Ian Rogers30fab402012-01-23 15:43:46 -0800627 size_t new_footprint = space->GetFootprintLimit();
Elliott Hughes418dfe72011-10-06 18:56:27 -0700628 // OLD-TODO: may want to grow a little bit more so that the amount of
Carl Shapiro58551df2011-07-24 03:09:51 -0700629 // free space is equal to the old free space + the
630 // utilization slop for the new allocation.
Ian Rogers3bb17a62012-01-27 23:56:44 -0800631 VLOG(gc) << "Grow heap (frag case) to " << PrettySize(new_footprint)
Ian Rogers162a31c2012-01-31 16:14:31 -0800632 << " for a " << PrettySize(alloc_size) << " allocation";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700633 return ptr;
634 }
635
Elliott Hughes81ff3182012-03-23 20:35:56 -0700636 // Most allocations should have succeeded by now, so the heap is really full, really fragmented,
637 // or the requested size is really big. Do another GC, collecting SoftReferences this time. The
638 // VM spec requires that all SoftReferences have been collected and cleared before throwing OOME.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700639
Elliott Hughes418dfe72011-10-06 18:56:27 -0700640 // OLD-TODO: wait for the finalizers from the previous GC to finish
Ian Rogers3bb17a62012-01-27 23:56:44 -0800641 VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size) << " allocation";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700642
643 if (Runtime::Current()->HasStatsEnabled()) {
644 ++Runtime::Current()->GetStats()->gc_for_alloc_count;
645 ++Thread::Current()->GetStats()->gc_for_alloc_count;
646 }
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -0700647 // We don't need a WaitForConcurrentGcToComplete here either.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700648 self->TransitionFromRunnableToSuspended(kWaitingPerformingGc);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700649 CollectGarbageInternal(GC_FULL, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700650 self->TransitionFromSuspendedToRunnable();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700651 return space->AllocWithGrowth(alloc_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700652}
653
Elliott Hughesbf86d042011-08-31 17:53:14 -0700654int64_t Heap::GetMaxMemory() {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700655 size_t total = 0;
656 // TODO: C++0x auto
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700657 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
658 Space* space = *it;
659 if (space->IsAllocSpace()) {
660 total += space->AsAllocSpace()->Capacity();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700661 }
662 }
663 return total;
Elliott Hughesbf86d042011-08-31 17:53:14 -0700664}
665
666int64_t Heap::GetTotalMemory() {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700667 return GetMaxMemory();
Elliott Hughesbf86d042011-08-31 17:53:14 -0700668}
669
670int64_t Heap::GetFreeMemory() {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700671 return GetMaxMemory() - num_bytes_allocated_;
Elliott Hughesbf86d042011-08-31 17:53:14 -0700672}
673
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700674class InstanceCounter {
675 public:
676 InstanceCounter(Class* c, bool count_assignable)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700677 SHARED_LOCKS_REQUIRED(GlobalSynchronization::mutator_lock_)
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700678 : class_(c), count_assignable_(count_assignable), count_(0) {
679 }
680
681 size_t GetCount() {
682 return count_;
683 }
684
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700685 static void Callback(Object* o, void* arg)
686 SHARED_LOCKS_REQUIRED(GlobalSynchronization::mutator_lock_) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700687 reinterpret_cast<InstanceCounter*>(arg)->VisitInstance(o);
688 }
689
690 private:
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700691 void VisitInstance(Object* o) SHARED_LOCKS_REQUIRED(GlobalSynchronization::mutator_lock_) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700692 Class* instance_class = o->GetClass();
693 if (count_assignable_) {
694 if (instance_class == class_) {
695 ++count_;
696 }
697 } else {
698 if (instance_class != NULL && class_->IsAssignableFrom(instance_class)) {
699 ++count_;
700 }
701 }
702 }
703
704 Class* class_;
705 bool count_assignable_;
706 size_t count_;
707};
708
709int64_t Heap::CountInstances(Class* c, bool count_assignable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700710 ReaderMutexLock mu(*GlobalSynchronization::heap_bitmap_lock_);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700711 InstanceCounter counter(c, count_assignable);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700712 GetLiveBitmap()->Walk(InstanceCounter::Callback, &counter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700713 return counter.GetCount();
714}
715
Ian Rogers30fab402012-01-23 15:43:46 -0800716void Heap::CollectGarbage(bool clear_soft_references) {
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -0700717 // If we just waited for a GC to complete then we do not need to do another
718 // GC unless we clear soft references.
719 if (!WaitForConcurrentGcToComplete() || clear_soft_references) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700720 ScopedThreadStateChange tsc(Thread::Current(), kWaitingPerformingGc);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700721 CollectGarbageInternal(have_zygote_space_ ? GC_PARTIAL : GC_FULL, clear_soft_references);
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -0700722 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700723}
724
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700725void Heap::PreZygoteFork() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700726 static Mutex zygote_creation_lock_("zygote creation lock", kZygoteCreationLock);
727 MutexLock mu(zygote_creation_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700728
729 // Try to see if we have any Zygote spaces.
730 if (have_zygote_space_) {
731 return;
732 }
733
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700734 VLOG(heap) << "Starting PreZygoteFork with alloc space size " << PrettySize(alloc_space_->Size());
735
736 {
737 // Flush the alloc stack.
738 WriterMutexLock mu(*GlobalSynchronization::heap_bitmap_lock_);
739 FlushAllocStack();
740 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700741
742 // Replace the first alloc space we find with a zygote space.
743 // TODO: C++0x auto
744 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
745 if ((*it)->IsAllocSpace()) {
746 AllocSpace* zygote_space = (*it)->AsAllocSpace();
747
748 // Turns the current alloc space into a Zygote space and obtain the new alloc space composed
749 // of the remaining available heap memory.
750 alloc_space_ = zygote_space->CreateZygoteSpace();
751
752 // Change the GC retention policy of the zygote space to only collect when full.
753 zygote_space->SetGcRetentionPolicy(GCRP_FULL_COLLECT);
754 AddSpace(alloc_space_);
755 have_zygote_space_ = true;
756 break;
757 }
758 }
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700759
760 // Reset this since we now count the ZygoteSpace in the total heap size.
761 num_bytes_allocated_ = 0;
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700762}
763
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700764void Heap::FlushAllocStack() {
765 MarkStackAsLive(allocation_stack_.get());
766 allocation_stack_->Reset();
767}
768
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700769size_t Heap::GetUsedMemorySize() const {
770 size_t total = num_bytes_allocated_;
771 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
772 if ((*it)->IsZygoteSpace()) {
773 total += (*it)->AsAllocSpace()->Size();
774 }
775 }
776 return total;
777}
778
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700779void Heap::MarkStackAsLive(MarkStack* alloc_stack) {
780 // We can just assume everything is inside the alloc_space_'s bitmap since we should only have
781 // fresh allocations.
782 SpaceBitmap* live_bitmap = alloc_space_->GetLiveBitmap();
783
784 // Empty the allocation stack.
785 const size_t count = alloc_stack->Size();
786 for (size_t i = 0; i < count; ++i) {
787 const Object* obj = alloc_stack->Get(i);
788 DCHECK(obj != NULL);
789 live_bitmap->Set(obj);
790 }
791}
792
793void Heap::UnMarkStack(MarkStack* alloc_stack) {
794 SpaceBitmap* mark_bitmap = alloc_space_->GetMarkBitmap();
795
796 // Clear all of the things in the AllocStack.
797 size_t count = alloc_stack->Size();
798 for (size_t i = 0;i < count;++i) {
799 const Object* obj = alloc_stack->Get(i);
800 DCHECK(obj != NULL);
801 if (mark_bitmap->Test(obj)) {
802 mark_bitmap->Clear(obj);
803 }
804 }
805}
806
807void Heap::CollectGarbageInternal(GcType gc_type, bool clear_soft_references) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700808 GlobalSynchronization::mutator_lock_->AssertNotHeld();
809#ifndef NDEBUG
810 {
811 MutexLock mu(*GlobalSynchronization::thread_suspend_count_lock_);
812 CHECK_EQ(Thread::Current()->GetState(), kWaitingPerformingGc);
813 }
814#endif
Carl Shapiro58551df2011-07-24 03:09:51 -0700815
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700816 // Ensure there is only one GC at a time.
817 bool start_collect = false;
818 while (!start_collect) {
819 {
820 MutexLock mu(*gc_complete_lock_);
821 if (!is_gc_running_) {
822 is_gc_running_ = true;
823 start_collect = true;
824 }
825 }
826 if (!start_collect) {
827 WaitForConcurrentGcToComplete();
828 // TODO: if another thread beat this one to do the GC, perhaps we should just return here?
829 // Not doing at the moment to ensure soft references are cleared.
830 }
831 }
832 gc_complete_lock_->AssertNotHeld();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700833
834 // We need to do partial GCs every now and then to avoid the heap growing too much and
835 // fragmenting.
836 if (gc_type == GC_STICKY && ++sticky_gc_count_ > kPartialGCFrequency) {
837 gc_type = GC_PARTIAL;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700838 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700839 if (gc_type != GC_STICKY) {
840 sticky_gc_count_ = 0;
841 }
842
Mathieu Chartier637e3482012-08-17 10:41:32 -0700843 if (concurrent_gc_) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700844 CollectGarbageConcurrentMarkSweepPlan(gc_type, clear_soft_references);
845 } else {
846 CollectGarbageMarkSweepPlan(gc_type, clear_soft_references);
847 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700848
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700849 gc_complete_lock_->AssertNotHeld();
850 MutexLock mu(*gc_complete_lock_);
851 is_gc_running_ = false;
852 // Wake anyone who may have been waiting for the GC to complete.
853 gc_complete_cond_->Broadcast();
854}
Mathieu Chartiera6399032012-06-11 18:49:50 -0700855
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700856void Heap::CollectGarbageMarkSweepPlan(GcType gc_type, bool clear_soft_references) {
857 TimingLogger timings("CollectGarbageInternal", true);
Mathieu Chartier662618f2012-06-06 12:01:47 -0700858
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700859 // Suspend all threads are get exclusive access to the heap.
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700860 uint64_t start_time = NanoTime();
Elliott Hughes8d768a92011-09-14 16:35:25 -0700861 ThreadList* thread_list = Runtime::Current()->GetThreadList();
862 thread_list->SuspendAll();
Mathieu Chartier662618f2012-06-06 12:01:47 -0700863 timings.AddSplit("SuspendAll");
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700864 GlobalSynchronization::mutator_lock_->AssertExclusiveHeld();
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700865
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700866 size_t bytes_freed = 0;
Elliott Hughesadb460d2011-10-05 17:02:34 -0700867 Object* cleared_references = NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700868 {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700869 MarkSweep mark_sweep(mark_stack_.get());
Carl Shapiro58551df2011-07-24 03:09:51 -0700870
871 mark_sweep.Init();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700872 timings.AddSplit("Init");
Carl Shapiro58551df2011-07-24 03:09:51 -0700873
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700874 // Make sure that the tables have the correct pointer for the mark sweep.
875 mod_union_table_->Init(&mark_sweep);
876 zygote_mod_union_table_->Init(&mark_sweep);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700877
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700878 // Swap allocation stack and live stack, enabling us to have new allocations during this GC.
879 MarkStack* temp = allocation_stack_.release();
880 allocation_stack_.reset(live_stack_.release());
881 live_stack_.reset(temp);
882
883 // We will need to know which cards were dirty for doing concurrent processing of dirty cards.
884 // TODO: Investigate using a mark stack instead of a vector.
885 std::vector<byte*> dirty_cards;
886 if (gc_type == GC_STICKY) {
887 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
888 card_table_->GetDirtyCards(*it, dirty_cards);
889 }
890 }
891
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700892 // Clear image space cards and keep track of cards we cleared in the mod-union table.
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700893 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
894 Space* space = *it;
895 if (space->IsImageSpace()) {
896 mod_union_table_->ClearCards(*it);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700897 timings.AddSplit("ClearModUnionCards");
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700898 } else if (space->GetGcRetentionPolicy() == GCRP_FULL_COLLECT) {
899 zygote_mod_union_table_->ClearCards(space);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700900 timings.AddSplit("ClearZygoteCards");
901 } else {
902 card_table_->ClearSpaceCards(space);
903 timings.AddSplit("ClearCards");
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700904 }
905 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700906
907#if VERIFY_MOD_UNION
908 mod_union_table_->Verify();
909 zygote_mod_union_table_->Verify();
910#endif
911
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700912 WriterMutexLock mu(*GlobalSynchronization::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700913 if (gc_type == GC_PARTIAL) {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700914 // Copy the mark bits over from the live bits, do this as early as possible or else we can
915 // accidentally un-mark roots.
916 // Needed for scanning dirty objects.
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700917 for (Spaces::iterator it = spaces_.begin();it != spaces_.end(); ++it) {
918 if ((*it)->GetGcRetentionPolicy() == GCRP_FULL_COLLECT) {
919 mark_sweep.CopyMarkBits(*it);
920 }
921 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700922 timings.AddSplit("CopyMarkBits");
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700923
924 // We can assume that everything < alloc_space_ start is marked at this point.
925 mark_sweep.SetCondemned(reinterpret_cast<Object*>(alloc_space_->Begin()));
926 } else if (gc_type == GC_STICKY) {
927 for (Spaces::iterator it = spaces_.begin();it != spaces_.end(); ++it) {
928 if ((*it)->GetGcRetentionPolicy() != GCRP_NEVER_COLLECT) {
929 mark_sweep.CopyMarkBits(*it);
930 }
931 }
932 timings.AddSplit("CopyMarkBits");
933
934 if (VERIFY_OBJECT_ENABLED) {
935 UnMarkStack(live_stack_.get());
936 }
937
938 mark_sweep.SetCondemned(reinterpret_cast<Object*>(alloc_space_->Begin()));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700939 }
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700940
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700941 MarkStackAsLive(live_stack_.get());
942
Carl Shapiro58551df2011-07-24 03:09:51 -0700943 mark_sweep.MarkRoots();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700944 timings.AddSplit("MarkRoots");
Carl Shapiro58551df2011-07-24 03:09:51 -0700945
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700946 // Roots are marked on the bitmap and the mark_stack is empty.
Ian Rogers5d76c432011-10-31 21:42:49 -0700947 DCHECK(mark_sweep.IsMarkStackEmpty());
Carl Shapiro58551df2011-07-24 03:09:51 -0700948
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700949 // Update zygote mod union table.
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700950 zygote_mod_union_table_->Update();
951 timings.AddSplit("UpdateZygoteModUnionTable");
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700952
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700953 zygote_mod_union_table_->MarkReferences();
954 timings.AddSplit("ZygoteMarkReferences");
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700955
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700956 // Processes the cards we cleared earlier and adds their objects into the mod-union table.
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700957 mod_union_table_->Update();
Mathieu Chartiere6e06512012-06-26 15:00:26 -0700958 timings.AddSplit("UpdateModUnionTable");
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700959
960 // Scans all objects in the mod-union table.
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700961 mod_union_table_->MarkReferences();
Mathieu Chartiere6e06512012-06-26 15:00:26 -0700962 timings.AddSplit("MarkImageToAllocSpaceReferences");
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700963
964 // Recursively mark all the non-image bits set in the mark bitmap.
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700965 if (gc_type != GC_STICKY) {
966 live_stack_->Reset();
967 mark_sweep.RecursiveMark(gc_type == GC_PARTIAL, timings);
968 } else {
969 mark_sweep.RecursiveMarkCards(card_table_.get(), dirty_cards, timings);
970 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700971
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700972 // Need to process references the swap since it uses IsMarked.
Ian Rogers30fab402012-01-23 15:43:46 -0800973 mark_sweep.ProcessReferences(clear_soft_references);
Elliott Hughes307f75d2011-10-12 18:04:40 -0700974 timings.AddSplit("ProcessReferences");
Carl Shapiro58551df2011-07-24 03:09:51 -0700975
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700976 // This doesn't work with mutators unpaused for some reason, TODO: Fix.
977 mark_sweep.SweepSystemWeaks(false);
978 timings.AddSplit("SweepSystemWeaks");
979
980 // Need to swap for VERIFY_OBJECT_ENABLED since we put things in the live bitmap after they
981 // have been allocated.
982 const bool swap = true;
983
984 if (swap) {
985 // Swap the live and mark bitmaps for each alloc space. This is needed since sweep re-swaps
986 // these bitmaps. Doing this enables us to sweep with the heap unlocked since new allocations
987 // set the live bit, but since we have the bitmaps reversed at this point, this sets the mark bit
988 // instead, resulting in no new allocated objects being incorrectly freed by sweep.
989 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
990 Space* space = *it;
991 // We only allocate into AllocSpace, so we only need to swap AllocSpaces.
992 if (space->GetGcRetentionPolicy() == GCRP_ALWAYS_COLLECT) {
993 live_bitmap_->ReplaceBitmap(space->GetLiveBitmap(), space->GetMarkBitmap());
994 mark_bitmap_->ReplaceBitmap(space->GetMarkBitmap(), space->GetLiveBitmap());
995 space->AsAllocSpace()->SwapBitmaps();
996 }
Mathieu Chartier654d3a22012-07-11 17:54:18 -0700997 }
998 }
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700999
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001000#ifndef NDEBUG
Mathieu Chartier262e5ff2012-06-01 17:35:38 -07001001 // Verify that we only reach marked objects from the image space
1002 mark_sweep.VerifyImageRoots();
1003 timings.AddSplit("VerifyImageRoots");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001004#endif
Carl Shapiro58551df2011-07-24 03:09:51 -07001005
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001006 if (gc_type != GC_STICKY) {
1007 mark_sweep.Sweep(gc_type == GC_PARTIAL, swap);
1008 } else {
1009 mark_sweep.SweepArray(timings, live_stack_.get(), swap);
1010 }
Elliott Hughes307f75d2011-10-12 18:04:40 -07001011 timings.AddSplit("Sweep");
Elliott Hughesadb460d2011-10-05 17:02:34 -07001012
1013 cleared_references = mark_sweep.GetClearedReferences();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001014 bytes_freed = mark_sweep.GetFreedBytes();
Carl Shapiro58551df2011-07-24 03:09:51 -07001015 }
1016
1017 GrowForUtilization();
Elliott Hughes307f75d2011-10-12 18:04:40 -07001018 timings.AddSplit("GrowForUtilization");
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001019
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001020 thread_list->ResumeAll();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001021 timings.AddSplit("ResumeAll");
Elliott Hughesadb460d2011-10-05 17:02:34 -07001022
1023 EnqueueClearedReferences(&cleared_references);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001024 RequestHeapTrim();
Mathieu Chartier662618f2012-06-06 12:01:47 -07001025 timings.AddSplit("Finish");
Elliott Hughes83df2ac2011-10-11 16:37:54 -07001026
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001027 // If the GC was slow, then print timings in the log.
1028 uint64_t duration = (NanoTime() - start_time) / 1000 * 1000;
1029 if (duration > MsToNs(50)) {
Mathieu Chartier637e3482012-08-17 10:41:32 -07001030 const size_t percent_free = GetPercentFree();
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001031 const size_t current_heap_size = GetUsedMemorySize();
Mathieu Chartier637e3482012-08-17 10:41:32 -07001032 const size_t total_memory = GetTotalMemory();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001033 LOG(INFO) << (gc_type == GC_PARTIAL ? "Partial " : (gc_type == GC_STICKY ? "Sticky " : ""))
Mathieu Chartier637e3482012-08-17 10:41:32 -07001034 << "GC freed " << PrettySize(bytes_freed) << ", " << percent_free << "% free, "
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001035 << PrettySize(current_heap_size) << "/" << PrettySize(total_memory) << ", "
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001036 << "paused " << PrettyDuration(duration);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001037 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001038
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001039 if (VLOG_IS_ON(heap)) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001040 timings.Dump();
1041 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001042}
Mathieu Chartiera6399032012-06-11 18:49:50 -07001043
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001044void Heap::CollectGarbageConcurrentMarkSweepPlan(GcType gc_type, bool clear_soft_references) {
1045 TimingLogger timings("ConcurrentCollectGarbageInternal", true);
1046 uint64_t root_begin = NanoTime(), root_end = 0, dirty_begin = 0, dirty_end = 0;
Mathieu Chartiera6399032012-06-11 18:49:50 -07001047
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001048 // Suspend all threads are get exclusive access to the heap.
1049 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1050 thread_list->SuspendAll();
1051 timings.AddSplit("SuspendAll");
1052 GlobalSynchronization::mutator_lock_->AssertExclusiveHeld();
1053
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001054 size_t bytes_freed = 0;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001055 Object* cleared_references = NULL;
1056 {
1057 MarkSweep mark_sweep(mark_stack_.get());
1058 timings.AddSplit("ctor");
1059
1060 mark_sweep.Init();
1061 timings.AddSplit("Init");
1062
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001063 // Swap the stacks, this is safe sunce all the mutators are suspended at this point.
1064 MarkStack* temp = allocation_stack_.release();
1065 allocation_stack_.reset(live_stack_.release());
1066 live_stack_.reset(temp);
1067
1068 // We will need to know which cards were dirty for doing concurrent processing of dirty cards.
1069 // TODO: Investigate using a mark stack instead of a vector.
1070 std::vector<byte*> dirty_cards;
1071 if (gc_type == GC_STICKY) {
1072 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1073 card_table_->GetDirtyCards(*it, dirty_cards);
1074 }
1075 }
1076
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001077 // Make sure that the tables have the correct pointer for the mark sweep.
1078 mod_union_table_->Init(&mark_sweep);
1079 zygote_mod_union_table_->Init(&mark_sweep);
1080
1081 // Clear image space cards and keep track of cards we cleared in the mod-union table.
1082 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1083 Space* space = *it;
1084 if (space->IsImageSpace()) {
1085 mod_union_table_->ClearCards(*it);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001086 timings.AddSplit("ModUnionClearCards");
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001087 } else if (space->GetGcRetentionPolicy() == GCRP_FULL_COLLECT) {
1088 zygote_mod_union_table_->ClearCards(space);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001089 timings.AddSplit("ZygoteModUnionClearCards");
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001090 } else {
1091 card_table_->ClearSpaceCards(space);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001092 timings.AddSplit("ClearCards");
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001093 }
1094 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001095
1096#if VERIFY_MOD_UNION
1097 mod_union_table_->Verify();
1098 zygote_mod_union_table_->Verify();
1099#endif
1100
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001101
1102 {
1103 WriterMutexLock mu(*GlobalSynchronization::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001104
1105 if (gc_type == GC_PARTIAL) {
1106 // Copy the mark bits over from the live bits, do this as early as possible or else we can
1107 // accidentally un-mark roots.
1108 // Needed for scanning dirty objects.
1109 for (Spaces::iterator it = spaces_.begin();it != spaces_.end(); ++it) {
1110 if ((*it)->GetGcRetentionPolicy() == GCRP_FULL_COLLECT) {
1111 mark_sweep.CopyMarkBits(*it);
1112 }
1113 }
1114 timings.AddSplit("CopyMarkBits");
1115 mark_sweep.SetCondemned(reinterpret_cast<Object*>(alloc_space_->Begin()));
1116 } else if (gc_type == GC_STICKY) {
1117 for (Spaces::iterator it = spaces_.begin();it != spaces_.end(); ++it) {
1118 if ((*it)->GetGcRetentionPolicy() != GCRP_NEVER_COLLECT) {
1119 mark_sweep.CopyMarkBits(*it);
1120 }
1121 }
1122 timings.AddSplit("CopyMarkBits");
1123 // We need to unmark the new objects since we marked them as live earlier to avoid verify
1124 // objects failing.
1125 if (VERIFY_OBJECT_ENABLED) {
1126 UnMarkStack(live_stack_.get());
1127 }
1128 mark_sweep.SetCondemned(reinterpret_cast<Object*>(alloc_space_->Begin()));
1129 }
1130
1131 // TODO: Investigate whether or not this is really necessary for sticky mark bits.
1132 MarkStackAsLive(live_stack_.get());
1133
1134 if (gc_type != GC_STICKY) {
1135 live_stack_->Reset();
1136 mark_sweep.MarkRoots();
1137 timings.AddSplit("MarkRoots");
1138 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001139 }
1140
1141 // Roots are marked on the bitmap and the mark_stack is empty.
1142 DCHECK(mark_sweep.IsMarkStackEmpty());
1143
1144 // Allow mutators to go again, acquire share on mutator_lock_ to continue.
1145 thread_list->ResumeAll();
1146 {
1147 ReaderMutexLock reader_lock(*GlobalSynchronization::mutator_lock_);
1148 root_end = NanoTime();
1149 timings.AddSplit("RootEnd");
1150
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001151 WriterMutexLock mu(*GlobalSynchronization::heap_bitmap_lock_);
1152 if (gc_type != GC_STICKY) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001153 // Update zygote mod union table.
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001154 if (gc_type == GC_PARTIAL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001155 zygote_mod_union_table_->Update();
1156 timings.AddSplit("UpdateZygoteModUnionTable");
1157
1158 zygote_mod_union_table_->MarkReferences();
1159 timings.AddSplit("ZygoteMarkReferences");
1160 }
1161
1162 // Processes the cards we cleared earlier and adds their objects into the mod-union table.
1163 mod_union_table_->Update();
1164 timings.AddSplit("UpdateModUnionTable");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001165
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001166 // Scans all objects in the mod-union table.
1167 mod_union_table_->MarkReferences();
1168 timings.AddSplit("MarkImageToAllocSpaceReferences");
1169
1170 // Recursively mark all the non-image bits set in the mark bitmap.
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001171 mark_sweep.RecursiveMark(gc_type == GC_PARTIAL, timings);
1172 } else {
1173 mark_sweep.RecursiveMarkCards(card_table_.get(), dirty_cards, timings);
1174 mark_sweep.DisableFinger();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001175 }
1176 }
1177 // Release share on mutator_lock_ and then get exclusive access.
1178 dirty_begin = NanoTime();
1179 thread_list->SuspendAll();
1180 timings.AddSplit("ReSuspend");
1181 GlobalSynchronization::mutator_lock_->AssertExclusiveHeld();
1182
1183 {
1184 WriterMutexLock mu(*GlobalSynchronization::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001185
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001186 // Re-mark root set.
1187 mark_sweep.ReMarkRoots();
1188 timings.AddSplit("ReMarkRoots");
1189
1190 // Scan dirty objects, this is only required if we are not doing concurrent GC.
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001191 mark_sweep.RecursiveMarkDirtyObjects(false);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001192 timings.AddSplit("RecursiveMarkDirtyObjects");
1193 }
1194 {
1195 ReaderMutexLock mu(*GlobalSynchronization::heap_bitmap_lock_);
1196 mark_sweep.ProcessReferences(clear_soft_references);
1197 timings.AddSplit("ProcessReferences");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001198
1199 // This doesn't work with mutators unpaused for some reason, TODO: Fix.
1200 mark_sweep.SweepSystemWeaks(false);
1201 timings.AddSplit("SweepSystemWeaks");
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001202 }
1203 // Swap the live and mark bitmaps for each alloc space. This is needed since sweep re-swaps
1204 // these bitmaps. Doing this enables us to sweep with the heap unlocked since new allocations
1205 // set the live bit, but since we have the bitmaps reversed at this point, this sets the mark
1206 // bit instead, resulting in no new allocated objects being incorrectly freed by sweep.
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001207 bool swap = true;
1208 if (swap) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001209 WriterMutexLock mu(*GlobalSynchronization::heap_bitmap_lock_);
1210 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1211 Space* space = *it;
1212 // We never allocate into zygote spaces.
1213 if (space->GetGcRetentionPolicy() == GCRP_ALWAYS_COLLECT) {
1214 live_bitmap_->ReplaceBitmap(space->GetLiveBitmap(), space->GetMarkBitmap());
1215 mark_bitmap_->ReplaceBitmap(space->GetMarkBitmap(), space->GetLiveBitmap());
1216 space->AsAllocSpace()->SwapBitmaps();
1217 }
1218 }
1219 }
1220
1221 if (kIsDebugBuild) {
1222 // Verify that we only reach marked objects from the image space.
1223 ReaderMutexLock mu(*GlobalSynchronization::heap_bitmap_lock_);
1224 mark_sweep.VerifyImageRoots();
1225 timings.AddSplit("VerifyImageRoots");
1226 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001227
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001228 thread_list->ResumeAll();
1229 dirty_end = NanoTime();
1230 GlobalSynchronization::mutator_lock_->AssertNotHeld();
1231
1232 {
1233 // TODO: this lock shouldn't be necessary (it's why we did the bitmap flip above).
1234 WriterMutexLock mu(*GlobalSynchronization::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001235 if (gc_type != GC_STICKY) {
1236 mark_sweep.Sweep(gc_type == GC_PARTIAL, swap);
1237 } else {
1238 mark_sweep.SweepArray(timings, live_stack_.get(), swap);
1239 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001240 timings.AddSplit("Sweep");
1241 }
1242
1243 cleared_references = mark_sweep.GetClearedReferences();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001244 bytes_freed = mark_sweep.GetFreedBytes();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001245 }
1246
1247 GrowForUtilization();
1248 timings.AddSplit("GrowForUtilization");
1249
1250 EnqueueClearedReferences(&cleared_references);
1251 RequestHeapTrim();
1252 timings.AddSplit("Finish");
1253
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001254 // If the GC was slow, then print timings in the log.
1255 uint64_t pause_roots = (root_end - root_begin) / 1000 * 1000;
1256 uint64_t pause_dirty = (dirty_end - dirty_begin) / 1000 * 1000;
Mathieu Chartier637e3482012-08-17 10:41:32 -07001257 uint64_t duration = (NanoTime() - root_begin) / 1000 * 1000;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001258 if (pause_roots > MsToNs(5) || pause_dirty > MsToNs(5)) {
Mathieu Chartier637e3482012-08-17 10:41:32 -07001259 const size_t percent_free = GetPercentFree();
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001260 const size_t current_heap_size = GetUsedMemorySize();
Mathieu Chartier637e3482012-08-17 10:41:32 -07001261 const size_t total_memory = GetTotalMemory();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001262 LOG(INFO) << (gc_type == GC_PARTIAL ? "Partial " : (gc_type == GC_STICKY ? "Sticky " : ""))
Mathieu Chartier637e3482012-08-17 10:41:32 -07001263 << "Concurrent GC freed " << PrettySize(bytes_freed) << ", " << percent_free
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001264 << "% free, " << PrettySize(current_heap_size) << "/"
Mathieu Chartier637e3482012-08-17 10:41:32 -07001265 << PrettySize(total_memory) << ", " << "paused " << PrettyDuration(pause_roots)
1266 << "+" << PrettyDuration(pause_dirty) << " total " << PrettyDuration(duration);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001267 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001268
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001269 if (VLOG_IS_ON(heap)) {
1270 timings.Dump();
1271 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001272}
1273
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -07001274bool Heap::WaitForConcurrentGcToComplete() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001275 if (concurrent_gc_) {
1276 bool do_wait = false;
1277 uint64_t wait_start;
1278 {
1279 // Check if GC is running holding gc_complete_lock_.
1280 MutexLock mu(*gc_complete_lock_);
1281 if (is_gc_running_) {
1282 wait_start = NanoTime();
1283 do_wait = true;
1284 }
Mathieu Chartiera6399032012-06-11 18:49:50 -07001285 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001286 if (do_wait) {
1287 // We must wait, change thread state then sleep on gc_complete_cond_;
1288 ScopedThreadStateChange tsc(Thread::Current(), kWaitingForGcToComplete);
1289 {
1290 MutexLock mu(*gc_complete_lock_);
1291 while (is_gc_running_) {
1292 gc_complete_cond_->Wait(*gc_complete_lock_);
1293 }
1294 }
1295 uint64_t wait_time = NanoTime() - wait_start;
1296 if (wait_time > MsToNs(5)) {
1297 LOG(INFO) << "WaitForConcurrentGcToComplete blocked for " << PrettyDuration(wait_time);
1298 }
1299 return true;
1300 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001301 }
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -07001302 return false;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001303}
1304
Elliott Hughesc967f782012-04-16 10:23:15 -07001305void Heap::DumpForSigQuit(std::ostream& os) {
1306 os << "Heap: " << GetPercentFree() << "% free, "
1307 << PrettySize(num_bytes_allocated_) << "/" << PrettySize(GetTotalMemory())
Elliott Hughesae80b492012-04-24 10:43:17 -07001308 << "; " << num_objects_allocated_ << " objects\n";
Elliott Hughesc967f782012-04-16 10:23:15 -07001309}
1310
1311size_t Heap::GetPercentFree() {
1312 size_t total = GetTotalMemory();
1313 return 100 - static_cast<size_t>(100.0f * static_cast<float>(num_bytes_allocated_) / total);
1314}
1315
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001316void Heap::SetIdealFootprint(size_t max_allowed_footprint) {
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001317 AllocSpace* alloc_space = alloc_space_;
1318 // TODO: Behavior for multiple alloc spaces?
1319 size_t alloc_space_capacity = alloc_space->Capacity();
1320 if (max_allowed_footprint > alloc_space_capacity) {
1321 VLOG(gc) << "Clamp target GC heap from " << PrettySize(max_allowed_footprint)
1322 << " to " << PrettySize(alloc_space_capacity);
1323 max_allowed_footprint = alloc_space_capacity;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001324 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001325 alloc_space->SetFootprintLimit(max_allowed_footprint);
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001326}
1327
Ian Rogers3bb17a62012-01-27 23:56:44 -08001328// kHeapIdealFree is the ideal maximum free size, when we grow the heap for utilization.
Shih-wei Liao7f1caab2011-10-06 12:11:04 -07001329static const size_t kHeapIdealFree = 2 * MB;
Ian Rogers3bb17a62012-01-27 23:56:44 -08001330// kHeapMinFree guarantees that you always have at least 512 KB free, when you grow for utilization,
1331// regardless of target utilization ratio.
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001332static const size_t kHeapMinFree = kHeapIdealFree / 4;
1333
Carl Shapiro69759ea2011-07-21 18:13:35 -07001334void Heap::GrowForUtilization() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001335 size_t target_size;
1336 bool use_footprint_limit = false;
1337 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001338 // We know what our utilization is at this moment.
1339 // This doesn't actually resize any memory. It just lets the heap grow more when necessary.
1340 target_size = num_bytes_allocated_ / Heap::GetTargetHeapUtilization();
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001341
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001342 if (target_size > num_bytes_allocated_ + kHeapIdealFree) {
1343 target_size = num_bytes_allocated_ + kHeapIdealFree;
1344 } else if (target_size < num_bytes_allocated_ + kHeapMinFree) {
1345 target_size = num_bytes_allocated_ + kHeapMinFree;
1346 }
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001347
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001348 // Calculate when to perform the next ConcurrentGC.
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001349 if (GetTotalMemory() - GetUsedMemorySize() < concurrent_min_free_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001350 // Not enough free memory to perform concurrent GC.
1351 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
1352 } else {
1353 // Compute below to avoid holding both the statistics and the alloc space lock
1354 use_footprint_limit = true;
1355 }
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001356 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001357
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001358 if (use_footprint_limit) {
1359 size_t foot_print_limit = alloc_space_->GetFootprintLimit();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001360 concurrent_start_bytes_ = foot_print_limit - concurrent_start_size_;
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001361 }
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001362 SetIdealFootprint(target_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001363}
1364
jeffhaoc1160702011-10-27 15:48:45 -07001365void Heap::ClearGrowthLimit() {
jeffhaoc1160702011-10-27 15:48:45 -07001366 WaitForConcurrentGcToComplete();
jeffhaoc1160702011-10-27 15:48:45 -07001367 alloc_space_->ClearGrowthLimit();
1368}
1369
Elliott Hughesadb460d2011-10-05 17:02:34 -07001370void Heap::SetReferenceOffsets(MemberOffset reference_referent_offset,
1371 MemberOffset reference_queue_offset,
1372 MemberOffset reference_queueNext_offset,
1373 MemberOffset reference_pendingNext_offset,
1374 MemberOffset finalizer_reference_zombie_offset) {
1375 reference_referent_offset_ = reference_referent_offset;
1376 reference_queue_offset_ = reference_queue_offset;
1377 reference_queueNext_offset_ = reference_queueNext_offset;
1378 reference_pendingNext_offset_ = reference_pendingNext_offset;
1379 finalizer_reference_zombie_offset_ = finalizer_reference_zombie_offset;
1380 CHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1381 CHECK_NE(reference_queue_offset_.Uint32Value(), 0U);
1382 CHECK_NE(reference_queueNext_offset_.Uint32Value(), 0U);
1383 CHECK_NE(reference_pendingNext_offset_.Uint32Value(), 0U);
1384 CHECK_NE(finalizer_reference_zombie_offset_.Uint32Value(), 0U);
1385}
1386
1387Object* Heap::GetReferenceReferent(Object* reference) {
1388 DCHECK(reference != NULL);
1389 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1390 return reference->GetFieldObject<Object*>(reference_referent_offset_, true);
1391}
1392
1393void Heap::ClearReferenceReferent(Object* reference) {
1394 DCHECK(reference != NULL);
1395 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1396 reference->SetFieldObject(reference_referent_offset_, NULL, true);
1397}
1398
1399// Returns true if the reference object has not yet been enqueued.
1400bool Heap::IsEnqueuable(const Object* ref) {
1401 DCHECK(ref != NULL);
1402 const Object* queue = ref->GetFieldObject<Object*>(reference_queue_offset_, false);
1403 const Object* queue_next = ref->GetFieldObject<Object*>(reference_queueNext_offset_, false);
1404 return (queue != NULL) && (queue_next == NULL);
1405}
1406
1407void Heap::EnqueueReference(Object* ref, Object** cleared_reference_list) {
1408 DCHECK(ref != NULL);
1409 CHECK(ref->GetFieldObject<Object*>(reference_queue_offset_, false) != NULL);
1410 CHECK(ref->GetFieldObject<Object*>(reference_queueNext_offset_, false) == NULL);
1411 EnqueuePendingReference(ref, cleared_reference_list);
1412}
1413
1414void Heap::EnqueuePendingReference(Object* ref, Object** list) {
1415 DCHECK(ref != NULL);
1416 DCHECK(list != NULL);
1417
1418 if (*list == NULL) {
1419 ref->SetFieldObject(reference_pendingNext_offset_, ref, false);
1420 *list = ref;
1421 } else {
1422 Object* head = (*list)->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
1423 ref->SetFieldObject(reference_pendingNext_offset_, head, false);
1424 (*list)->SetFieldObject(reference_pendingNext_offset_, ref, false);
1425 }
1426}
1427
1428Object* Heap::DequeuePendingReference(Object** list) {
1429 DCHECK(list != NULL);
1430 DCHECK(*list != NULL);
1431 Object* head = (*list)->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
1432 Object* ref;
1433 if (*list == head) {
1434 ref = *list;
1435 *list = NULL;
1436 } else {
1437 Object* next = head->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
1438 (*list)->SetFieldObject(reference_pendingNext_offset_, next, false);
1439 ref = head;
1440 }
1441 ref->SetFieldObject(reference_pendingNext_offset_, NULL, false);
1442 return ref;
1443}
1444
Ian Rogers5d4bdc22011-11-02 22:15:43 -07001445void Heap::AddFinalizerReference(Thread* self, Object* object) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001446 ScopedObjectAccess soa(self);
Elliott Hughes77405792012-03-15 15:22:12 -07001447 JValue args[1];
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07001448 args[0].SetL(object);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001449 soa.DecodeMethod(WellKnownClasses::java_lang_ref_FinalizerReference_add)->Invoke(self,
1450 NULL, args, NULL);
1451}
1452
1453size_t Heap::GetBytesAllocated() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001454 return num_bytes_allocated_;
1455}
1456
1457size_t Heap::GetObjectsAllocated() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001458 return num_objects_allocated_;
1459}
1460
1461size_t Heap::GetConcurrentStartSize() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001462 return concurrent_start_size_;
1463}
1464
1465size_t Heap::GetConcurrentMinFree() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001466 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 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001533 float utilization = static_cast<float>(num_bytes_allocated_) / alloc_space_->Size();
1534 if ((utilization > 0.75f) || ((ms_time - last_trim_time_) < 2 * 1000)) {
1535 // Don't bother trimming the heap if it's more than 75% utilized, or if a
1536 // heap trim occurred in the last two seconds.
1537 return;
1538 }
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001539 }
Mathieu Chartiera6399032012-06-11 18:49:50 -07001540 if (!Runtime::Current()->IsFinishedStarting() || Runtime::Current()->IsShuttingDown()) {
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001541 // Heap trimming isn't supported without a Java runtime or Daemons (such as at dex2oat time)
Mathieu Chartiera6399032012-06-11 18:49:50 -07001542 // Also: we do not wish to start a heap trim if the runtime is shutting down.
Ian Rogerse1d490c2012-02-03 09:09:07 -08001543 return;
1544 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001545 last_trim_time_ = ms_time;
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001546 JNIEnv* env = Thread::Current()->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07001547 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
1548 DCHECK(WellKnownClasses::java_lang_Daemons_requestHeapTrim != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001549 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
1550 WellKnownClasses::java_lang_Daemons_requestHeapTrim);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001551 CHECK(!env->ExceptionCheck());
1552}
1553
Carl Shapiro69759ea2011-07-21 18:13:35 -07001554} // namespace art