blob: 47473e3c53ccc89bf8aa0d0c45fe4edbf1c40ee3 [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 Chartierfd678be2012-08-30 14:50:54 -0700151 pre_gc_verify_heap_(false),
152 post_gc_verify_heap_(false),
153 verify_mod_union_table_(false),
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700154 last_trim_time_(0),
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700155 try_running_gc_(false),
156 requesting_gc_(false),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800157 reference_referent_offset_(0),
158 reference_queue_offset_(0),
159 reference_queueNext_offset_(0),
160 reference_pendingNext_offset_(0),
161 finalizer_reference_zombie_offset_(0),
162 target_utilization_(0.5),
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700163 verify_objects_(false) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800164 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800165 LOG(INFO) << "Heap() entering";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700166 }
167
Ian Rogers30fab402012-01-23 15:43:46 -0800168 // Compute the bounds of all spaces for allocating live and mark bitmaps
169 // there will be at least one space (the alloc space)
170 Space* first_space = NULL;
171 Space* last_space = NULL;
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700172
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700173 live_bitmap_.reset(new HeapBitmap(this));
174 mark_bitmap_.reset(new HeapBitmap(this));
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700175
Ian Rogers30fab402012-01-23 15:43:46 -0800176 // Requested begin for the alloc space, to follow the mapped image and oat files
177 byte* requested_begin = NULL;
Brian Carlstrom5643b782012-02-05 12:32:53 -0800178 std::string image_file_name(original_image_file_name);
179 if (!image_file_name.empty()) {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700180 Space* image_space = NULL;
181
Brian Carlstrom5643b782012-02-05 12:32:53 -0800182 if (OS::FileExists(image_file_name.c_str())) {
183 // If the /system file exists, it should be up-to-date, don't try to generate
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700184 image_space = Space::CreateImageSpace(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800185 } else {
186 // If the /system file didn't exist, we need to use one from the art-cache.
187 // If the cache file exists, try to open, but if it fails, regenerate.
188 // If it does not exist, generate.
189 image_file_name = GetArtCacheFilenameOrDie(image_file_name);
190 if (OS::FileExists(image_file_name.c_str())) {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700191 image_space = Space::CreateImageSpace(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800192 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700193 if (image_space == NULL) {
Brian Carlstrom5643b782012-02-05 12:32:53 -0800194 if (!GenerateImage(image_file_name)) {
195 LOG(FATAL) << "Failed to generate image: " << image_file_name;
196 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700197 image_space = Space::CreateImageSpace(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800198 }
199 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700200 if (image_space == NULL) {
Brian Carlstrom223f20f2012-02-04 23:06:55 -0800201 LOG(FATAL) << "Failed to create space from " << image_file_name;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700202 }
Brian Carlstrom5643b782012-02-05 12:32:53 -0800203
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700204 AddSpace(image_space);
205 UpdateFirstAndLastSpace(&first_space, &last_space, image_space);
Ian Rogers30fab402012-01-23 15:43:46 -0800206 // Oat files referenced by image files immediately follow them in memory, ensure alloc space
207 // isn't going to get in the middle
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700208 byte* oat_end_addr = GetImageSpace()->GetImageHeader().GetOatEnd();
209 CHECK(oat_end_addr > GetImageSpace()->End());
Ian Rogers30fab402012-01-23 15:43:46 -0800210 if (oat_end_addr > requested_begin) {
211 requested_begin = reinterpret_cast<byte*>(RoundUp(reinterpret_cast<uintptr_t>(oat_end_addr),
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700212 kPageSize));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700213 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700214 }
215
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700216 UniquePtr<AllocSpace> alloc_space(Space::CreateAllocSpace(
217 "alloc space", initial_size, growth_limit, capacity, requested_begin));
218 alloc_space_ = alloc_space.release();
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700219 CHECK(alloc_space_ != NULL) << "Failed to create alloc space";
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700220 AddSpace(alloc_space_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700221
Ian Rogers30fab402012-01-23 15:43:46 -0800222 UpdateFirstAndLastSpace(&first_space, &last_space, alloc_space_);
223 byte* heap_begin = first_space->Begin();
Ian Rogers3bb17a62012-01-27 23:56:44 -0800224 size_t heap_capacity = (last_space->Begin() - first_space->Begin()) + last_space->NonGrowthLimitCapacity();
Carl Shapiro69759ea2011-07-21 18:13:35 -0700225
Ian Rogers30fab402012-01-23 15:43:46 -0800226 // Mark image objects in the live bitmap
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800227 for (size_t i = 0; i < spaces_.size(); ++i) {
Ian Rogers30fab402012-01-23 15:43:46 -0800228 Space* space = spaces_[i];
229 if (space->IsImageSpace()) {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700230 space->AsImageSpace()->RecordImageAllocations(space->GetLiveBitmap());
Ian Rogers30fab402012-01-23 15:43:46 -0800231 }
232 }
233
Elliott Hughes6c9c06d2011-11-07 16:43:47 -0800234 // Allocate the card table.
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700235 card_table_.reset(CardTable::Create(heap_begin, heap_capacity));
236 CHECK(card_table_.get() != NULL) << "Failed to create card table";
Ian Rogers5d76c432011-10-31 21:42:49 -0700237
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700238 mod_union_table_.reset(new ModUnionTableToZygoteAllocspace<ModUnionTableReferenceCache>(this));
239 CHECK(mod_union_table_.get() != NULL) << "Failed to create mod-union table";
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700240
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700241 zygote_mod_union_table_.reset(new ModUnionTableCardCache(this));
242 CHECK(zygote_mod_union_table_.get() != NULL) << "Failed to create Zygote mod-union table";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700243
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700244 // TODO: Count objects in the image space here.
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700245 num_bytes_allocated_ = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700246 num_objects_allocated_ = 0;
247
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700248 // Max stack size in bytes.
249 static const size_t max_stack_size = capacity / SpaceBitmap::kAlignment * kWordSize;
250
251 // TODO: Rename MarkStack to a more generic name?
252 mark_stack_.reset(MarkStack::Create("dalvik-mark-stack", max_stack_size));
253 allocation_stack_.reset(MarkStack::Create("dalvik-allocation-stack", max_stack_size));
254 live_stack_.reset(MarkStack::Create("dalvik-live-stack", max_stack_size));
Mathieu Chartier5301cd22012-05-31 12:11:36 -0700255
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800256 // It's still too early to take a lock because there are no threads yet,
Elliott Hughes92b3b562011-09-08 16:32:26 -0700257 // but we can create the heap lock now. We don't create it earlier to
258 // make it clear that you can't use locks during heap initialization.
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700259 gc_complete_lock_ = new Mutex("GC complete lock");
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700260 gc_complete_cond_.reset(new ConditionVariable("GC complete condition variable"));
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700261
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800262 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800263 LOG(INFO) << "Heap() exiting";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700264 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700265}
266
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700267// Sort spaces based on begin address
268class SpaceSorter {
269 public:
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700270 bool operator ()(const Space* a, const Space* b) const {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700271 return a->Begin() < b->Begin();
272 }
273};
274
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800275void Heap::AddSpace(Space* space) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700276 WriterMutexLock mu(*GlobalSynchronization::heap_bitmap_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700277 DCHECK(space != NULL);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700278 DCHECK(space->GetLiveBitmap() != NULL);
279 live_bitmap_->AddSpaceBitmap(space->GetLiveBitmap());
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700280 DCHECK(space->GetMarkBitmap() != NULL);
281 mark_bitmap_->AddSpaceBitmap(space->GetMarkBitmap());
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800282 spaces_.push_back(space);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700283 if (space->IsAllocSpace()) {
284 alloc_space_ = space->AsAllocSpace();
285 }
286
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700287 // Ensure that spaces remain sorted in increasing order of start address (required for CMS finger)
288 std::sort(spaces_.begin(), spaces_.end(), SpaceSorter());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700289
290 // Ensure that ImageSpaces < ZygoteSpaces < AllocSpaces so that we can do address based checks to
291 // avoid redundant marking.
292 bool seen_zygote = false, seen_alloc = false;
293 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
294 Space* space = *it;
295 if (space->IsImageSpace()) {
296 DCHECK(!seen_zygote);
297 DCHECK(!seen_alloc);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700298 } else if (space->IsZygoteSpace()) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700299 DCHECK(!seen_alloc);
300 seen_zygote = true;
301 } else if (space->IsAllocSpace()) {
302 seen_alloc = true;
303 }
304 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800305}
306
307Heap::~Heap() {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700308 // If we don't reset then the mark stack complains in it's destructor.
309 allocation_stack_->Reset();
310 live_stack_->Reset();
311
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800312 VLOG(heap) << "~Heap()";
Elliott Hughesb3e66df2012-01-12 14:49:18 -0800313 // We can't take the heap lock here because there might be a daemon thread suspended with the
314 // heap lock held. We know though that no non-daemon threads are executing, and we know that
315 // all daemon threads are suspended, and we also know that the threads list have been deleted, so
316 // 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 -0700317 STLDeleteElements(&spaces_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700318 delete gc_complete_lock_;
319
Carl Shapiro69759ea2011-07-21 18:13:35 -0700320}
321
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700322Space* Heap::FindSpaceFromObject(const Object* obj) const {
323 // TODO: C++0x auto
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700324 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
325 if ((*it)->Contains(obj)) {
326 return *it;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700327 }
328 }
329 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
330 return NULL;
331}
332
333ImageSpace* Heap::GetImageSpace() {
334 // TODO: C++0x auto
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700335 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
336 if ((*it)->IsImageSpace()) {
337 return (*it)->AsImageSpace();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700338 }
339 }
340 return NULL;
341}
342
343AllocSpace* Heap::GetAllocSpace() {
344 return alloc_space_;
345}
346
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700347static void MSpaceChunkCallback(void* start, void* end, size_t used_bytes, void* arg) {
348 size_t& max_contiguous_allocation = *reinterpret_cast<size_t*>(arg);
349
350 size_t chunk_size = static_cast<size_t>(reinterpret_cast<uint8_t*>(end) - reinterpret_cast<uint8_t*>(start));
351 size_t chunk_free_bytes = 0;
352 if (used_bytes < chunk_size) {
353 chunk_free_bytes = chunk_size - used_bytes;
354 }
355
356 if (chunk_free_bytes > max_contiguous_allocation) {
357 max_contiguous_allocation = chunk_free_bytes;
358 }
359}
360
361Object* Heap::AllocObject(Class* c, size_t byte_count) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700362 DCHECK(c == NULL || (c->IsClassClass() && byte_count >= sizeof(Class)) ||
363 (c->IsVariableSize() || c->GetObjectSize() == byte_count) ||
364 strlen(ClassHelper(c).GetDescriptor()) == 0);
365 DCHECK_GE(byte_count, sizeof(Object));
Mathieu Chartier037813d2012-08-23 16:44:59 -0700366 Object* obj = Allocate(alloc_space_, byte_count);
367 if (LIKELY(obj != NULL)) {
368#if VERIFY_OBJECT_ENABLED
369 WriterMutexLock mu(*GlobalSynchronization::heap_bitmap_lock_);
370 // Verify objects doesn't like objects in allocation stack not being marked as live.
371 live_bitmap_->Set(obj);
372#endif
373
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700374 obj->SetClass(c);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700375
376 // Record allocation after since we want to use the atomic add for the atomic fence to guard
377 // the SetClass since we do not want the class to appear NULL in another thread.
378 RecordAllocation(alloc_space_, obj);
379
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700380 if (Dbg::IsAllocTrackingEnabled()) {
381 Dbg::RecordAllocation(c, byte_count);
Elliott Hughes418dfe72011-10-06 18:56:27 -0700382 }
Mathieu Chartier637e3482012-08-17 10:41:32 -0700383 const bool request_concurrent_gc = num_bytes_allocated_ >= concurrent_start_bytes_;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700384 if (request_concurrent_gc) {
385 // The SirtRef is necessary since the calls in RequestConcurrentGC are a safepoint.
386 SirtRef<Object> ref(obj);
387 RequestConcurrentGC();
388 }
389 VerifyObject(obj);
390
391 // Additional verification to ensure that we did not allocate into a zygote space.
392 DCHECK(!have_zygote_space_ || !FindSpaceFromObject(obj)->IsZygoteSpace());
393
394 return obj;
395 }
Mathieu Chartier037813d2012-08-23 16:44:59 -0700396 int64_t total_bytes_free = GetFreeMemory();
397 size_t max_contiguous_allocation = 0;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700398 // TODO: C++0x auto
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700399 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
400 if ((*it)->IsAllocSpace()) {
401 (*it)->AsAllocSpace()->Walk(MSpaceChunkCallback, &max_contiguous_allocation);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700402 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700403 }
Elliott Hughes418dfe72011-10-06 18:56:27 -0700404
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700405 std::string msg(StringPrintf("Failed to allocate a %zd-byte %s (%lld total bytes free; largest possible contiguous allocation %zd bytes)",
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700406 byte_count, PrettyDescriptor(c).c_str(), total_bytes_free, max_contiguous_allocation));
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700407 Thread::Current()->ThrowOutOfMemoryError(msg.c_str());
Elliott Hughes418dfe72011-10-06 18:56:27 -0700408 return NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700409}
410
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700411bool Heap::IsHeapAddress(const Object* obj) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700412 // Note: we deliberately don't take the lock here, and mustn't test anything that would
413 // require taking the lock.
Elliott Hughes88c5c352012-03-15 18:49:48 -0700414 if (obj == NULL) {
415 return true;
416 }
417 if (!IsAligned<kObjectAlignment>(obj)) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700418 return false;
419 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800420 for (size_t i = 0; i < spaces_.size(); ++i) {
Ian Rogers30fab402012-01-23 15:43:46 -0800421 if (spaces_[i]->Contains(obj)) {
422 return true;
423 }
424 }
425 return false;
Elliott Hughesa2501992011-08-26 19:39:54 -0700426}
427
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700428bool Heap::IsLiveObjectLocked(const Object* obj) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700429 GlobalSynchronization::heap_bitmap_lock_->AssertReaderHeld();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700430 return IsHeapAddress(obj) && GetLiveBitmap()->Test(obj);
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700431}
432
Elliott Hughes3e465b12011-09-02 18:26:12 -0700433#if VERIFY_OBJECT_ENABLED
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700434void Heap::VerifyObject(const Object* obj) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700435 if (obj == NULL || this == NULL || !verify_objects_ || Runtime::Current()->IsShuttingDown() ||
Ian Rogers141d6222012-04-05 12:23:06 -0700436 Thread::Current() == NULL ||
jeffhao25045522012-03-13 19:34:37 -0700437 Runtime::Current()->GetThreadList()->GetLockOwner() == Thread::Current()->GetTid()) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700438 return;
439 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700440 VerifyObjectBody(obj);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700441}
442#endif
443
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700444void Heap::DumpSpaces() {
445 // TODO: C++0x auto
446 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700447 Space* space = *it;
448 LOG(INFO) << *space;
449 LOG(INFO) << *space->GetLiveBitmap();
450 LOG(INFO) << *space->GetMarkBitmap();
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700451 }
452}
453
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700454// We want to avoid bit rotting.
455void Heap::VerifyObjectBody(const Object* obj) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700456 if (!IsAligned<kObjectAlignment>(obj)) {
457 LOG(FATAL) << "Object isn't aligned: " << obj;
458 } else if (!GetLiveBitmap()->Test(obj)) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700459 DumpSpaces();
460 LOG(FATAL) << "Object is dead: " << obj;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700461 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700462
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700463 // Ignore early dawn of the universe verifications
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700464 if (!VERIFY_OBJECT_FAST && num_objects_allocated_ > 10) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700465 const byte* raw_addr = reinterpret_cast<const byte*>(obj) +
466 Object::ClassOffset().Int32Value();
467 const Class* c = *reinterpret_cast<Class* const *>(raw_addr);
468 if (c == NULL) {
469 LOG(FATAL) << "Null class in object: " << obj;
470 } else if (!IsAligned<kObjectAlignment>(c)) {
471 LOG(FATAL) << "Class isn't aligned: " << c << " in object: " << obj;
472 } else if (!GetLiveBitmap()->Test(c)) {
473 LOG(FATAL) << "Class of object is dead: " << c << " in object: " << obj;
474 }
475 // Check obj.getClass().getClass() == obj.getClass().getClass().getClass()
476 // Note: we don't use the accessors here as they have internal sanity checks
477 // that we don't want to run
478 raw_addr = reinterpret_cast<const byte*>(c) + Object::ClassOffset().Int32Value();
479 const Class* c_c = *reinterpret_cast<Class* const *>(raw_addr);
480 raw_addr = reinterpret_cast<const byte*>(c_c) + Object::ClassOffset().Int32Value();
481 const Class* c_c_c = *reinterpret_cast<Class* const *>(raw_addr);
482 CHECK_EQ(c_c, c_c_c);
483 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700484}
485
Brian Carlstrom78128a62011-09-15 17:21:19 -0700486void Heap::VerificationCallback(Object* obj, void* arg) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700487 DCHECK(obj != NULL);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700488 reinterpret_cast<Heap*>(arg)->VerifyObjectBody(obj);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700489}
490
491void Heap::VerifyHeap() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700492 ReaderMutexLock mu(*GlobalSynchronization::heap_bitmap_lock_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700493 GetLiveBitmap()->Walk(Heap::VerificationCallback, this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700494}
495
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700496void Heap::RecordAllocation(AllocSpace* space, const Object* obj) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700497 DCHECK(obj != NULL);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700498
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700499 size_t size = space->AllocationSize(obj);
500 DCHECK_GT(size, 0u);
501 COMPILE_ASSERT(sizeof(size_t) == sizeof(int32_t),
502 int32_t_must_be_same_size_as_size_t_for_used_atomic_operations);
503 android_atomic_add(
504 size, reinterpret_cast<volatile int32_t*>(reinterpret_cast<size_t>(&num_bytes_allocated_)));
505 android_atomic_add(
506 1, reinterpret_cast<volatile int32_t*>(reinterpret_cast<size_t>(&num_objects_allocated_)));
507
508 if (Runtime::Current()->HasStatsEnabled()) {
509 RuntimeStats* global_stats = Runtime::Current()->GetStats();
510 RuntimeStats* thread_stats = Thread::Current()->GetStats();
511 ++global_stats->allocated_objects;
512 ++thread_stats->allocated_objects;
513 global_stats->allocated_bytes += size;
514 thread_stats->allocated_bytes += size;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700515 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700516
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700517 allocation_stack_->AtomicPush(obj);
Carl Shapiro58551df2011-07-24 03:09:51 -0700518}
519
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700520void Heap::RecordFree(size_t freed_objects, size_t freed_bytes) {
Mathieu Chartier637e3482012-08-17 10:41:32 -0700521 COMPILE_ASSERT(sizeof(size_t) == sizeof(int32_t),
522 int32_t_must_be_same_size_as_size_t_for_used_atomic_operations);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700523 DCHECK_LE(freed_objects, num_objects_allocated_);
Mathieu Chartier637e3482012-08-17 10:41:32 -0700524 android_atomic_add(-static_cast<int32_t>(freed_objects),
Mathieu Chartier556fad32012-08-20 16:13:20 -0700525 reinterpret_cast<volatile int32_t*>(
526 reinterpret_cast<size_t>(&num_objects_allocated_)));
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700527
528 DCHECK_LE(freed_bytes, num_bytes_allocated_);
Mathieu Chartier637e3482012-08-17 10:41:32 -0700529 android_atomic_add(-static_cast<int32_t>(freed_bytes),
Mathieu Chartier556fad32012-08-20 16:13:20 -0700530 reinterpret_cast<volatile int32_t*>(
531 reinterpret_cast<size_t>(&num_bytes_allocated_)));
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700532
533 if (Runtime::Current()->HasStatsEnabled()) {
534 RuntimeStats* global_stats = Runtime::Current()->GetStats();
535 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700536 global_stats->freed_objects += freed_objects;
537 thread_stats->freed_objects += freed_objects;
Elliott Hughes307f75d2011-10-12 18:04:40 -0700538 global_stats->freed_bytes += freed_bytes;
539 thread_stats->freed_bytes += freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700540 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700541}
542
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700543Object* Heap::Allocate(AllocSpace* space, size_t alloc_size) {
544 Thread* self = Thread::Current();
Ian Rogers0399dde2012-06-06 17:09:28 -0700545 // Since allocation can cause a GC which will need to SuspendAll, make sure all allocations are
546 // done in the runnable state where suspension is expected.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700547#ifndef NDEBUG
548 {
549 MutexLock mu(*GlobalSynchronization::thread_suspend_count_lock_);
550 CHECK_EQ(self->GetState(), kRunnable);
551 }
552 self->AssertThreadSuspensionIsAllowable();
553#endif
Brian Carlstromb82b6872011-10-26 17:18:07 -0700554
Ian Rogers30fab402012-01-23 15:43:46 -0800555 Object* ptr = space->AllocWithoutGrowth(alloc_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700556 if (ptr != NULL) {
557 return ptr;
558 }
559
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700560 // The allocation failed. If the GC is running, block until it completes else request a
561 // foreground partial collection.
562 if (!WaitForConcurrentGcToComplete()) {
563 // No concurrent GC so perform a foreground collection.
564 if (Runtime::Current()->HasStatsEnabled()) {
565 ++Runtime::Current()->GetStats()->gc_for_alloc_count;
566 ++Thread::Current()->GetStats()->gc_for_alloc_count;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700567 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700568 self->TransitionFromRunnableToSuspended(kWaitingPerformingGc);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700569 const size_t alloc_space_size = alloc_space_->Size();
570 if (alloc_space_size > kMinAllocSpaceSizeForStickyGC
571 && alloc_space_->Capacity() - alloc_space_size >= kMinRemainingSpaceForStickyGC) {
572 CollectGarbageInternal(GC_STICKY, false);
573 } else {
574 CollectGarbageInternal(have_zygote_space_ ? GC_PARTIAL : GC_FULL, false);
575 }
576 self->TransitionFromSuspendedToRunnable();
577 } else if (have_zygote_space_) {
578 // TODO: Keep track of what kind of Gc we waited to complete and is this to figure out what Gc
579 // to do.
580 // Try a partial Gc.
581 if (Runtime::Current()->HasStatsEnabled()) {
582 ++Runtime::Current()->GetStats()->gc_for_alloc_count;
583 ++Thread::Current()->GetStats()->gc_for_alloc_count;
584 }
585 self->TransitionFromRunnableToSuspended(kWaitingPerformingGc);
586 CollectGarbageInternal(GC_PARTIAL, false);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700587 self->TransitionFromSuspendedToRunnable();
Carl Shapiro69759ea2011-07-21 18:13:35 -0700588 }
589
Ian Rogers30fab402012-01-23 15:43:46 -0800590 ptr = space->AllocWithoutGrowth(alloc_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700591 if (ptr != NULL) {
592 return ptr;
593 }
594
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700595 // Partial GC didn't free enough memory, try a full GC.
596 if (Runtime::Current()->HasStatsEnabled()) {
597 ++Runtime::Current()->GetStats()->gc_for_alloc_count;
598 ++Thread::Current()->GetStats()->gc_for_alloc_count;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700599 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700600 self->TransitionFromRunnableToSuspended(kWaitingPerformingGc);
601 CollectGarbageInternal(GC_FULL, false);
602 self->TransitionFromSuspendedToRunnable();
603 ptr = space->AllocWithoutGrowth(alloc_size);
604 if (ptr != NULL) {
605 return ptr;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700606 }
607
608 // Allocations have failed after GCs; this is an exceptional state.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700609 // Try harder, growing the heap if necessary.
Ian Rogers30fab402012-01-23 15:43:46 -0800610 ptr = space->AllocWithGrowth(alloc_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700611 if (ptr != NULL) {
Ian Rogers30fab402012-01-23 15:43:46 -0800612 size_t new_footprint = space->GetFootprintLimit();
Elliott Hughes418dfe72011-10-06 18:56:27 -0700613 // OLD-TODO: may want to grow a little bit more so that the amount of
Carl Shapiro58551df2011-07-24 03:09:51 -0700614 // free space is equal to the old free space + the
615 // utilization slop for the new allocation.
Ian Rogers3bb17a62012-01-27 23:56:44 -0800616 VLOG(gc) << "Grow heap (frag case) to " << PrettySize(new_footprint)
Ian Rogers162a31c2012-01-31 16:14:31 -0800617 << " for a " << PrettySize(alloc_size) << " allocation";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700618 return ptr;
619 }
620
Elliott Hughes81ff3182012-03-23 20:35:56 -0700621 // Most allocations should have succeeded by now, so the heap is really full, really fragmented,
622 // or the requested size is really big. Do another GC, collecting SoftReferences this time. The
623 // VM spec requires that all SoftReferences have been collected and cleared before throwing OOME.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700624
Elliott Hughes418dfe72011-10-06 18:56:27 -0700625 // OLD-TODO: wait for the finalizers from the previous GC to finish
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700626 VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size)
627 << " allocation";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700628
629 if (Runtime::Current()->HasStatsEnabled()) {
630 ++Runtime::Current()->GetStats()->gc_for_alloc_count;
631 ++Thread::Current()->GetStats()->gc_for_alloc_count;
632 }
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -0700633 // We don't need a WaitForConcurrentGcToComplete here either.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700634 self->TransitionFromRunnableToSuspended(kWaitingPerformingGc);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700635 CollectGarbageInternal(GC_FULL, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700636 self->TransitionFromSuspendedToRunnable();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700637 return space->AllocWithGrowth(alloc_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700638}
639
Elliott Hughesbf86d042011-08-31 17:53:14 -0700640int64_t Heap::GetMaxMemory() {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700641 size_t total = 0;
642 // TODO: C++0x auto
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700643 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
644 Space* space = *it;
645 if (space->IsAllocSpace()) {
646 total += space->AsAllocSpace()->Capacity();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700647 }
648 }
649 return total;
Elliott Hughesbf86d042011-08-31 17:53:14 -0700650}
651
652int64_t Heap::GetTotalMemory() {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700653 return GetMaxMemory();
Elliott Hughesbf86d042011-08-31 17:53:14 -0700654}
655
656int64_t Heap::GetFreeMemory() {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700657 return GetMaxMemory() - num_bytes_allocated_;
Elliott Hughesbf86d042011-08-31 17:53:14 -0700658}
659
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700660class InstanceCounter {
661 public:
662 InstanceCounter(Class* c, bool count_assignable)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700663 SHARED_LOCKS_REQUIRED(GlobalSynchronization::mutator_lock_)
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700664 : class_(c), count_assignable_(count_assignable), count_(0) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700665
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700666 }
667
668 size_t GetCount() {
669 return count_;
670 }
671
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700672 static void Callback(Object* o, void* arg)
673 SHARED_LOCKS_REQUIRED(GlobalSynchronization::mutator_lock_) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700674 reinterpret_cast<InstanceCounter*>(arg)->VisitInstance(o);
675 }
676
677 private:
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700678 void VisitInstance(Object* o) SHARED_LOCKS_REQUIRED(GlobalSynchronization::mutator_lock_) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700679 Class* instance_class = o->GetClass();
680 if (count_assignable_) {
681 if (instance_class == class_) {
682 ++count_;
683 }
684 } else {
685 if (instance_class != NULL && class_->IsAssignableFrom(instance_class)) {
686 ++count_;
687 }
688 }
689 }
690
691 Class* class_;
692 bool count_assignable_;
693 size_t count_;
694};
695
696int64_t Heap::CountInstances(Class* c, bool count_assignable) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700697 ReaderMutexLock mu(*GlobalSynchronization::heap_bitmap_lock_);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700698 InstanceCounter counter(c, count_assignable);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700699 GetLiveBitmap()->Walk(InstanceCounter::Callback, &counter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700700 return counter.GetCount();
701}
702
Ian Rogers30fab402012-01-23 15:43:46 -0800703void Heap::CollectGarbage(bool clear_soft_references) {
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -0700704 // If we just waited for a GC to complete then we do not need to do another
705 // GC unless we clear soft references.
706 if (!WaitForConcurrentGcToComplete() || clear_soft_references) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700707 ScopedThreadStateChange tsc(Thread::Current(), kWaitingPerformingGc);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700708 CollectGarbageInternal(have_zygote_space_ ? GC_PARTIAL : GC_FULL, clear_soft_references);
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -0700709 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700710}
711
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700712void Heap::PreZygoteFork() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700713 static Mutex zygote_creation_lock_("zygote creation lock", kZygoteCreationLock);
714 MutexLock mu(zygote_creation_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700715
716 // Try to see if we have any Zygote spaces.
717 if (have_zygote_space_) {
718 return;
719 }
720
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700721 VLOG(heap) << "Starting PreZygoteFork with alloc space size " << PrettySize(alloc_space_->Size());
722
723 {
724 // Flush the alloc stack.
725 WriterMutexLock mu(*GlobalSynchronization::heap_bitmap_lock_);
726 FlushAllocStack();
727 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700728
729 // Replace the first alloc space we find with a zygote space.
730 // TODO: C++0x auto
731 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
732 if ((*it)->IsAllocSpace()) {
733 AllocSpace* zygote_space = (*it)->AsAllocSpace();
734
735 // Turns the current alloc space into a Zygote space and obtain the new alloc space composed
736 // of the remaining available heap memory.
737 alloc_space_ = zygote_space->CreateZygoteSpace();
738
739 // Change the GC retention policy of the zygote space to only collect when full.
740 zygote_space->SetGcRetentionPolicy(GCRP_FULL_COLLECT);
741 AddSpace(alloc_space_);
742 have_zygote_space_ = true;
743 break;
744 }
745 }
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700746
747 // Reset this since we now count the ZygoteSpace in the total heap size.
748 num_bytes_allocated_ = 0;
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700749}
750
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700751void Heap::FlushAllocStack() {
752 MarkStackAsLive(allocation_stack_.get());
753 allocation_stack_->Reset();
754}
755
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700756size_t Heap::GetUsedMemorySize() const {
757 size_t total = num_bytes_allocated_;
758 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
759 if ((*it)->IsZygoteSpace()) {
760 total += (*it)->AsAllocSpace()->Size();
761 }
762 }
763 return total;
764}
765
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700766void Heap::MarkStackAsLive(MarkStack* alloc_stack) {
767 // We can just assume everything is inside the alloc_space_'s bitmap since we should only have
768 // fresh allocations.
769 SpaceBitmap* live_bitmap = alloc_space_->GetLiveBitmap();
770
771 // Empty the allocation stack.
772 const size_t count = alloc_stack->Size();
773 for (size_t i = 0; i < count; ++i) {
774 const Object* obj = alloc_stack->Get(i);
775 DCHECK(obj != NULL);
776 live_bitmap->Set(obj);
777 }
778}
779
780void Heap::UnMarkStack(MarkStack* alloc_stack) {
781 SpaceBitmap* mark_bitmap = alloc_space_->GetMarkBitmap();
782
783 // Clear all of the things in the AllocStack.
784 size_t count = alloc_stack->Size();
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700785 for (size_t i = 0; i < count; ++i) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700786 const Object* obj = alloc_stack->Get(i);
787 DCHECK(obj != NULL);
788 if (mark_bitmap->Test(obj)) {
789 mark_bitmap->Clear(obj);
790 }
791 }
792}
793
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700794void Heap::UnMarkStackAsLive(MarkStack* alloc_stack) {
795 SpaceBitmap* live_bitmap = alloc_space_->GetLiveBitmap();
796
797 // Clear all of the things in the AllocStack.
798 size_t count = alloc_stack->Size();
799 for (size_t i = 0; i < count; ++i) {
800 const Object* obj = alloc_stack->Get(i);
801 DCHECK(obj != NULL);
802 if (live_bitmap->Test(obj)) {
803 live_bitmap->Clear(obj);
804 }
805 }
806}
807
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700808void Heap::CollectGarbageInternal(GcType gc_type, bool clear_soft_references) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700809 GlobalSynchronization::mutator_lock_->AssertNotHeld();
810#ifndef NDEBUG
811 {
812 MutexLock mu(*GlobalSynchronization::thread_suspend_count_lock_);
813 CHECK_EQ(Thread::Current()->GetState(), kWaitingPerformingGc);
814 }
815#endif
Carl Shapiro58551df2011-07-24 03:09:51 -0700816
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700817 // Ensure there is only one GC at a time.
818 bool start_collect = false;
819 while (!start_collect) {
820 {
821 MutexLock mu(*gc_complete_lock_);
822 if (!is_gc_running_) {
823 is_gc_running_ = true;
824 start_collect = true;
825 }
826 }
827 if (!start_collect) {
828 WaitForConcurrentGcToComplete();
829 // TODO: if another thread beat this one to do the GC, perhaps we should just return here?
830 // Not doing at the moment to ensure soft references are cleared.
831 }
832 }
833 gc_complete_lock_->AssertNotHeld();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700834
835 // We need to do partial GCs every now and then to avoid the heap growing too much and
836 // fragmenting.
837 if (gc_type == GC_STICKY && ++sticky_gc_count_ > kPartialGCFrequency) {
838 gc_type = GC_PARTIAL;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700839 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700840 if (gc_type != GC_STICKY) {
841 sticky_gc_count_ = 0;
842 }
843
Mathieu Chartier637e3482012-08-17 10:41:32 -0700844 if (concurrent_gc_) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700845 CollectGarbageConcurrentMarkSweepPlan(gc_type, clear_soft_references);
846 } else {
847 CollectGarbageMarkSweepPlan(gc_type, clear_soft_references);
848 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700849
Ian Rogers15bf2d32012-08-28 17:33:04 -0700850 {
851 MutexLock mu(*gc_complete_lock_);
852 is_gc_running_ = false;
853 // Wake anyone who may have been waiting for the GC to complete.
854 gc_complete_cond_->Broadcast();
855 }
856 // Inform DDMS that a GC completed.
857 Dbg::GcDidFinish();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700858}
Mathieu Chartiera6399032012-06-11 18:49:50 -0700859
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700860void Heap::CollectGarbageMarkSweepPlan(GcType gc_type, bool clear_soft_references) {
861 TimingLogger timings("CollectGarbageInternal", true);
Mathieu Chartier662618f2012-06-06 12:01:47 -0700862
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700863 std::stringstream gc_type_str;
864 gc_type_str << gc_type << " ";
865
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700866 // Suspend all threads are get exclusive access to the heap.
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700867 uint64_t start_time = NanoTime();
Elliott Hughes8d768a92011-09-14 16:35:25 -0700868 ThreadList* thread_list = Runtime::Current()->GetThreadList();
869 thread_list->SuspendAll();
Mathieu Chartier662618f2012-06-06 12:01:47 -0700870 timings.AddSplit("SuspendAll");
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700871 GlobalSynchronization::mutator_lock_->AssertExclusiveHeld();
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700872
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700873 size_t bytes_freed = 0;
Elliott Hughesadb460d2011-10-05 17:02:34 -0700874 Object* cleared_references = NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700875 {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700876 MarkSweep mark_sweep(mark_stack_.get());
Carl Shapiro58551df2011-07-24 03:09:51 -0700877
878 mark_sweep.Init();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700879 timings.AddSplit("Init");
Carl Shapiro58551df2011-07-24 03:09:51 -0700880
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700881 // Pre verify the heap
882 if (pre_gc_verify_heap_) {
883 WriterMutexLock mu(*GlobalSynchronization::heap_bitmap_lock_);
884 VerifyHeapReferences(std::string("Pre ") + gc_type_str.str() + "Gc");
885 timings.AddSplit("VerifyHeapReferencesPreGC");
886 }
887
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700888 // Make sure that the tables have the correct pointer for the mark sweep.
889 mod_union_table_->Init(&mark_sweep);
890 zygote_mod_union_table_->Init(&mark_sweep);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700891
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700892 // Swap allocation stack and live stack, enabling us to have new allocations during this GC.
893 MarkStack* temp = allocation_stack_.release();
894 allocation_stack_.reset(live_stack_.release());
895 live_stack_.reset(temp);
896
897 // We will need to know which cards were dirty for doing concurrent processing of dirty cards.
898 // TODO: Investigate using a mark stack instead of a vector.
899 std::vector<byte*> dirty_cards;
900 if (gc_type == GC_STICKY) {
901 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
902 card_table_->GetDirtyCards(*it, dirty_cards);
903 }
904 }
905
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700906 // Clear image space cards and keep track of cards we cleared in the mod-union table.
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700907 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
908 Space* space = *it;
909 if (space->IsImageSpace()) {
910 mod_union_table_->ClearCards(*it);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700911 timings.AddSplit("ClearModUnionCards");
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700912 } else if (space->GetGcRetentionPolicy() == GCRP_FULL_COLLECT) {
913 zygote_mod_union_table_->ClearCards(space);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700914 timings.AddSplit("ClearZygoteCards");
915 } else {
916 card_table_->ClearSpaceCards(space);
917 timings.AddSplit("ClearCards");
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700918 }
919 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700920
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700921 WriterMutexLock mu(*GlobalSynchronization::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700922 if (gc_type == GC_PARTIAL) {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700923 // Copy the mark bits over from the live bits, do this as early as possible or else we can
924 // accidentally un-mark roots.
925 // Needed for scanning dirty objects.
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700926 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700927 if ((*it)->GetGcRetentionPolicy() == GCRP_FULL_COLLECT) {
928 mark_sweep.CopyMarkBits(*it);
929 }
930 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700931 timings.AddSplit("CopyMarkBits");
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700932
933 // We can assume that everything < alloc_space_ start is marked at this point.
934 mark_sweep.SetCondemned(reinterpret_cast<Object*>(alloc_space_->Begin()));
935 } else if (gc_type == GC_STICKY) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700936 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700937 if ((*it)->GetGcRetentionPolicy() != GCRP_NEVER_COLLECT) {
938 mark_sweep.CopyMarkBits(*it);
939 }
940 }
941 timings.AddSplit("CopyMarkBits");
942
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700943 mark_sweep.SetCondemned(reinterpret_cast<Object*>(alloc_space_->Begin()));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700944 }
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700945
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700946 MarkStackAsLive(live_stack_.get());
947
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700948 if (gc_type != GC_STICKY) {
949 live_stack_->Reset();
950 }
951
Carl Shapiro58551df2011-07-24 03:09:51 -0700952 mark_sweep.MarkRoots();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700953 timings.AddSplit("MarkRoots");
Carl Shapiro58551df2011-07-24 03:09:51 -0700954
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700955 // Roots are marked on the bitmap and the mark_stack is empty.
Ian Rogers5d76c432011-10-31 21:42:49 -0700956 DCHECK(mark_sweep.IsMarkStackEmpty());
Carl Shapiro58551df2011-07-24 03:09:51 -0700957
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700958 UpdateAndMarkModUnion(timings, gc_type);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700959
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700960 if (verify_mod_union_table_) {
961 zygote_mod_union_table_->Update();
962 zygote_mod_union_table_->Verify();
963 mod_union_table_->Update();
964 mod_union_table_->Verify();
965 }
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700966
967 // Recursively mark all the non-image bits set in the mark bitmap.
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700968 if (gc_type != GC_STICKY) {
969 live_stack_->Reset();
970 mark_sweep.RecursiveMark(gc_type == GC_PARTIAL, timings);
971 } else {
972 mark_sweep.RecursiveMarkCards(card_table_.get(), dirty_cards, timings);
973 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700974 mark_sweep.DisableFinger();
Carl Shapiro58551df2011-07-24 03:09:51 -0700975
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700976 // Need to process references the swap since it uses IsMarked.
Ian Rogers30fab402012-01-23 15:43:46 -0800977 mark_sweep.ProcessReferences(clear_soft_references);
Elliott Hughes307f75d2011-10-12 18:04:40 -0700978 timings.AddSplit("ProcessReferences");
Carl Shapiro58551df2011-07-24 03:09:51 -0700979
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700980 // This doesn't work with mutators unpaused for some reason, TODO: Fix.
981 mark_sweep.SweepSystemWeaks(false);
982 timings.AddSplit("SweepSystemWeaks");
983
984 // Need to swap for VERIFY_OBJECT_ENABLED since we put things in the live bitmap after they
985 // have been allocated.
986 const bool swap = true;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700987 if (swap) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700988 SwapBitmaps();
Mathieu Chartier654d3a22012-07-11 17:54:18 -0700989 }
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700990
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700991#ifndef NDEBUG
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700992 // Verify that we only reach marked objects from the image space
993 mark_sweep.VerifyImageRoots();
994 timings.AddSplit("VerifyImageRoots");
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700995#endif
Carl Shapiro58551df2011-07-24 03:09:51 -0700996
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700997 if (gc_type != GC_STICKY) {
998 mark_sweep.Sweep(gc_type == GC_PARTIAL, swap);
999 } else {
1000 mark_sweep.SweepArray(timings, live_stack_.get(), swap);
1001 }
Elliott Hughes307f75d2011-10-12 18:04:40 -07001002 timings.AddSplit("Sweep");
Elliott Hughesadb460d2011-10-05 17:02:34 -07001003
1004 cleared_references = mark_sweep.GetClearedReferences();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001005 bytes_freed = mark_sweep.GetFreedBytes();
Carl Shapiro58551df2011-07-24 03:09:51 -07001006 }
1007
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001008 // Post gc verify the heap
1009 if (post_gc_verify_heap_) {
1010 WriterMutexLock mu(*GlobalSynchronization::heap_bitmap_lock_);
1011 VerifyHeapReferences(std::string("Post ") + gc_type_str.str() + "Gc");
1012 timings.AddSplit("VerifyHeapReferencesPostGC");
1013 }
1014
Carl Shapiro58551df2011-07-24 03:09:51 -07001015 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)) {
Mathieu Chartier637e3482012-08-17 10:41:32 -07001028 const size_t percent_free = GetPercentFree();
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001029 const size_t current_heap_size = GetUsedMemorySize();
Mathieu Chartier637e3482012-08-17 10:41:32 -07001030 const size_t total_memory = GetTotalMemory();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001031 LOG(INFO) << gc_type_str.str() << " "
Mathieu Chartier637e3482012-08-17 10:41:32 -07001032 << "GC freed " << PrettySize(bytes_freed) << ", " << percent_free << "% free, "
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001033 << PrettySize(current_heap_size) << "/" << PrettySize(total_memory) << ", "
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001034 << "paused " << PrettyDuration(duration);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001035 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001036
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001037 if (VLOG_IS_ON(heap)) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001038 timings.Dump();
1039 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001040}
Mathieu Chartiera6399032012-06-11 18:49:50 -07001041
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001042void Heap::UpdateAndMarkModUnion(TimingLogger& timings, GcType gc_type) {
1043 if (gc_type == GC_STICKY) {
1044 // Don't need to do anythign for mod union table in this case since we are only scanning dirty
1045 // cards.
1046 return;
1047 }
1048
1049 // Update zygote mod union table.
1050 if (gc_type == GC_PARTIAL) {
1051 zygote_mod_union_table_->Update();
1052 timings.AddSplit("UpdateZygoteModUnionTable");
1053
1054 zygote_mod_union_table_->MarkReferences();
1055 timings.AddSplit("ZygoteMarkReferences");
1056 }
1057
1058 // Processes the cards we cleared earlier and adds their objects into the mod-union table.
1059 mod_union_table_->Update();
1060 timings.AddSplit("UpdateModUnionTable");
1061
1062 // Scans all objects in the mod-union table.
1063 mod_union_table_->MarkReferences();
1064 timings.AddSplit("MarkImageToAllocSpaceReferences");
1065}
1066
1067void Heap::RootMatchesObjectVisitor(const Object* root, void* arg) {
1068 Object* obj = reinterpret_cast<Object*>(arg);
1069 if (root == obj) {
1070 LOG(INFO) << "Object " << obj << " is a root";
1071 }
1072}
1073
1074class ScanVisitor {
1075 public:
1076 void operator ()(const Object* obj) const {
1077 LOG(INFO) << "Would have rescanned object " << obj;
1078 }
1079};
1080
1081class VerifyReferenceVisitor {
1082 public:
1083 VerifyReferenceVisitor(Heap* heap, bool* failed)
1084 SHARED_LOCKS_REQUIRED(GlobalSynchronization::mutator_lock_,
1085 GlobalSynchronization::heap_bitmap_lock_)
1086 : heap_(heap),
1087 failed_(failed) {
1088 }
1089
1090 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for smarter
1091 // analysis.
1092 void operator ()(const Object* obj, const Object* ref, const MemberOffset& /* offset */,
1093 bool /* is_static */) const NO_THREAD_SAFETY_ANALYSIS {
1094 // Verify that the reference is live.
1095 if (ref != NULL && !IsLive(ref)) {
1096 CardTable* card_table = heap_->GetCardTable();
1097 MarkStack* alloc_stack = heap_->allocation_stack_.get();
1098 MarkStack* live_stack = heap_->live_stack_.get();
1099
1100 // Print the cards around our object
1101 byte* card_addr = card_table->CardFromAddr(obj);
1102 LOG(INFO) << "Object " << obj << " references dead object " << ref << " on IsDirty = "
1103 << (*card_addr == GC_CARD_DIRTY);
1104 void* cover_begin = card_table->AddrFromCard(card_addr);
1105 void* cover_end = reinterpret_cast<void*>(reinterpret_cast<size_t>(cover_begin) +
1106 GC_CARD_SIZE);
1107 LOG(INFO) << "Card " << reinterpret_cast<void*>(card_addr) << " covers " << cover_begin
1108 << "-" << cover_end;
1109 SpaceBitmap* bitmap = heap_->GetLiveBitmap()->GetSpaceBitmap(obj);
1110
1111 // Print out how the object is live.
1112 if (bitmap->Test(obj)) {
1113 LOG(INFO) << "Object " << obj << " found in live bitmap";
1114 } else if (std::binary_search(alloc_stack->Begin(), alloc_stack->End(), obj)) {
1115 LOG(INFO) << "Object " << obj << " found in allocation stack";
1116 }
1117
1118 if (std::binary_search(live_stack->Begin(), live_stack->End(), ref)) {
1119 LOG(INFO) << "Reference " << ref << " found in live stack!";
1120 }
1121
1122 // Attempt to see if the card table missed the reference.
1123 ScanVisitor scan_visitor;
1124 byte* byte_cover_begin = reinterpret_cast<byte*>(card_table->AddrFromCard(card_addr));
1125 card_table->Scan(bitmap, byte_cover_begin, byte_cover_begin + GC_CARD_SIZE, scan_visitor,
1126 IdentityFunctor());
1127
1128 // Try and see if a mark sweep collector scans the reference.
1129 MarkStack* mark_stack = heap_->mark_stack_.get();
1130 MarkSweep ms(mark_stack);
1131 ms.Init();
1132 mark_stack->Reset();
1133 ms.SetFinger(reinterpret_cast<Object*>(~size_t(0)));
1134 // All the references should end up in the mark stack.
1135 ms.ScanRoot(obj);
1136 if (std::find(mark_stack->Begin(), mark_stack->End(), ref)) {
1137 LOG(INFO) << "Ref found in the mark_stack when rescanning the object!";
1138 } else {
1139 LOG(INFO) << "Dumping mark stack contents";
1140 for (Object** it = mark_stack->Begin(); it != mark_stack->End(); ++it) {
1141 LOG(INFO) << *it;
1142 }
1143 }
1144 mark_stack->Reset();
1145
1146 // Search to see if any of the roots reference our object.
1147 void* arg = const_cast<void*>(reinterpret_cast<const void*>(obj));
1148 Runtime::Current()->VisitRoots(&Heap::RootMatchesObjectVisitor, arg);
1149 *failed_ = true;
1150 }
1151 }
1152
1153 bool IsLive(const Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
1154 SpaceBitmap* bitmap = heap_->GetLiveBitmap()->GetSpaceBitmap(obj);
1155 if (bitmap != NULL) {
1156 if (bitmap->Test(obj)) {
1157 return true;
1158 }
1159 } else {
1160 heap_->DumpSpaces();
1161 LOG(FATAL) << "Object " << obj << " not found in any spaces";
1162 }
1163 MarkStack* alloc_stack = heap_->allocation_stack_.get();
1164 // At this point we need to search the allocation since things in the live stack may get swept.
1165 if (std::binary_search(alloc_stack->Begin(), alloc_stack->End(), const_cast<Object*>(obj))) {
1166 return true;
1167 }
1168 // Not either in the live bitmap or allocation stack, so the object must be dead.
1169 return false;
1170 }
1171
1172 private:
1173 Heap* heap_;
1174 bool* failed_;
1175};
1176
1177class VerifyObjectVisitor {
1178 public:
1179 VerifyObjectVisitor(Heap* heap)
1180 : heap_(heap),
1181 failed_(false) {
1182
1183 }
1184
1185 void operator ()(const Object* obj) const
1186 SHARED_LOCKS_REQUIRED(GlobalSynchronization::mutator_lock_,
1187 GlobalSynchronization::heap_bitmap_lock_) {
1188 VerifyReferenceVisitor visitor(heap_, const_cast<bool*>(&failed_));
1189 MarkSweep::VisitObjectReferences(obj, visitor);
1190 }
1191
1192 bool Failed() const {
1193 return failed_;
1194 }
1195
1196 private:
1197 Heap* heap_;
1198 bool failed_;
1199};
1200
1201// Must do this with mutators suspended since we are directly accessing the allocation stacks.
1202void Heap::VerifyHeapReferences(const std::string& phase) {
1203 GlobalSynchronization::mutator_lock_->AssertExclusiveHeld();
1204 // Lets sort our allocation stacks so that we can efficiently binary search them.
1205 std::sort(allocation_stack_->Begin(), allocation_stack_->End());
1206 std::sort(live_stack_->Begin(), live_stack_->End());
1207 // Perform the verification.
1208 VerifyObjectVisitor visitor(this);
1209 GetLiveBitmap()->Visit(visitor);
1210 // We don't want to verify the objects in the allocation stack since they themselves may be
1211 // pointing to dead objects if they are not reachable.
1212 if (visitor.Failed()) {
1213 DumpSpaces();
1214 LOG(FATAL) << phase << " heap verification failed";
1215 }
1216}
1217
1218void Heap::SwapBitmaps() {
1219 // Swap the live and mark bitmaps for each alloc space. This is needed since sweep re-swaps
1220 // these bitmaps. Doing this enables us to sweep with the heap unlocked since new allocations
1221 // set the live bit, but since we have the bitmaps reversed at this point, this sets the mark bit
1222 // instead, resulting in no new allocated objects being incorrectly freed by sweep.
1223 WriterMutexLock mu(*GlobalSynchronization::heap_bitmap_lock_);
1224 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1225 Space* space = *it;
1226 // We never allocate into zygote spaces.
1227 if (space->GetGcRetentionPolicy() != GCRP_NEVER_COLLECT) {
1228 live_bitmap_->ReplaceBitmap(space->GetLiveBitmap(), space->GetMarkBitmap());
1229 mark_bitmap_->ReplaceBitmap(space->GetMarkBitmap(), space->GetLiveBitmap());
1230 space->AsAllocSpace()->SwapBitmaps();
1231 }
1232 }
1233}
1234
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001235void Heap::CollectGarbageConcurrentMarkSweepPlan(GcType gc_type, bool clear_soft_references) {
1236 TimingLogger timings("ConcurrentCollectGarbageInternal", true);
1237 uint64_t root_begin = NanoTime(), root_end = 0, dirty_begin = 0, dirty_end = 0;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001238 std::stringstream gc_type_str;
1239 gc_type_str << gc_type << " ";
Mathieu Chartiera6399032012-06-11 18:49:50 -07001240
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001241 // Suspend all threads are get exclusive access to the heap.
1242 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1243 thread_list->SuspendAll();
1244 timings.AddSplit("SuspendAll");
1245 GlobalSynchronization::mutator_lock_->AssertExclusiveHeld();
1246
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001247 size_t bytes_freed = 0;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001248 Object* cleared_references = NULL;
1249 {
1250 MarkSweep mark_sweep(mark_stack_.get());
1251 timings.AddSplit("ctor");
1252
1253 mark_sweep.Init();
1254 timings.AddSplit("Init");
1255
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001256 // Pre verify the heap
1257 if (pre_gc_verify_heap_) {
1258 WriterMutexLock mu(*GlobalSynchronization::heap_bitmap_lock_);
1259 VerifyHeapReferences(std::string("Pre ") + gc_type_str.str() + "Gc");
1260 timings.AddSplit("VerifyHeapReferencesPreGC");
1261 }
1262
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001263 // Swap the stacks, this is safe sunce all the mutators are suspended at this point.
1264 MarkStack* temp = allocation_stack_.release();
1265 allocation_stack_.reset(live_stack_.release());
1266 live_stack_.reset(temp);
1267
1268 // We will need to know which cards were dirty for doing concurrent processing of dirty cards.
1269 // TODO: Investigate using a mark stack instead of a vector.
1270 std::vector<byte*> dirty_cards;
1271 if (gc_type == GC_STICKY) {
1272 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1273 card_table_->GetDirtyCards(*it, dirty_cards);
1274 }
1275 }
1276
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001277 // Make sure that the tables have the correct pointer for the mark sweep.
1278 mod_union_table_->Init(&mark_sweep);
1279 zygote_mod_union_table_->Init(&mark_sweep);
1280
1281 // Clear image space cards and keep track of cards we cleared in the mod-union table.
1282 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1283 Space* space = *it;
1284 if (space->IsImageSpace()) {
1285 mod_union_table_->ClearCards(*it);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001286 timings.AddSplit("ModUnionClearCards");
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001287 } else if (space->GetGcRetentionPolicy() == GCRP_FULL_COLLECT) {
1288 zygote_mod_union_table_->ClearCards(space);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001289 timings.AddSplit("ZygoteModUnionClearCards");
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001290 } else {
1291 card_table_->ClearSpaceCards(space);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001292 timings.AddSplit("ClearCards");
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001293 }
1294 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001295
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001296 {
1297 WriterMutexLock mu(*GlobalSynchronization::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001298
1299 if (gc_type == GC_PARTIAL) {
1300 // Copy the mark bits over from the live bits, do this as early as possible or else we can
1301 // accidentally un-mark roots.
1302 // Needed for scanning dirty objects.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001303 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001304 if ((*it)->GetGcRetentionPolicy() == GCRP_FULL_COLLECT) {
1305 mark_sweep.CopyMarkBits(*it);
1306 }
1307 }
1308 timings.AddSplit("CopyMarkBits");
1309 mark_sweep.SetCondemned(reinterpret_cast<Object*>(alloc_space_->Begin()));
1310 } else if (gc_type == GC_STICKY) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001311 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001312 if ((*it)->GetGcRetentionPolicy() != GCRP_NEVER_COLLECT) {
1313 mark_sweep.CopyMarkBits(*it);
1314 }
1315 }
1316 timings.AddSplit("CopyMarkBits");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001317 mark_sweep.SetCondemned(reinterpret_cast<Object*>(alloc_space_->Begin()));
1318 }
1319
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001320 // Mark everything as live so that sweeping system weak works correctly for sticky mark bit
1321 // GCs.
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001322 MarkStackAsLive(live_stack_.get());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001323 timings.AddSplit("MarkStackAsLive");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001324
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001325 // TODO: Investigate whether or not this is really necessary for sticky mark bits.
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001326 if (gc_type != GC_STICKY) {
1327 live_stack_->Reset();
1328 mark_sweep.MarkRoots();
1329 timings.AddSplit("MarkRoots");
1330 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001331
1332 if (verify_mod_union_table_) {
1333 zygote_mod_union_table_->Update();
1334 zygote_mod_union_table_->Verify();
1335 mod_union_table_->Update();
1336 mod_union_table_->Verify();
1337 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001338 }
1339
1340 // Roots are marked on the bitmap and the mark_stack is empty.
1341 DCHECK(mark_sweep.IsMarkStackEmpty());
1342
1343 // Allow mutators to go again, acquire share on mutator_lock_ to continue.
1344 thread_list->ResumeAll();
1345 {
1346 ReaderMutexLock reader_lock(*GlobalSynchronization::mutator_lock_);
1347 root_end = NanoTime();
1348 timings.AddSplit("RootEnd");
1349
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001350 WriterMutexLock mu(*GlobalSynchronization::heap_bitmap_lock_);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001351 UpdateAndMarkModUnion(timings, gc_type);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001352 if (gc_type != GC_STICKY) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001353 // Recursively mark all the non-image bits set in the mark bitmap.
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001354 mark_sweep.RecursiveMark(gc_type == GC_PARTIAL, timings);
1355 } else {
1356 mark_sweep.RecursiveMarkCards(card_table_.get(), dirty_cards, timings);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001357 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001358 mark_sweep.DisableFinger();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001359 }
1360 // Release share on mutator_lock_ and then get exclusive access.
1361 dirty_begin = NanoTime();
1362 thread_list->SuspendAll();
1363 timings.AddSplit("ReSuspend");
1364 GlobalSynchronization::mutator_lock_->AssertExclusiveHeld();
1365
1366 {
1367 WriterMutexLock mu(*GlobalSynchronization::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001368
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001369 // Re-mark root set.
1370 mark_sweep.ReMarkRoots();
1371 timings.AddSplit("ReMarkRoots");
1372
1373 // Scan dirty objects, this is only required if we are not doing concurrent GC.
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001374 mark_sweep.RecursiveMarkDirtyObjects(false);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001375 timings.AddSplit("RecursiveMarkDirtyObjects");
1376 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001377
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001378 {
1379 ReaderMutexLock mu(*GlobalSynchronization::heap_bitmap_lock_);
1380 mark_sweep.ProcessReferences(clear_soft_references);
1381 timings.AddSplit("ProcessReferences");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001382
1383 // This doesn't work with mutators unpaused for some reason, TODO: Fix.
1384 mark_sweep.SweepSystemWeaks(false);
1385 timings.AddSplit("SweepSystemWeaks");
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001386 }
1387 // Swap the live and mark bitmaps for each alloc space. This is needed since sweep re-swaps
1388 // these bitmaps. Doing this enables us to sweep with the heap unlocked since new allocations
1389 // set the live bit, but since we have the bitmaps reversed at this point, this sets the mark
1390 // bit instead, resulting in no new allocated objects being incorrectly freed by sweep.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001391 const bool swap = true;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001392 if (swap) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001393 SwapBitmaps();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001394 }
1395
1396 if (kIsDebugBuild) {
1397 // Verify that we only reach marked objects from the image space.
1398 ReaderMutexLock mu(*GlobalSynchronization::heap_bitmap_lock_);
1399 mark_sweep.VerifyImageRoots();
1400 timings.AddSplit("VerifyImageRoots");
1401 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001402
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001403 if (gc_type == GC_STICKY) {
1404 // We only sweep over the live stack, and the live stack should not intersect with the
1405 // allocation stack, so it should be safe to UnMark anything in the allocation stack as live.
1406 // This only works for sticky Gcs though!
1407 UnMarkStackAsLive(allocation_stack_.get());
1408 }
1409 timings.AddSplit("UnMarkStacks");
1410
1411 // If we are going to do post Gc verification, lets keep the mutators paused since we don't
1412 // want them to touch dead objects before we find these in verification.
1413 if (post_gc_verify_heap_) {
1414 WriterMutexLock mu(*GlobalSynchronization::heap_bitmap_lock_);
1415 VerifyHeapReferences(std::string("Post ") + gc_type_str.str() + "Gc");
1416 timings.AddSplit("VerifyHeapReferencesPostGC");
1417 }
1418
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001419 thread_list->ResumeAll();
1420 dirty_end = NanoTime();
1421 GlobalSynchronization::mutator_lock_->AssertNotHeld();
1422
1423 {
1424 // TODO: this lock shouldn't be necessary (it's why we did the bitmap flip above).
1425 WriterMutexLock mu(*GlobalSynchronization::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001426 if (gc_type != GC_STICKY) {
1427 mark_sweep.Sweep(gc_type == GC_PARTIAL, swap);
1428 } else {
1429 mark_sweep.SweepArray(timings, live_stack_.get(), swap);
1430 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001431 timings.AddSplit("Sweep");
1432 }
1433
1434 cleared_references = mark_sweep.GetClearedReferences();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001435 bytes_freed = mark_sweep.GetFreedBytes();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001436 }
1437
1438 GrowForUtilization();
1439 timings.AddSplit("GrowForUtilization");
1440
1441 EnqueueClearedReferences(&cleared_references);
1442 RequestHeapTrim();
1443 timings.AddSplit("Finish");
1444
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001445 // If the GC was slow, then print timings in the log.
1446 uint64_t pause_roots = (root_end - root_begin) / 1000 * 1000;
1447 uint64_t pause_dirty = (dirty_end - dirty_begin) / 1000 * 1000;
Mathieu Chartier637e3482012-08-17 10:41:32 -07001448 uint64_t duration = (NanoTime() - root_begin) / 1000 * 1000;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001449 if (pause_roots > MsToNs(5) || pause_dirty > MsToNs(5)) {
Mathieu Chartier637e3482012-08-17 10:41:32 -07001450 const size_t percent_free = GetPercentFree();
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001451 const size_t current_heap_size = GetUsedMemorySize();
Mathieu Chartier637e3482012-08-17 10:41:32 -07001452 const size_t total_memory = GetTotalMemory();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001453 LOG(INFO) << gc_type_str.str()
Mathieu Chartier637e3482012-08-17 10:41:32 -07001454 << "Concurrent GC freed " << PrettySize(bytes_freed) << ", " << percent_free
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001455 << "% free, " << PrettySize(current_heap_size) << "/"
Mathieu Chartier637e3482012-08-17 10:41:32 -07001456 << PrettySize(total_memory) << ", " << "paused " << PrettyDuration(pause_roots)
1457 << "+" << PrettyDuration(pause_dirty) << " total " << PrettyDuration(duration);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001458 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001459
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001460 if (VLOG_IS_ON(heap)) {
1461 timings.Dump();
1462 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001463}
1464
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -07001465bool Heap::WaitForConcurrentGcToComplete() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001466 if (concurrent_gc_) {
1467 bool do_wait = false;
1468 uint64_t wait_start;
1469 {
1470 // Check if GC is running holding gc_complete_lock_.
1471 MutexLock mu(*gc_complete_lock_);
1472 if (is_gc_running_) {
1473 wait_start = NanoTime();
1474 do_wait = true;
1475 }
Mathieu Chartiera6399032012-06-11 18:49:50 -07001476 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001477 if (do_wait) {
1478 // We must wait, change thread state then sleep on gc_complete_cond_;
1479 ScopedThreadStateChange tsc(Thread::Current(), kWaitingForGcToComplete);
1480 {
1481 MutexLock mu(*gc_complete_lock_);
1482 while (is_gc_running_) {
1483 gc_complete_cond_->Wait(*gc_complete_lock_);
1484 }
1485 }
1486 uint64_t wait_time = NanoTime() - wait_start;
1487 if (wait_time > MsToNs(5)) {
1488 LOG(INFO) << "WaitForConcurrentGcToComplete blocked for " << PrettyDuration(wait_time);
1489 }
1490 return true;
1491 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001492 }
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -07001493 return false;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001494}
1495
Elliott Hughesc967f782012-04-16 10:23:15 -07001496void Heap::DumpForSigQuit(std::ostream& os) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001497 os << "Heap: " << GetPercentFree() << "% free, " << PrettySize(num_bytes_allocated_) << "/"
1498 << PrettySize(GetTotalMemory()) << "; " << num_objects_allocated_ << " objects\n";
Elliott Hughesc967f782012-04-16 10:23:15 -07001499}
1500
1501size_t Heap::GetPercentFree() {
1502 size_t total = GetTotalMemory();
1503 return 100 - static_cast<size_t>(100.0f * static_cast<float>(num_bytes_allocated_) / total);
1504}
1505
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001506void Heap::SetIdealFootprint(size_t max_allowed_footprint) {
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001507 AllocSpace* alloc_space = alloc_space_;
1508 // TODO: Behavior for multiple alloc spaces?
1509 size_t alloc_space_capacity = alloc_space->Capacity();
1510 if (max_allowed_footprint > alloc_space_capacity) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001511 VLOG(gc) << "Clamp target GC heap from " << PrettySize(max_allowed_footprint) << " to "
1512 << PrettySize(alloc_space_capacity);
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001513 max_allowed_footprint = alloc_space_capacity;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001514 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001515 alloc_space->SetFootprintLimit(max_allowed_footprint);
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001516}
1517
Ian Rogers3bb17a62012-01-27 23:56:44 -08001518// kHeapIdealFree is the ideal maximum free size, when we grow the heap for utilization.
Shih-wei Liao7f1caab2011-10-06 12:11:04 -07001519static const size_t kHeapIdealFree = 2 * MB;
Ian Rogers3bb17a62012-01-27 23:56:44 -08001520// kHeapMinFree guarantees that you always have at least 512 KB free, when you grow for utilization,
1521// regardless of target utilization ratio.
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001522static const size_t kHeapMinFree = kHeapIdealFree / 4;
1523
Carl Shapiro69759ea2011-07-21 18:13:35 -07001524void Heap::GrowForUtilization() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001525 size_t target_size;
1526 bool use_footprint_limit = false;
1527 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001528 // We know what our utilization is at this moment.
1529 // This doesn't actually resize any memory. It just lets the heap grow more when necessary.
1530 target_size = num_bytes_allocated_ / Heap::GetTargetHeapUtilization();
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001531
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001532 if (target_size > num_bytes_allocated_ + kHeapIdealFree) {
1533 target_size = num_bytes_allocated_ + kHeapIdealFree;
1534 } else if (target_size < num_bytes_allocated_ + kHeapMinFree) {
1535 target_size = num_bytes_allocated_ + kHeapMinFree;
1536 }
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001537
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001538 // Calculate when to perform the next ConcurrentGC.
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001539 if (GetTotalMemory() - GetUsedMemorySize() < concurrent_min_free_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001540 // Not enough free memory to perform concurrent GC.
1541 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
1542 } else {
1543 // Compute below to avoid holding both the statistics and the alloc space lock
1544 use_footprint_limit = true;
1545 }
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001546 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001547
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001548 if (use_footprint_limit) {
1549 size_t foot_print_limit = alloc_space_->GetFootprintLimit();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001550 concurrent_start_bytes_ = foot_print_limit - concurrent_start_size_;
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001551 }
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001552 SetIdealFootprint(target_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001553}
1554
jeffhaoc1160702011-10-27 15:48:45 -07001555void Heap::ClearGrowthLimit() {
jeffhaoc1160702011-10-27 15:48:45 -07001556 WaitForConcurrentGcToComplete();
jeffhaoc1160702011-10-27 15:48:45 -07001557 alloc_space_->ClearGrowthLimit();
1558}
1559
Elliott Hughesadb460d2011-10-05 17:02:34 -07001560void Heap::SetReferenceOffsets(MemberOffset reference_referent_offset,
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001561 MemberOffset reference_queue_offset,
1562 MemberOffset reference_queueNext_offset,
1563 MemberOffset reference_pendingNext_offset,
1564 MemberOffset finalizer_reference_zombie_offset) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001565 reference_referent_offset_ = reference_referent_offset;
1566 reference_queue_offset_ = reference_queue_offset;
1567 reference_queueNext_offset_ = reference_queueNext_offset;
1568 reference_pendingNext_offset_ = reference_pendingNext_offset;
1569 finalizer_reference_zombie_offset_ = finalizer_reference_zombie_offset;
1570 CHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1571 CHECK_NE(reference_queue_offset_.Uint32Value(), 0U);
1572 CHECK_NE(reference_queueNext_offset_.Uint32Value(), 0U);
1573 CHECK_NE(reference_pendingNext_offset_.Uint32Value(), 0U);
1574 CHECK_NE(finalizer_reference_zombie_offset_.Uint32Value(), 0U);
1575}
1576
1577Object* Heap::GetReferenceReferent(Object* reference) {
1578 DCHECK(reference != NULL);
1579 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1580 return reference->GetFieldObject<Object*>(reference_referent_offset_, true);
1581}
1582
1583void Heap::ClearReferenceReferent(Object* reference) {
1584 DCHECK(reference != NULL);
1585 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1586 reference->SetFieldObject(reference_referent_offset_, NULL, true);
1587}
1588
1589// Returns true if the reference object has not yet been enqueued.
1590bool Heap::IsEnqueuable(const Object* ref) {
1591 DCHECK(ref != NULL);
1592 const Object* queue = ref->GetFieldObject<Object*>(reference_queue_offset_, false);
1593 const Object* queue_next = ref->GetFieldObject<Object*>(reference_queueNext_offset_, false);
1594 return (queue != NULL) && (queue_next == NULL);
1595}
1596
1597void Heap::EnqueueReference(Object* ref, Object** cleared_reference_list) {
1598 DCHECK(ref != NULL);
1599 CHECK(ref->GetFieldObject<Object*>(reference_queue_offset_, false) != NULL);
1600 CHECK(ref->GetFieldObject<Object*>(reference_queueNext_offset_, false) == NULL);
1601 EnqueuePendingReference(ref, cleared_reference_list);
1602}
1603
1604void Heap::EnqueuePendingReference(Object* ref, Object** list) {
1605 DCHECK(ref != NULL);
1606 DCHECK(list != NULL);
1607
1608 if (*list == NULL) {
1609 ref->SetFieldObject(reference_pendingNext_offset_, ref, false);
1610 *list = ref;
1611 } else {
1612 Object* head = (*list)->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
1613 ref->SetFieldObject(reference_pendingNext_offset_, head, false);
1614 (*list)->SetFieldObject(reference_pendingNext_offset_, ref, false);
1615 }
1616}
1617
1618Object* Heap::DequeuePendingReference(Object** list) {
1619 DCHECK(list != NULL);
1620 DCHECK(*list != NULL);
1621 Object* head = (*list)->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
1622 Object* ref;
1623 if (*list == head) {
1624 ref = *list;
1625 *list = NULL;
1626 } else {
1627 Object* next = head->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
1628 (*list)->SetFieldObject(reference_pendingNext_offset_, next, false);
1629 ref = head;
1630 }
1631 ref->SetFieldObject(reference_pendingNext_offset_, NULL, false);
1632 return ref;
1633}
1634
Ian Rogers5d4bdc22011-11-02 22:15:43 -07001635void Heap::AddFinalizerReference(Thread* self, Object* object) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001636 ScopedObjectAccess soa(self);
Elliott Hughes77405792012-03-15 15:22:12 -07001637 JValue args[1];
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07001638 args[0].SetL(object);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001639 soa.DecodeMethod(WellKnownClasses::java_lang_ref_FinalizerReference_add)->Invoke(self, NULL, args,
1640 NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001641}
1642
1643size_t Heap::GetBytesAllocated() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001644 return num_bytes_allocated_;
1645}
1646
1647size_t Heap::GetObjectsAllocated() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001648 return num_objects_allocated_;
1649}
1650
1651size_t Heap::GetConcurrentStartSize() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001652 return concurrent_start_size_;
1653}
1654
1655size_t Heap::GetConcurrentMinFree() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001656 return concurrent_min_free_;
Elliott Hughesadb460d2011-10-05 17:02:34 -07001657}
1658
1659void Heap::EnqueueClearedReferences(Object** cleared) {
1660 DCHECK(cleared != NULL);
1661 if (*cleared != NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001662 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes77405792012-03-15 15:22:12 -07001663 JValue args[1];
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07001664 args[0].SetL(*cleared);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001665 soa.DecodeMethod(WellKnownClasses::java_lang_ref_ReferenceQueue_add)->Invoke(soa.Self(), NULL,
1666 args, NULL);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001667 *cleared = NULL;
1668 }
1669}
1670
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001671void Heap::RequestConcurrentGC() {
Mathieu Chartier069387a2012-06-18 12:01:01 -07001672 // Make sure that we can do a concurrent GC.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001673 if (requesting_gc_ || !Runtime::Current()->IsFinishedStarting() ||
1674 Runtime::Current()->IsShuttingDown() || !Runtime::Current()->IsConcurrentGcEnabled()) {
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001675 return;
1676 }
1677
1678 requesting_gc_ = true;
1679 JNIEnv* env = Thread::Current()->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07001680 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
1681 DCHECK(WellKnownClasses::java_lang_Daemons_requestGC != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001682 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
1683 WellKnownClasses::java_lang_Daemons_requestGC);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001684 CHECK(!env->ExceptionCheck());
1685 requesting_gc_ = false;
1686}
1687
1688void Heap::ConcurrentGC() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001689 if (Runtime::Current()->IsShuttingDown() || !concurrent_gc_) {
Mathieu Chartier2542d662012-06-21 17:14:11 -07001690 return;
1691 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001692
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001693 // TODO: We shouldn't need a WaitForConcurrentGcToComplete here since only
1694 // concurrent GC resumes threads before the GC is completed and this function
1695 // is only called within the GC daemon thread.
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001696 if (!WaitForConcurrentGcToComplete()) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001697 // Start a concurrent GC as one wasn't in progress
1698 ScopedThreadStateChange tsc(Thread::Current(), kWaitingPerformingGc);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001699 if (alloc_space_->Size() > kMinAllocSpaceSizeForStickyGC) {
1700 CollectGarbageInternal(GC_STICKY, false);
1701 } else {
1702 CollectGarbageInternal(GC_PARTIAL, false);
1703 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001704 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001705}
1706
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001707void Heap::Trim() {
Mathieu Chartiera6399032012-06-11 18:49:50 -07001708 WaitForConcurrentGcToComplete();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001709 alloc_space_->Trim();
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001710}
1711
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001712void Heap::RequestHeapTrim() {
1713 // We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
1714 // because that only marks object heads, so a large array looks like lots of empty space. We
1715 // don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
1716 // to utilization (which is probably inversely proportional to how much benefit we can expect).
1717 // We could try mincore(2) but that's only a measure of how many pages we haven't given away,
1718 // not how much use we're making of those pages.
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001719 uint64_t ms_time = NsToMs(NanoTime());
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001720 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001721 float utilization = static_cast<float>(num_bytes_allocated_) / alloc_space_->Size();
1722 if ((utilization > 0.75f) || ((ms_time - last_trim_time_) < 2 * 1000)) {
1723 // Don't bother trimming the heap if it's more than 75% utilized, or if a
1724 // heap trim occurred in the last two seconds.
1725 return;
1726 }
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001727 }
Mathieu Chartiera6399032012-06-11 18:49:50 -07001728 if (!Runtime::Current()->IsFinishedStarting() || Runtime::Current()->IsShuttingDown()) {
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001729 // Heap trimming isn't supported without a Java runtime or Daemons (such as at dex2oat time)
Mathieu Chartiera6399032012-06-11 18:49:50 -07001730 // Also: we do not wish to start a heap trim if the runtime is shutting down.
Ian Rogerse1d490c2012-02-03 09:09:07 -08001731 return;
1732 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001733 last_trim_time_ = ms_time;
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001734 JNIEnv* env = Thread::Current()->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07001735 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
1736 DCHECK(WellKnownClasses::java_lang_Daemons_requestHeapTrim != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001737 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
1738 WellKnownClasses::java_lang_Daemons_requestHeapTrim);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001739 CHECK(!env->ExceptionCheck());
1740}
1741
Carl Shapiro69759ea2011-07-21 18:13:35 -07001742} // namespace art