blob: 3989a247e41ed2ac2e398cec416e451a1241d13a [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
Elliott Hughes767a1472011-10-26 18:49:02 -070025#include "debugger.h"
Mathieu Chartier7469ebf2012-09-24 16:28:36 -070026#include "gc/atomic_stack.h"
27#include "gc/card_table.h"
28#include "gc/heap_bitmap.h"
29#include "gc/mark_sweep.h"
30#include "gc/mod_union_table.h"
31#include "gc/space.h"
Brian Carlstrom9cff8e12011-08-18 16:47:29 -070032#include "image.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070033#include "object.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080034#include "object_utils.h"
Brian Carlstrom5643b782012-02-05 12:32:53 -080035#include "os.h"
Mathieu Chartier7664f5c2012-06-08 18:15:32 -070036#include "ScopedLocalRef.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070037#include "scoped_thread_state_change.h"
Ian Rogers1f539342012-10-03 21:09:42 -070038#include "sirt_ref.h"
Carl Shapiro58551df2011-07-24 03:09:51 -070039#include "stl_util.h"
Elliott Hughes8d768a92011-09-14 16:35:25 -070040#include "thread_list.h"
Elliott Hughes767a1472011-10-26 18:49:02 -070041#include "timing_logger.h"
42#include "UniquePtr.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070043#include "well_known_classes.h"
Carl Shapiro69759ea2011-07-21 18:13:35 -070044
45namespace art {
46
Elliott Hughesae80b492012-04-24 10:43:17 -070047static bool GenerateImage(const std::string& image_file_name) {
Brian Carlstroma004aa92012-02-08 18:05:09 -080048 const std::string boot_class_path_string(Runtime::Current()->GetBootClassPathString());
Brian Carlstrom5643b782012-02-05 12:32:53 -080049 std::vector<std::string> boot_class_path;
50 Split(boot_class_path_string, ':', boot_class_path);
Brian Carlstromb2793372012-03-17 18:27:16 -070051 if (boot_class_path.empty()) {
52 LOG(FATAL) << "Failed to generate image because no boot class path specified";
53 }
Brian Carlstrom5643b782012-02-05 12:32:53 -080054
55 std::vector<char*> arg_vector;
56
57 std::string dex2oat_string(GetAndroidRoot());
Elliott Hughes67d92002012-03-26 15:08:51 -070058 dex2oat_string += (kIsDebugBuild ? "/bin/dex2oatd" : "/bin/dex2oat");
Brian Carlstrom5643b782012-02-05 12:32:53 -080059 const char* dex2oat = dex2oat_string.c_str();
60 arg_vector.push_back(strdup(dex2oat));
61
62 std::string image_option_string("--image=");
63 image_option_string += image_file_name;
64 const char* image_option = image_option_string.c_str();
65 arg_vector.push_back(strdup(image_option));
66
67 arg_vector.push_back(strdup("--runtime-arg"));
68 arg_vector.push_back(strdup("-Xms64m"));
69
70 arg_vector.push_back(strdup("--runtime-arg"));
71 arg_vector.push_back(strdup("-Xmx64m"));
72
73 for (size_t i = 0; i < boot_class_path.size(); i++) {
74 std::string dex_file_option_string("--dex-file=");
75 dex_file_option_string += boot_class_path[i];
76 const char* dex_file_option = dex_file_option_string.c_str();
77 arg_vector.push_back(strdup(dex_file_option));
78 }
79
80 std::string oat_file_option_string("--oat-file=");
81 oat_file_option_string += image_file_name;
82 oat_file_option_string.erase(oat_file_option_string.size() - 3);
83 oat_file_option_string += "oat";
84 const char* oat_file_option = oat_file_option_string.c_str();
85 arg_vector.push_back(strdup(oat_file_option));
86
87 arg_vector.push_back(strdup("--base=0x60000000"));
88
Elliott Hughes48436bb2012-02-07 15:23:28 -080089 std::string command_line(Join(arg_vector, ' '));
Brian Carlstrom5643b782012-02-05 12:32:53 -080090 LOG(INFO) << command_line;
91
Elliott Hughes48436bb2012-02-07 15:23:28 -080092 arg_vector.push_back(NULL);
Brian Carlstrom5643b782012-02-05 12:32:53 -080093 char** argv = &arg_vector[0];
94
95 // fork and exec dex2oat
96 pid_t pid = fork();
97 if (pid == 0) {
98 // no allocation allowed between fork and exec
99
100 // change process groups, so we don't get reaped by ProcessManager
101 setpgid(0, 0);
102
103 execv(dex2oat, argv);
104
105 PLOG(FATAL) << "execv(" << dex2oat << ") failed";
106 return false;
107 } else {
108 STLDeleteElements(&arg_vector);
109
110 // wait for dex2oat to finish
111 int status;
112 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
113 if (got_pid != pid) {
114 PLOG(ERROR) << "waitpid failed: wanted " << pid << ", got " << got_pid;
115 return false;
116 }
117 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
118 LOG(ERROR) << dex2oat << " failed: " << command_line;
119 return false;
120 }
121 }
122 return true;
123}
124
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700125void Heap::UnReserveOatFileAddressRange() {
126 oat_file_map_.reset(NULL);
127}
128
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800129Heap::Heap(size_t initial_size, size_t growth_limit, size_t capacity,
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700130 const std::string& original_image_file_name, bool concurrent_gc)
131 : alloc_space_(NULL),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800132 card_table_(NULL),
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700133 concurrent_gc_(concurrent_gc),
134 have_zygote_space_(false),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800135 card_marking_disabled_(false),
136 is_gc_running_(false),
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700137 last_gc_type_(kGcTypeNone),
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700138 growth_limit_(growth_limit),
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700139 concurrent_start_bytes_(std::numeric_limits<size_t>::max()),
Mathieu Chartier7664f5c2012-06-08 18:15:32 -0700140 concurrent_start_size_(128 * KB),
141 concurrent_min_free_(256 * KB),
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700142 concurrent_gc_start_rate_(3 * MB / 2),
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700143 sticky_gc_count_(0),
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700144 large_object_threshold_(3 * kPageSize),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800145 num_bytes_allocated_(0),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700146 verify_missing_card_marks_(false),
147 verify_system_weaks_(false),
148 verify_pre_gc_heap_(false),
149 verify_post_gc_heap_(false),
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700150 verify_mod_union_table_(false),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700151 partial_gc_frequency_(10),
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700152 min_alloc_space_size_for_sticky_gc_(2 * MB),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700153 min_remaining_space_for_sticky_gc_(1 * MB),
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),
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700157 max_allocation_stack_size_(MB),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800158 reference_referent_offset_(0),
159 reference_queue_offset_(0),
160 reference_queueNext_offset_(0),
161 reference_pendingNext_offset_(0),
162 finalizer_reference_zombie_offset_(0),
163 target_utilization_(0.5),
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700164 verify_objects_(false) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800165 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800166 LOG(INFO) << "Heap() entering";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700167 }
168
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700169 live_bitmap_.reset(new HeapBitmap(this));
170 mark_bitmap_.reset(new HeapBitmap(this));
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700171
Ian Rogers30fab402012-01-23 15:43:46 -0800172 // Requested begin for the alloc space, to follow the mapped image and oat files
173 byte* requested_begin = NULL;
Brian Carlstrom5643b782012-02-05 12:32:53 -0800174 std::string image_file_name(original_image_file_name);
175 if (!image_file_name.empty()) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700176 ImageSpace* image_space = NULL;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700177
Brian Carlstrom5643b782012-02-05 12:32:53 -0800178 if (OS::FileExists(image_file_name.c_str())) {
179 // If the /system file exists, it should be up-to-date, don't try to generate
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700180 image_space = ImageSpace::Create(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800181 } else {
182 // If the /system file didn't exist, we need to use one from the art-cache.
183 // If the cache file exists, try to open, but if it fails, regenerate.
184 // If it does not exist, generate.
185 image_file_name = GetArtCacheFilenameOrDie(image_file_name);
186 if (OS::FileExists(image_file_name.c_str())) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700187 image_space = ImageSpace::Create(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800188 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700189 if (image_space == NULL) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700190 CHECK(GenerateImage(image_file_name)) << "Failed to generate image: " << image_file_name;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700191 image_space = ImageSpace::Create(image_file_name);
Brian Carlstrom5643b782012-02-05 12:32:53 -0800192 }
193 }
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700194
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700195 CHECK(image_space != NULL) << "Failed to create space from " << image_file_name;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700196 AddSpace(image_space);
Ian Rogers30fab402012-01-23 15:43:46 -0800197 // Oat files referenced by image files immediately follow them in memory, ensure alloc space
198 // isn't going to get in the middle
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700199 byte* oat_end_addr = image_space->GetImageHeader().GetOatEnd();
200 CHECK_GT(oat_end_addr, image_space->End());
201
202 // Reserve address range from image_space->End() to image_space->GetImageHeader().GetOatEnd()
203 uintptr_t reserve_begin = RoundUp(reinterpret_cast<uintptr_t>(image_space->End()), kPageSize);
204 uintptr_t reserve_end = RoundUp(reinterpret_cast<uintptr_t>(oat_end_addr), kPageSize);
205 oat_file_map_.reset(MemMap::MapAnonymous("oat file reserve",
206 reinterpret_cast<byte*>(reserve_begin),
207 reserve_end - reserve_begin, PROT_READ));
208
Ian Rogers30fab402012-01-23 15:43:46 -0800209 if (oat_end_addr > requested_begin) {
210 requested_begin = reinterpret_cast<byte*>(RoundUp(reinterpret_cast<uintptr_t>(oat_end_addr),
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700211 kPageSize));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700212 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700213 }
214
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700215 // Allocate the large object space.
216 large_object_space_.reset(FreeListSpace::Create("large object space", NULL, capacity));
Mathieu Chartier8e9a1492012-10-04 12:25:40 -0700217 live_bitmap_->SetLargeObjects(large_object_space_->GetLiveObjects());
218 mark_bitmap_->SetLargeObjects(large_object_space_->GetMarkObjects());
219
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700220 UniquePtr<AllocSpace> alloc_space(AllocSpace::Create("alloc space", initial_size, growth_limit,
221 capacity, requested_begin));
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700222 alloc_space_ = alloc_space.release();
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700223 CHECK(alloc_space_ != NULL) << "Failed to create alloc space";
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700224 AddSpace(alloc_space_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700225
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700226 // Spaces are sorted in order of Begin().
227 byte* heap_begin = spaces_.front()->Begin();
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700228 size_t heap_capacity = spaces_.back()->End() - spaces_.front()->Begin();
229 if (spaces_.back()->IsAllocSpace()) {
230 heap_capacity += spaces_.back()->AsAllocSpace()->NonGrowthLimitCapacity();
231 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700232
Ian Rogers30fab402012-01-23 15:43:46 -0800233 // Mark image objects in the live bitmap
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700234 // TODO: C++0x
235 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
236 Space* space = *it;
Ian Rogers30fab402012-01-23 15:43:46 -0800237 if (space->IsImageSpace()) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700238 ImageSpace* image_space = space->AsImageSpace();
239 image_space->RecordImageAllocations(image_space->GetLiveBitmap());
Ian Rogers30fab402012-01-23 15:43:46 -0800240 }
241 }
242
Elliott Hughes6c9c06d2011-11-07 16:43:47 -0800243 // Allocate the card table.
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700244 card_table_.reset(CardTable::Create(heap_begin, heap_capacity));
245 CHECK(card_table_.get() != NULL) << "Failed to create card table";
Ian Rogers5d76c432011-10-31 21:42:49 -0700246
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700247 mod_union_table_.reset(new ModUnionTableToZygoteAllocspace<ModUnionTableReferenceCache>(this));
248 CHECK(mod_union_table_.get() != NULL) << "Failed to create mod-union table";
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700249
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700250 zygote_mod_union_table_.reset(new ModUnionTableCardCache(this));
251 CHECK(zygote_mod_union_table_.get() != NULL) << "Failed to create Zygote mod-union table";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700252
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700253 // TODO: Count objects in the image space here.
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700254 num_bytes_allocated_ = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700255
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700256 // Max stack size in bytes.
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700257 static const size_t default_mark_stack_size = 64 * KB;
258 mark_stack_.reset(ObjectStack::Create("dalvik-mark-stack", default_mark_stack_size));
259 allocation_stack_.reset(ObjectStack::Create("dalvik-allocation-stack",
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700260 max_allocation_stack_size_));
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700261 live_stack_.reset(ObjectStack::Create("dalvik-live-stack",
262 max_allocation_stack_size_));
Mathieu Chartier5301cd22012-05-31 12:11:36 -0700263
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800264 // It's still too early to take a lock because there are no threads yet,
Elliott Hughes92b3b562011-09-08 16:32:26 -0700265 // but we can create the heap lock now. We don't create it earlier to
266 // make it clear that you can't use locks during heap initialization.
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700267 gc_complete_lock_ = new Mutex("GC complete lock");
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700268 gc_complete_cond_.reset(new ConditionVariable("GC complete condition variable"));
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700269
Mathieu Chartier0325e622012-09-05 14:22:51 -0700270 // Set up the cumulative timing loggers.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700271 for (size_t i = static_cast<size_t>(kGcTypeSticky); i < static_cast<size_t>(kGcTypeMax);
272 ++i) {
Mathieu Chartier0325e622012-09-05 14:22:51 -0700273 std::ostringstream name;
274 name << static_cast<GcType>(i);
275 cumulative_timings_.Put(static_cast<GcType>(i),
276 new CumulativeLogger(name.str().c_str(), true));
277 }
278
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800279 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800280 LOG(INFO) << "Heap() exiting";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700281 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700282}
283
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700284// Sort spaces based on begin address
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700285struct SpaceSorter {
286 bool operator ()(const ContinuousSpace* a, const ContinuousSpace* b) const {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700287 return a->Begin() < b->Begin();
288 }
289};
290
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700291void Heap::AddSpace(ContinuousSpace* space) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700292 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700293 DCHECK(space != NULL);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700294 DCHECK(space->GetLiveBitmap() != NULL);
295 live_bitmap_->AddSpaceBitmap(space->GetLiveBitmap());
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700296 DCHECK(space->GetMarkBitmap() != NULL);
297 mark_bitmap_->AddSpaceBitmap(space->GetMarkBitmap());
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800298 spaces_.push_back(space);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700299 if (space->IsAllocSpace()) {
300 alloc_space_ = space->AsAllocSpace();
301 }
302
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700303 // Ensure that spaces remain sorted in increasing order of start address (required for CMS finger)
304 std::sort(spaces_.begin(), spaces_.end(), SpaceSorter());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700305
306 // Ensure that ImageSpaces < ZygoteSpaces < AllocSpaces so that we can do address based checks to
307 // avoid redundant marking.
308 bool seen_zygote = false, seen_alloc = false;
309 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
310 Space* space = *it;
311 if (space->IsImageSpace()) {
312 DCHECK(!seen_zygote);
313 DCHECK(!seen_alloc);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700314 } else if (space->IsZygoteSpace()) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700315 DCHECK(!seen_alloc);
316 seen_zygote = true;
317 } else if (space->IsAllocSpace()) {
318 seen_alloc = true;
319 }
320 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800321}
322
323Heap::~Heap() {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700324 // If we don't reset then the mark stack complains in it's destructor.
325 allocation_stack_->Reset();
326 live_stack_->Reset();
327
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800328 VLOG(heap) << "~Heap()";
Elliott Hughesb3e66df2012-01-12 14:49:18 -0800329 // We can't take the heap lock here because there might be a daemon thread suspended with the
330 // heap lock held. We know though that no non-daemon threads are executing, and we know that
331 // all daemon threads are suspended, and we also know that the threads list have been deleted, so
332 // 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 -0700333 STLDeleteElements(&spaces_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700334 delete gc_complete_lock_;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700335 STLDeleteValues(&cumulative_timings_);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700336}
337
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700338ContinuousSpace* Heap::FindSpaceFromObject(const Object* obj) const {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700339 // TODO: C++0x auto
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700340 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
341 if ((*it)->Contains(obj)) {
342 return *it;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700343 }
344 }
345 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
346 return NULL;
347}
348
349ImageSpace* Heap::GetImageSpace() {
350 // TODO: C++0x auto
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700351 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
352 if ((*it)->IsImageSpace()) {
353 return (*it)->AsImageSpace();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700354 }
355 }
356 return NULL;
357}
358
359AllocSpace* Heap::GetAllocSpace() {
360 return alloc_space_;
361}
362
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700363static void MSpaceChunkCallback(void* start, void* end, size_t used_bytes, void* arg) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700364 size_t chunk_size = reinterpret_cast<uint8_t*>(end) - reinterpret_cast<uint8_t*>(start);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700365 if (used_bytes < chunk_size) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700366 size_t chunk_free_bytes = chunk_size - used_bytes;
367 size_t& max_contiguous_allocation = *reinterpret_cast<size_t*>(arg);
368 max_contiguous_allocation = std::max(max_contiguous_allocation, chunk_free_bytes);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700369 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700370}
371
Ian Rogers50b35e22012-10-04 10:09:15 -0700372Object* Heap::AllocObject(Thread* self, Class* c, size_t byte_count) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700373 DCHECK(c == NULL || (c->IsClassClass() && byte_count >= sizeof(Class)) ||
374 (c->IsVariableSize() || c->GetObjectSize() == byte_count) ||
375 strlen(ClassHelper(c).GetDescriptor()) == 0);
376 DCHECK_GE(byte_count, sizeof(Object));
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700377
378 Object* obj = NULL;
379 size_t size = 0;
380
381 // We need to have a zygote space or else our newly allocated large object can end up in the
382 // Zygote resulting in it being prematurely freed.
383 // We can only do this for primive objects since large objects will not be within the card table
384 // range. This also means that we rely on SetClass not dirtying the object's card.
385 if (byte_count >= large_object_threshold_ && have_zygote_space_ && c->IsPrimitiveArray()) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700386 size = RoundUp(byte_count, kPageSize);
Ian Rogers50b35e22012-10-04 10:09:15 -0700387 obj = Allocate(self, NULL, size);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700388
389 if (obj != NULL) {
390 // Make sure that our large object didn't get placed anywhere within the space interval or else
391 // it breaks the immune range.
392 DCHECK(reinterpret_cast<byte*>(obj) < spaces_.front()->Begin() ||
393 reinterpret_cast<byte*>(obj) >= spaces_.back()->End());
394 }
395 } else {
Ian Rogers50b35e22012-10-04 10:09:15 -0700396 obj = Allocate(self, alloc_space_, byte_count);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700397 size = alloc_space_->AllocationSize(obj);
398
399 if (obj != NULL) {
400 // Additional verification to ensure that we did not allocate into a zygote space.
401 DCHECK(!have_zygote_space_ || !FindSpaceFromObject(obj)->IsZygoteSpace());
402 }
403 }
404
Mathieu Chartier037813d2012-08-23 16:44:59 -0700405 if (LIKELY(obj != NULL)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700406 obj->SetClass(c);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700407
408 // Record allocation after since we want to use the atomic add for the atomic fence to guard
409 // the SetClass since we do not want the class to appear NULL in another thread.
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700410 RecordAllocation(size, obj);
Mathieu Chartier037813d2012-08-23 16:44:59 -0700411
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700412 if (Dbg::IsAllocTrackingEnabled()) {
413 Dbg::RecordAllocation(c, byte_count);
Elliott Hughes418dfe72011-10-06 18:56:27 -0700414 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700415 if (static_cast<size_t>(num_bytes_allocated_) >= concurrent_start_bytes_) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700416 // We already have a request pending, no reason to start more until we update
417 // concurrent_start_bytes_.
418 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700419 // The SirtRef is necessary since the calls in RequestConcurrentGC are a safepoint.
Ian Rogers1f539342012-10-03 21:09:42 -0700420 SirtRef<Object> ref(self, obj);
421 RequestConcurrentGC(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700422 }
423 VerifyObject(obj);
424
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700425 return obj;
426 }
Mathieu Chartier037813d2012-08-23 16:44:59 -0700427 int64_t total_bytes_free = GetFreeMemory();
428 size_t max_contiguous_allocation = 0;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700429 // TODO: C++0x auto
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700430 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
431 if ((*it)->IsAllocSpace()) {
432 (*it)->AsAllocSpace()->Walk(MSpaceChunkCallback, &max_contiguous_allocation);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700433 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700434 }
Elliott Hughes418dfe72011-10-06 18:56:27 -0700435
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700436 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 -0700437 byte_count, PrettyDescriptor(c).c_str(), total_bytes_free, max_contiguous_allocation));
Ian Rogers50b35e22012-10-04 10:09:15 -0700438 self->ThrowOutOfMemoryError(msg.c_str());
Elliott Hughes418dfe72011-10-06 18:56:27 -0700439 return NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700440}
441
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700442bool Heap::IsHeapAddress(const Object* obj) {
Elliott Hughes92b3b562011-09-08 16:32:26 -0700443 // Note: we deliberately don't take the lock here, and mustn't test anything that would
444 // require taking the lock.
Elliott Hughes88c5c352012-03-15 18:49:48 -0700445 if (obj == NULL) {
446 return true;
447 }
448 if (!IsAligned<kObjectAlignment>(obj)) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700449 return false;
450 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800451 for (size_t i = 0; i < spaces_.size(); ++i) {
Ian Rogers30fab402012-01-23 15:43:46 -0800452 if (spaces_[i]->Contains(obj)) {
453 return true;
454 }
455 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700456 // TODO: Find a way to check large object space without using a lock.
457 return true;
Elliott Hughesa2501992011-08-26 19:39:54 -0700458}
459
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700460bool Heap::IsLiveObjectLocked(const Object* obj) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700461 Locks::heap_bitmap_lock_->AssertReaderHeld(Thread::Current());
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700462 return IsHeapAddress(obj) && GetLiveBitmap()->Test(obj);
Elliott Hughes6a5bd492011-10-28 14:33:57 -0700463}
464
Elliott Hughes3e465b12011-09-02 18:26:12 -0700465#if VERIFY_OBJECT_ENABLED
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700466void Heap::VerifyObject(const Object* obj) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700467 if (obj == NULL || this == NULL || !verify_objects_ || Runtime::Current()->IsShuttingDown() ||
Ian Rogers141d6222012-04-05 12:23:06 -0700468 Thread::Current() == NULL ||
jeffhao25045522012-03-13 19:34:37 -0700469 Runtime::Current()->GetThreadList()->GetLockOwner() == Thread::Current()->GetTid()) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700470 return;
471 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700472 VerifyObjectBody(obj);
Elliott Hughes92b3b562011-09-08 16:32:26 -0700473}
474#endif
475
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700476void Heap::DumpSpaces() {
477 // TODO: C++0x auto
478 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700479 ContinuousSpace* space = *it;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700480 SpaceBitmap* live_bitmap = space->GetLiveBitmap();
481 SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
482 LOG(INFO) << space << " " << *space << "\n"
483 << live_bitmap << " " << *live_bitmap << "\n"
484 << mark_bitmap << " " << *mark_bitmap;
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700485 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700486 // TODO: Dump large object space?
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700487}
488
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700489void Heap::VerifyObjectBody(const Object* obj) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700490 if (!IsAligned<kObjectAlignment>(obj)) {
491 LOG(FATAL) << "Object isn't aligned: " << obj;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700492 }
493
Ian Rogersf0bbeab2012-10-10 18:26:27 -0700494 // TODO: the bitmap tests below are racy if VerifyObjectBody is called without the
495 // heap_bitmap_lock_.
Mathieu Chartier0325e622012-09-05 14:22:51 -0700496 if (!GetLiveBitmap()->Test(obj)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700497 // Check the allocation stack / live stack.
498 if (!std::binary_search(live_stack_->Begin(), live_stack_->End(), obj) &&
499 std::find(allocation_stack_->Begin(), allocation_stack_->End(), obj) ==
500 allocation_stack_->End()) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700501 if (large_object_space_->GetLiveObjects()->Test(obj)) {
502 DumpSpaces();
503 LOG(FATAL) << "Object is dead: " << obj;
504 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700505 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700506 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700507
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700508 // Ignore early dawn of the universe verifications
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700509 if (!VERIFY_OBJECT_FAST && GetObjectsAllocated() > 10) {
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700510 const byte* raw_addr = reinterpret_cast<const byte*>(obj) +
511 Object::ClassOffset().Int32Value();
512 const Class* c = *reinterpret_cast<Class* const *>(raw_addr);
513 if (c == NULL) {
514 LOG(FATAL) << "Null class in object: " << obj;
515 } else if (!IsAligned<kObjectAlignment>(c)) {
516 LOG(FATAL) << "Class isn't aligned: " << c << " in object: " << obj;
517 } else if (!GetLiveBitmap()->Test(c)) {
518 LOG(FATAL) << "Class of object is dead: " << c << " in object: " << obj;
519 }
520 // Check obj.getClass().getClass() == obj.getClass().getClass().getClass()
521 // Note: we don't use the accessors here as they have internal sanity checks
522 // that we don't want to run
523 raw_addr = reinterpret_cast<const byte*>(c) + Object::ClassOffset().Int32Value();
524 const Class* c_c = *reinterpret_cast<Class* const *>(raw_addr);
525 raw_addr = reinterpret_cast<const byte*>(c_c) + Object::ClassOffset().Int32Value();
526 const Class* c_c_c = *reinterpret_cast<Class* const *>(raw_addr);
527 CHECK_EQ(c_c, c_c_c);
528 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700529}
530
Brian Carlstrom78128a62011-09-15 17:21:19 -0700531void Heap::VerificationCallback(Object* obj, void* arg) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700532 DCHECK(obj != NULL);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700533 reinterpret_cast<Heap*>(arg)->VerifyObjectBody(obj);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700534}
535
536void Heap::VerifyHeap() {
Ian Rogers50b35e22012-10-04 10:09:15 -0700537 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700538 GetLiveBitmap()->Walk(Heap::VerificationCallback, this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700539}
540
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700541void Heap::RecordAllocation(size_t size, Object* obj) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700542 DCHECK(obj != NULL);
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700543 DCHECK_GT(size, 0u);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700544 num_bytes_allocated_ += size;
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700545
546 if (Runtime::Current()->HasStatsEnabled()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700547 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700548 ++thread_stats->allocated_objects;
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700549 thread_stats->allocated_bytes += size;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700550
551 // TODO: Update these atomically.
552 RuntimeStats* global_stats = Runtime::Current()->GetStats();
553 ++global_stats->allocated_objects;
554 global_stats->allocated_bytes += size;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700555 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700556
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700557 // This is safe to do since the GC will never free objects which are neither in the allocation
558 // stack or the live bitmap.
559 while (!allocation_stack_->AtomicPushBack(obj)) {
560 Thread* self = Thread::Current();
561 self->TransitionFromRunnableToSuspended(kWaitingPerformingGc);
562 // If we actually ran a different type of Gc than requested, we can skip the index forwards.
563 CollectGarbageInternal(kGcTypeSticky, kGcCauseForAlloc, false);
564 self->TransitionFromSuspendedToRunnable();
565 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700566}
567
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700568void Heap::RecordFree(size_t freed_objects, size_t freed_bytes) {
Mathieu Chartier637e3482012-08-17 10:41:32 -0700569 COMPILE_ASSERT(sizeof(size_t) == sizeof(int32_t),
570 int32_t_must_be_same_size_as_size_t_for_used_atomic_operations);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700571 DCHECK_LE(freed_bytes, static_cast<size_t>(num_bytes_allocated_));
572 num_bytes_allocated_ -= freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700573
574 if (Runtime::Current()->HasStatsEnabled()) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700575 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700576 thread_stats->freed_objects += freed_objects;
Elliott Hughes307f75d2011-10-12 18:04:40 -0700577 thread_stats->freed_bytes += freed_bytes;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700578
579 // TODO: Do this concurrently.
580 RuntimeStats* global_stats = Runtime::Current()->GetStats();
581 global_stats->freed_objects += freed_objects;
582 global_stats->freed_bytes += freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700583 }
Carl Shapiro58551df2011-07-24 03:09:51 -0700584}
585
Ian Rogers50b35e22012-10-04 10:09:15 -0700586Object* Heap::TryToAllocate(Thread* self, AllocSpace* space, size_t alloc_size, bool grow) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700587 // Should we try to use a CAS here and fix up num_bytes_allocated_ later with AllocationSize?
588 if (num_bytes_allocated_ + alloc_size > growth_limit_) {
589 return NULL;
590 }
591
Mathieu Chartier83cf3282012-09-26 17:54:27 -0700592 if (UNLIKELY(space == NULL)) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700593 return large_object_space_->Alloc(self, alloc_size);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700594 } else if (grow) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700595 return space->AllocWithGrowth(self, alloc_size);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700596 } else {
Ian Rogers50b35e22012-10-04 10:09:15 -0700597 return space->AllocWithoutGrowth(self, alloc_size);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700598 }
599}
600
Ian Rogers50b35e22012-10-04 10:09:15 -0700601Object* Heap::Allocate(Thread* self, AllocSpace* space, size_t alloc_size) {
Ian Rogers0399dde2012-06-06 17:09:28 -0700602 // Since allocation can cause a GC which will need to SuspendAll, make sure all allocations are
603 // done in the runnable state where suspension is expected.
Ian Rogers81d425b2012-09-27 16:03:43 -0700604 DCHECK_EQ(self->GetState(), kRunnable);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700605 self->AssertThreadSuspensionIsAllowable();
Brian Carlstromb82b6872011-10-26 17:18:07 -0700606
Ian Rogers50b35e22012-10-04 10:09:15 -0700607 Object* ptr = TryToAllocate(self, space, alloc_size, false);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700608 if (ptr != NULL) {
609 return ptr;
610 }
611
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700612 // The allocation failed. If the GC is running, block until it completes, and then retry the
613 // allocation.
Ian Rogers81d425b2012-09-27 16:03:43 -0700614 GcType last_gc = WaitForConcurrentGcToComplete(self);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700615 if (last_gc != kGcTypeNone) {
616 // A GC was in progress and we blocked, retry allocation now that memory has been freed.
Ian Rogers50b35e22012-10-04 10:09:15 -0700617 ptr = TryToAllocate(self, space, alloc_size, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700618 if (ptr != NULL) {
619 return ptr;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700620 }
621 }
622
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700623 // Loop through our different Gc types and try to Gc until we get enough free memory.
624 for (size_t i = static_cast<size_t>(last_gc) + 1; i < static_cast<size_t>(kGcTypeMax); ++i) {
625 bool run_gc = false;
626 GcType gc_type = static_cast<GcType>(i);
627 switch (gc_type) {
628 case kGcTypeSticky: {
629 const size_t alloc_space_size = alloc_space_->Size();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700630 run_gc = alloc_space_size > min_alloc_space_size_for_sticky_gc_ &&
631 alloc_space_->Capacity() - alloc_space_size >= min_remaining_space_for_sticky_gc_;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700632 break;
633 }
634 case kGcTypePartial:
635 run_gc = have_zygote_space_;
636 break;
637 case kGcTypeFull:
638 run_gc = true;
639 break;
640 default:
641 break;
642 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700643
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700644 if (run_gc) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700645 self->TransitionFromRunnableToSuspended(kWaitingPerformingGc);
646
647 // If we actually ran a different type of Gc than requested, we can skip the index forwards.
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700648 GcType gc_type_ran = CollectGarbageInternal(gc_type, kGcCauseForAlloc, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700649 DCHECK(static_cast<size_t>(gc_type_ran) >= i);
650 i = static_cast<size_t>(gc_type_ran);
651 self->TransitionFromSuspendedToRunnable();
652
653 // Did we free sufficient memory for the allocation to succeed?
Ian Rogers50b35e22012-10-04 10:09:15 -0700654 ptr = TryToAllocate(self, space, alloc_size, false);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700655 if (ptr != NULL) {
656 return ptr;
657 }
658 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700659 }
660
661 // Allocations have failed after GCs; this is an exceptional state.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700662 // Try harder, growing the heap if necessary.
Ian Rogers50b35e22012-10-04 10:09:15 -0700663 ptr = TryToAllocate(self, space, alloc_size, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700664 if (ptr != NULL) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700665 if (space != NULL) {
666 size_t new_footprint = space->GetFootprintLimit();
667 // OLD-TODO: may want to grow a little bit more so that the amount of
668 // free space is equal to the old free space + the
669 // utilization slop for the new allocation.
670 VLOG(gc) << "Grow alloc space (frag case) to " << PrettySize(new_footprint)
671 << " for a " << PrettySize(alloc_size) << " allocation";
672 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700673 return ptr;
674 }
675
Elliott Hughes81ff3182012-03-23 20:35:56 -0700676 // Most allocations should have succeeded by now, so the heap is really full, really fragmented,
677 // or the requested size is really big. Do another GC, collecting SoftReferences this time. The
678 // VM spec requires that all SoftReferences have been collected and cleared before throwing OOME.
Carl Shapiro69759ea2011-07-21 18:13:35 -0700679
Elliott Hughes418dfe72011-10-06 18:56:27 -0700680 // OLD-TODO: wait for the finalizers from the previous GC to finish
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700681 VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size)
682 << " allocation";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700683
Mathieu Chartierfc8cfac2012-06-19 11:56:36 -0700684 // We don't need a WaitForConcurrentGcToComplete here either.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700685 self->TransitionFromRunnableToSuspended(kWaitingPerformingGc);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700686 CollectGarbageInternal(kGcTypeFull, kGcCauseForAlloc, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700687 self->TransitionFromSuspendedToRunnable();
Ian Rogers50b35e22012-10-04 10:09:15 -0700688 return TryToAllocate(self, space, alloc_size, true);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700689}
690
Elliott Hughesbf86d042011-08-31 17:53:14 -0700691int64_t Heap::GetMaxMemory() {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700692 return growth_limit_;
Elliott Hughesbf86d042011-08-31 17:53:14 -0700693}
694
695int64_t Heap::GetTotalMemory() {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700696 return GetMaxMemory();
Elliott Hughesbf86d042011-08-31 17:53:14 -0700697}
698
699int64_t Heap::GetFreeMemory() {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700700 return GetMaxMemory() - num_bytes_allocated_;
Elliott Hughesbf86d042011-08-31 17:53:14 -0700701}
702
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700703class InstanceCounter {
704 public:
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700705 InstanceCounter(Class* c, bool count_assignable, size_t* const count)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700706 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700707 : class_(c), count_assignable_(count_assignable), count_(count) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700708
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700709 }
710
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700711 void operator()(const Object* o) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
712 const Class* instance_class = o->GetClass();
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700713 if (count_assignable_) {
714 if (instance_class == class_) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700715 ++*count_;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700716 }
717 } else {
718 if (instance_class != NULL && class_->IsAssignableFrom(instance_class)) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700719 ++*count_;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700720 }
721 }
722 }
723
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700724 private:
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700725 Class* class_;
726 bool count_assignable_;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700727 size_t* const count_;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700728};
729
730int64_t Heap::CountInstances(Class* c, bool count_assignable) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700731 size_t count = 0;
732 InstanceCounter counter(c, count_assignable, &count);
Ian Rogers50b35e22012-10-04 10:09:15 -0700733 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700734 GetLiveBitmap()->Visit(counter);
735 return count;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700736}
737
Ian Rogers30fab402012-01-23 15:43:46 -0800738void Heap::CollectGarbage(bool clear_soft_references) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700739 // Even if we waited for a GC we still need to do another GC since weaks allocated during the
740 // last GC will not have necessarily been cleared.
Ian Rogers81d425b2012-09-27 16:03:43 -0700741 Thread* self = Thread::Current();
742 WaitForConcurrentGcToComplete(self);
743 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700744 // CollectGarbageInternal(have_zygote_space_ ? kGcTypePartial : kGcTypeFull, clear_soft_references);
745 CollectGarbageInternal(kGcTypeFull, kGcCauseExplicit, clear_soft_references);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700746}
747
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700748void Heap::PreZygoteFork() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700749 static Mutex zygote_creation_lock_("zygote creation lock", kZygoteCreationLock);
Ian Rogers81d425b2012-09-27 16:03:43 -0700750 Thread* self = Thread::Current();
751 MutexLock mu(self, zygote_creation_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700752
753 // Try to see if we have any Zygote spaces.
754 if (have_zygote_space_) {
755 return;
756 }
757
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700758 VLOG(heap) << "Starting PreZygoteFork with alloc space size " << PrettySize(alloc_space_->Size());
759
760 {
761 // Flush the alloc stack.
Ian Rogers81d425b2012-09-27 16:03:43 -0700762 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700763 FlushAllocStack();
764 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700765
766 // Replace the first alloc space we find with a zygote space.
767 // TODO: C++0x auto
768 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
769 if ((*it)->IsAllocSpace()) {
770 AllocSpace* zygote_space = (*it)->AsAllocSpace();
771
772 // Turns the current alloc space into a Zygote space and obtain the new alloc space composed
773 // of the remaining available heap memory.
774 alloc_space_ = zygote_space->CreateZygoteSpace();
775
776 // Change the GC retention policy of the zygote space to only collect when full.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700777 zygote_space->SetGcRetentionPolicy(kGcRetentionPolicyFullCollect);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700778 AddSpace(alloc_space_);
779 have_zygote_space_ = true;
780 break;
781 }
782 }
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700783
Ian Rogers5f5a2c02012-09-17 10:52:08 -0700784 // Reset the cumulative loggers since we now have a few additional timing phases.
Mathieu Chartier0325e622012-09-05 14:22:51 -0700785 // TODO: C++0x
786 for (CumulativeTimings::iterator it = cumulative_timings_.begin();
787 it != cumulative_timings_.end(); ++it) {
788 it->second->Reset();
789 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700790}
791
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700792void Heap::FlushAllocStack() {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700793 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
794 allocation_stack_.get());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700795 allocation_stack_->Reset();
796}
797
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700798size_t Heap::GetUsedMemorySize() const {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700799 return num_bytes_allocated_;
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700800}
801
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700802void Heap::MarkAllocStack(SpaceBitmap* bitmap, SpaceSetMap* large_objects, ObjectStack* stack) {
803 Object** limit = stack->End();
804 for (Object** it = stack->Begin(); it != limit; ++it) {
805 const Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700806 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700807 if (LIKELY(bitmap->HasAddress(obj))) {
808 bitmap->Set(obj);
809 } else {
810 large_objects->Set(obj);
811 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700812 }
813}
814
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700815void Heap::UnMarkAllocStack(SpaceBitmap* bitmap, SpaceSetMap* large_objects, ObjectStack* stack) {
816 Object** limit = stack->End();
817 for (Object** it = stack->Begin(); it != limit; ++it) {
818 const Object* obj = *it;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700819 DCHECK(obj != NULL);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700820 if (LIKELY(bitmap->HasAddress(obj))) {
821 bitmap->Clear(obj);
822 } else {
823 large_objects->Clear(obj);
824 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700825 }
826}
827
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700828GcType Heap::CollectGarbageInternal(GcType gc_type, GcCause gc_cause, bool clear_soft_references) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700829 Thread* self = Thread::Current();
830 Locks::mutator_lock_->AssertNotHeld(self);
831 DCHECK_EQ(self->GetState(), kWaitingPerformingGc);
Carl Shapiro58551df2011-07-24 03:09:51 -0700832
Ian Rogers120f1c72012-09-28 17:17:10 -0700833 if (self->IsHandlingStackOverflow()) {
834 LOG(WARNING) << "Performing GC on a thread that is handling a stack overflow.";
835 }
836
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700837 // Ensure there is only one GC at a time.
838 bool start_collect = false;
839 while (!start_collect) {
840 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700841 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700842 if (!is_gc_running_) {
843 is_gc_running_ = true;
844 start_collect = true;
845 }
846 }
847 if (!start_collect) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700848 WaitForConcurrentGcToComplete(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700849 // TODO: if another thread beat this one to do the GC, perhaps we should just return here?
850 // Not doing at the moment to ensure soft references are cleared.
851 }
852 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700853 gc_complete_lock_->AssertNotHeld(self);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700854
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700855 if (gc_cause == kGcCauseForAlloc && Runtime::Current()->HasStatsEnabled()) {
856 ++Runtime::Current()->GetStats()->gc_for_alloc_count;
857 ++Thread::Current()->GetStats()->gc_for_alloc_count;
858 }
859
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700860 // We need to do partial GCs every now and then to avoid the heap growing too much and
861 // fragmenting.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700862 if (gc_type == kGcTypeSticky && ++sticky_gc_count_ > partial_gc_frequency_) {
Mathieu Chartier0325e622012-09-05 14:22:51 -0700863 gc_type = kGcTypePartial;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700864 }
Mathieu Chartier0325e622012-09-05 14:22:51 -0700865 if (gc_type != kGcTypeSticky) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700866 sticky_gc_count_ = 0;
867 }
868
Mathieu Chartier637e3482012-08-17 10:41:32 -0700869 if (concurrent_gc_) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700870 CollectGarbageConcurrentMarkSweepPlan(self, gc_type, gc_cause, clear_soft_references);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700871 } else {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700872 CollectGarbageMarkSweepPlan(self, gc_type, gc_cause, clear_soft_references);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700873 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700874 bytes_since_last_gc_ = 0;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700875
Ian Rogers15bf2d32012-08-28 17:33:04 -0700876 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700877 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers15bf2d32012-08-28 17:33:04 -0700878 is_gc_running_ = false;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700879 last_gc_type_ = gc_type;
Ian Rogers15bf2d32012-08-28 17:33:04 -0700880 // Wake anyone who may have been waiting for the GC to complete.
881 gc_complete_cond_->Broadcast();
882 }
883 // Inform DDMS that a GC completed.
884 Dbg::GcDidFinish();
Mathieu Chartier866fb2a2012-09-10 10:47:49 -0700885 return gc_type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700886}
Mathieu Chartiera6399032012-06-11 18:49:50 -0700887
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700888void Heap::CollectGarbageMarkSweepPlan(Thread* self, GcType gc_type, GcCause gc_cause,
889 bool clear_soft_references) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700890 TimingLogger timings("CollectGarbageInternal", true);
Mathieu Chartier662618f2012-06-06 12:01:47 -0700891
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700892 std::stringstream gc_type_str;
893 gc_type_str << gc_type << " ";
894
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700895 // Suspend all threads are get exclusive access to the heap.
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700896 uint64_t start_time = NanoTime();
Elliott Hughes8d768a92011-09-14 16:35:25 -0700897 ThreadList* thread_list = Runtime::Current()->GetThreadList();
898 thread_list->SuspendAll();
Mathieu Chartier662618f2012-06-06 12:01:47 -0700899 timings.AddSplit("SuspendAll");
Ian Rogers81d425b2012-09-27 16:03:43 -0700900 Locks::mutator_lock_->AssertExclusiveHeld(self);
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700901
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700902 size_t bytes_freed = 0;
Elliott Hughesadb460d2011-10-05 17:02:34 -0700903 Object* cleared_references = NULL;
Carl Shapiro58551df2011-07-24 03:09:51 -0700904 {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700905 MarkSweep mark_sweep(mark_stack_.get());
Carl Shapiro58551df2011-07-24 03:09:51 -0700906 mark_sweep.Init();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700907 timings.AddSplit("Init");
Carl Shapiro58551df2011-07-24 03:09:51 -0700908
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700909 if (verify_pre_gc_heap_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700910 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700911 if (!VerifyHeapReferences()) {
912 LOG(FATAL) << "Pre " << gc_type_str.str() << "Gc verification failed";
913 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700914 timings.AddSplit("VerifyHeapReferencesPreGC");
915 }
916
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700917 // Swap allocation stack and live stack, enabling us to have new allocations during this GC.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700918 SwapStacks();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700919
920 // We will need to know which cards were dirty for doing concurrent processing of dirty cards.
921 // TODO: Investigate using a mark stack instead of a vector.
922 std::vector<byte*> dirty_cards;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700923 if (gc_type == kGcTypeSticky) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700924 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
925 card_table_->GetDirtyCards(*it, dirty_cards);
926 }
927 }
928
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700929 // Clear image space cards and keep track of cards we cleared in the mod-union table.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700930 ClearCards(timings);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700931
Ian Rogers120f1c72012-09-28 17:17:10 -0700932 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier0325e622012-09-05 14:22:51 -0700933 if (gc_type == kGcTypePartial) {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700934 // Copy the mark bits over from the live bits, do this as early as possible or else we can
935 // accidentally un-mark roots.
936 // Needed for scanning dirty objects.
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700937 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700938 if ((*it)->GetGcRetentionPolicy() == kGcRetentionPolicyFullCollect) {
939 mark_sweep.BindLiveToMarkBitmap(*it);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700940 }
941 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700942 timings.AddSplit("BindLiveToMarked");
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700943
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700944 // We can assume that everything from the start of the first space to the alloc space is marked.
945 mark_sweep.SetImmuneRange(reinterpret_cast<Object*>(spaces_[0]->Begin()),
946 reinterpret_cast<Object*>(alloc_space_->Begin()));
Mathieu Chartier0325e622012-09-05 14:22:51 -0700947 } else if (gc_type == kGcTypeSticky) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700948 for (Spaces::iterator it = spaces_.begin();it != spaces_.end(); ++it) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700949 if ((*it)->GetGcRetentionPolicy() != kGcRetentionPolicyNeverCollect) {
950 mark_sweep.BindLiveToMarkBitmap(*it);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700951 }
952 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700953 timings.AddSplit("BindLiveToMarkBitmap");
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700954 large_object_space_->CopyLiveToMarked();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700955 timings.AddSplit("CopyLiveToMarked");
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700956 mark_sweep.SetImmuneRange(reinterpret_cast<Object*>(spaces_[0]->Begin()),
957 reinterpret_cast<Object*>(alloc_space_->Begin()));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700958 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700959 mark_sweep.FindDefaultMarkBitmap();
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700960
Carl Shapiro58551df2011-07-24 03:09:51 -0700961 mark_sweep.MarkRoots();
Elliott Hughes307f75d2011-10-12 18:04:40 -0700962 timings.AddSplit("MarkRoots");
Carl Shapiro58551df2011-07-24 03:09:51 -0700963
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700964 // Roots are marked on the bitmap and the mark_stack is empty.
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700965 DCHECK(mark_stack_->IsEmpty());
Carl Shapiro58551df2011-07-24 03:09:51 -0700966
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700967 UpdateAndMarkModUnion(&mark_sweep, timings, gc_type);
968
969 if (gc_type != kGcTypeSticky) {
970 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
971 live_stack_.get());
972 timings.AddSplit("MarkStackAsLive");
973 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700974
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700975 if (verify_mod_union_table_) {
976 zygote_mod_union_table_->Update();
977 zygote_mod_union_table_->Verify();
978 mod_union_table_->Update();
979 mod_union_table_->Verify();
980 }
Mathieu Chartierb43b7d42012-06-19 13:15:09 -0700981
982 // Recursively mark all the non-image bits set in the mark bitmap.
Mathieu Chartier0325e622012-09-05 14:22:51 -0700983 if (gc_type != kGcTypeSticky) {
Mathieu Chartier0325e622012-09-05 14:22:51 -0700984 mark_sweep.RecursiveMark(gc_type == kGcTypePartial, timings);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700985 } else {
986 mark_sweep.RecursiveMarkCards(card_table_.get(), dirty_cards, timings);
987 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700988 mark_sweep.DisableFinger();
Carl Shapiro58551df2011-07-24 03:09:51 -0700989
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700990 // Need to process references before the swap since it uses IsMarked.
Ian Rogers30fab402012-01-23 15:43:46 -0800991 mark_sweep.ProcessReferences(clear_soft_references);
Elliott Hughes307f75d2011-10-12 18:04:40 -0700992 timings.AddSplit("ProcessReferences");
Carl Shapiro58551df2011-07-24 03:09:51 -0700993
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700994#ifndef NDEBUG
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700995 // Verify that we only reach marked objects from the image space
996 mark_sweep.VerifyImageRoots();
997 timings.AddSplit("VerifyImageRoots");
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700998#endif
Carl Shapiro58551df2011-07-24 03:09:51 -0700999
Mathieu Chartier0325e622012-09-05 14:22:51 -07001000 if (gc_type != kGcTypeSticky) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001001 mark_sweep.Sweep(gc_type == kGcTypePartial, false);
1002 timings.AddSplit("Sweep");
1003 mark_sweep.SweepLargeObjects(false);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001004 timings.AddSplit("SweepLargeObjects");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001005 } else {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001006 mark_sweep.SweepArray(timings, live_stack_.get(), false);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001007 timings.AddSplit("SweepArray");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001008 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001009 live_stack_->Reset();
1010
1011 // Unbind the live and mark bitmaps.
1012 mark_sweep.UnBindBitmaps();
1013
1014 const bool swap = true;
1015 if (swap) {
1016 if (gc_type == kGcTypeSticky) {
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001017 SwapLargeObjects();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001018 } else {
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001019 SwapBitmaps(gc_type);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001020 }
1021 }
Elliott Hughesadb460d2011-10-05 17:02:34 -07001022
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001023 if (verify_system_weaks_) {
1024 mark_sweep.VerifySystemWeaks();
1025 timings.AddSplit("VerifySystemWeaks");
1026 }
1027
Elliott Hughesadb460d2011-10-05 17:02:34 -07001028 cleared_references = mark_sweep.GetClearedReferences();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001029 bytes_freed = mark_sweep.GetFreedBytes();
Carl Shapiro58551df2011-07-24 03:09:51 -07001030 }
1031
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001032 if (verify_post_gc_heap_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001033 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001034 if (!VerifyHeapReferences()) {
1035 LOG(FATAL) << "Post " + gc_type_str.str() + "Gc verification failed";
1036 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001037 timings.AddSplit("VerifyHeapReferencesPostGC");
1038 }
1039
Carl Shapiro58551df2011-07-24 03:09:51 -07001040 GrowForUtilization();
Elliott Hughes307f75d2011-10-12 18:04:40 -07001041 timings.AddSplit("GrowForUtilization");
Mathieu Chartierb43b7d42012-06-19 13:15:09 -07001042
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001043 thread_list->ResumeAll();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001044 timings.AddSplit("ResumeAll");
Elliott Hughesadb460d2011-10-05 17:02:34 -07001045
1046 EnqueueClearedReferences(&cleared_references);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001047 RequestHeapTrim();
Mathieu Chartier662618f2012-06-06 12:01:47 -07001048 timings.AddSplit("Finish");
Elliott Hughes83df2ac2011-10-11 16:37:54 -07001049
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001050 // If the GC was slow, then print timings in the log.
1051 uint64_t duration = (NanoTime() - start_time) / 1000 * 1000;
1052 if (duration > MsToNs(50)) {
Mathieu Chartier637e3482012-08-17 10:41:32 -07001053 const size_t percent_free = GetPercentFree();
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001054 const size_t current_heap_size = GetUsedMemorySize();
Mathieu Chartier637e3482012-08-17 10:41:32 -07001055 const size_t total_memory = GetTotalMemory();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001056 LOG(INFO) << gc_cause << " " << gc_type_str.str()
Mathieu Chartier637e3482012-08-17 10:41:32 -07001057 << "GC freed " << PrettySize(bytes_freed) << ", " << percent_free << "% free, "
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001058 << PrettySize(current_heap_size) << "/" << PrettySize(total_memory) << ", "
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001059 << "paused " << PrettyDuration(duration);
Mathieu Chartier0325e622012-09-05 14:22:51 -07001060 if (VLOG_IS_ON(heap)) {
1061 timings.Dump();
1062 }
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001063 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001064
Mathieu Chartier0325e622012-09-05 14:22:51 -07001065 CumulativeLogger* logger = cumulative_timings_.Get(gc_type);
1066 logger->Start();
1067 logger->AddLogger(timings);
1068 logger->End(); // Next iteration.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001069}
Mathieu Chartiera6399032012-06-11 18:49:50 -07001070
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001071void Heap::UpdateAndMarkModUnion(MarkSweep* mark_sweep, TimingLogger& timings, GcType gc_type) {
Mathieu Chartier0325e622012-09-05 14:22:51 -07001072 if (gc_type == kGcTypeSticky) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001073 // Don't need to do anything for mod union table in this case since we are only scanning dirty
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001074 // cards.
1075 return;
1076 }
1077
1078 // Update zygote mod union table.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001079 if (gc_type == kGcTypePartial) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001080 zygote_mod_union_table_->Update();
1081 timings.AddSplit("UpdateZygoteModUnionTable");
1082
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001083 zygote_mod_union_table_->MarkReferences(mark_sweep);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001084 timings.AddSplit("ZygoteMarkReferences");
1085 }
1086
1087 // Processes the cards we cleared earlier and adds their objects into the mod-union table.
1088 mod_union_table_->Update();
1089 timings.AddSplit("UpdateModUnionTable");
1090
1091 // Scans all objects in the mod-union table.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001092 mod_union_table_->MarkReferences(mark_sweep);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001093 timings.AddSplit("MarkImageToAllocSpaceReferences");
1094}
1095
1096void Heap::RootMatchesObjectVisitor(const Object* root, void* arg) {
1097 Object* obj = reinterpret_cast<Object*>(arg);
1098 if (root == obj) {
1099 LOG(INFO) << "Object " << obj << " is a root";
1100 }
1101}
1102
1103class ScanVisitor {
1104 public:
1105 void operator ()(const Object* obj) const {
1106 LOG(INFO) << "Would have rescanned object " << obj;
1107 }
1108};
1109
1110class VerifyReferenceVisitor {
1111 public:
1112 VerifyReferenceVisitor(Heap* heap, bool* failed)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001113 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
1114 Locks::heap_bitmap_lock_)
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001115 : heap_(heap),
1116 failed_(failed) {
1117 }
1118
1119 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for smarter
1120 // analysis.
1121 void operator ()(const Object* obj, const Object* ref, const MemberOffset& /* offset */,
1122 bool /* is_static */) const NO_THREAD_SAFETY_ANALYSIS {
1123 // Verify that the reference is live.
1124 if (ref != NULL && !IsLive(ref)) {
1125 CardTable* card_table = heap_->GetCardTable();
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001126 ObjectStack* alloc_stack = heap_->allocation_stack_.get();
1127 ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001128
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001129 byte* card_addr = card_table->CardFromAddr(obj);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001130 LOG(ERROR) << "Object " << obj << " references dead object " << ref << "\n"
1131 << "IsDirty = " << (*card_addr == CardTable::kCardDirty) << "\n"
1132 << "Obj type " << PrettyTypeOf(obj) << "\n"
1133 << "Ref type " << PrettyTypeOf(ref);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001134 card_table->CheckAddrIsInCardTable(reinterpret_cast<const byte*>(obj));
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001135 void* cover_begin = card_table->AddrFromCard(card_addr);
1136 void* cover_end = reinterpret_cast<void*>(reinterpret_cast<size_t>(cover_begin) +
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001137 CardTable::kCardSize);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001138 LOG(ERROR) << "Card " << reinterpret_cast<void*>(card_addr) << " covers " << cover_begin
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001139 << "-" << cover_end;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001140 SpaceBitmap* bitmap = heap_->GetLiveBitmap()->GetSpaceBitmap(obj);
1141
1142 // Print out how the object is live.
1143 if (bitmap->Test(obj)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001144 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1145 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001146 if (std::binary_search(alloc_stack->Begin(), alloc_stack->End(), obj)) {
1147 LOG(ERROR) << "Object " << obj << " found in allocation stack";
1148 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001149 if (std::binary_search(live_stack->Begin(), live_stack->End(), obj)) {
1150 LOG(ERROR) << "Object " << obj << " found in live stack";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001151 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001152 if (std::binary_search(live_stack->Begin(), live_stack->End(), ref)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001153 LOG(ERROR) << "Reference " << ref << " found in live stack!";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001154 }
1155
1156 // Attempt to see if the card table missed the reference.
1157 ScanVisitor scan_visitor;
1158 byte* byte_cover_begin = reinterpret_cast<byte*>(card_table->AddrFromCard(card_addr));
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001159 card_table->Scan(bitmap, byte_cover_begin, byte_cover_begin + CardTable::kCardSize,
1160 scan_visitor, IdentityFunctor());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001161
1162 // Try and see if a mark sweep collector scans the reference.
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001163 ObjectStack* mark_stack = heap_->mark_stack_.get();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001164 MarkSweep ms(mark_stack);
1165 ms.Init();
1166 mark_stack->Reset();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001167 ms.DisableFinger();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001168
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001169 // All the references should end up in the mark stack.
1170 ms.ScanRoot(obj);
1171 if (std::find(mark_stack->Begin(), mark_stack->End(), ref)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001172 LOG(ERROR) << "Ref found in the mark_stack when rescanning the object!";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001173 } else {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001174 LOG(ERROR) << "Dumping mark stack contents";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001175 for (Object** it = mark_stack->Begin(); it != mark_stack->End(); ++it) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001176 LOG(ERROR) << *it;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001177 }
1178 }
1179 mark_stack->Reset();
1180
1181 // Search to see if any of the roots reference our object.
1182 void* arg = const_cast<void*>(reinterpret_cast<const void*>(obj));
1183 Runtime::Current()->VisitRoots(&Heap::RootMatchesObjectVisitor, arg);
1184 *failed_ = true;
1185 }
1186 }
1187
1188 bool IsLive(const Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
1189 SpaceBitmap* bitmap = heap_->GetLiveBitmap()->GetSpaceBitmap(obj);
1190 if (bitmap != NULL) {
1191 if (bitmap->Test(obj)) {
1192 return true;
1193 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001194 } else if (heap_->GetLargeObjectsSpace()->Contains(obj)) {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001195 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001196 } else {
1197 heap_->DumpSpaces();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001198 LOG(ERROR) << "Object " << obj << " not found in any spaces";
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001199 }
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001200 ObjectStack* alloc_stack = heap_->allocation_stack_.get();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001201 // At this point we need to search the allocation since things in the live stack may get swept.
1202 if (std::binary_search(alloc_stack->Begin(), alloc_stack->End(), const_cast<Object*>(obj))) {
1203 return true;
1204 }
1205 // Not either in the live bitmap or allocation stack, so the object must be dead.
1206 return false;
1207 }
1208
1209 private:
1210 Heap* heap_;
1211 bool* failed_;
1212};
1213
1214class VerifyObjectVisitor {
1215 public:
1216 VerifyObjectVisitor(Heap* heap)
1217 : heap_(heap),
1218 failed_(false) {
1219
1220 }
1221
1222 void operator ()(const Object* obj) const
Ian Rogersb726dcb2012-09-05 08:57:23 -07001223 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001224 VerifyReferenceVisitor visitor(heap_, const_cast<bool*>(&failed_));
1225 MarkSweep::VisitObjectReferences(obj, visitor);
1226 }
1227
1228 bool Failed() const {
1229 return failed_;
1230 }
1231
1232 private:
1233 Heap* heap_;
1234 bool failed_;
1235};
1236
1237// Must do this with mutators suspended since we are directly accessing the allocation stacks.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001238bool Heap::VerifyHeapReferences() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001239 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001240 // Lets sort our allocation stacks so that we can efficiently binary search them.
1241 std::sort(allocation_stack_->Begin(), allocation_stack_->End());
1242 std::sort(live_stack_->Begin(), live_stack_->End());
1243 // Perform the verification.
1244 VerifyObjectVisitor visitor(this);
1245 GetLiveBitmap()->Visit(visitor);
1246 // We don't want to verify the objects in the allocation stack since they themselves may be
1247 // pointing to dead objects if they are not reachable.
1248 if (visitor.Failed()) {
1249 DumpSpaces();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001250 return false;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001251 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001252 return true;
1253}
1254
1255class VerifyReferenceCardVisitor {
1256 public:
1257 VerifyReferenceCardVisitor(Heap* heap, bool* failed)
1258 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
1259 Locks::heap_bitmap_lock_)
1260 : heap_(heap),
1261 failed_(failed) {
1262 }
1263
1264 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for smarter
1265 // analysis.
1266 void operator ()(const Object* obj, const Object* ref, const MemberOffset& offset,
1267 bool is_static) const NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001268 if (ref != NULL && !obj->GetClass()->IsPrimitiveArray()) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001269 CardTable* card_table = heap_->GetCardTable();
1270 // If the object is not dirty and it is referencing something in the live stack other than
1271 // class, then it must be on a dirty card.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001272 if (!card_table->AddrIsInCardTable(obj)) {
1273 LOG(ERROR) << "Object " << obj << " is not in the address range of the card table";
1274 *failed_ = true;
1275 } else if (!card_table->IsDirty(obj)) {
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001276 ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001277 if (std::binary_search(live_stack->Begin(), live_stack->End(), ref) && !ref->IsClass()) {
1278 if (std::binary_search(live_stack->Begin(), live_stack->End(), obj)) {
1279 LOG(ERROR) << "Object " << obj << " found in live stack";
1280 }
1281 if (heap_->GetLiveBitmap()->Test(obj)) {
1282 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1283 }
1284 LOG(ERROR) << "Object " << obj << " " << PrettyTypeOf(obj)
1285 << " references " << ref << " " << PrettyTypeOf(ref) << " in live stack";
1286
1287 // Print which field of the object is dead.
1288 if (!obj->IsObjectArray()) {
1289 const Class* klass = is_static ? obj->AsClass() : obj->GetClass();
1290 CHECK(klass != NULL);
1291 const ObjectArray<Field>* fields = is_static ? klass->GetSFields() : klass->GetIFields();
1292 CHECK(fields != NULL);
1293 for (int32_t i = 0; i < fields->GetLength(); ++i) {
1294 const Field* cur = fields->Get(i);
1295 if (cur->GetOffset().Int32Value() == offset.Int32Value()) {
1296 LOG(ERROR) << (is_static ? "Static " : "") << "field in the live stack is "
1297 << PrettyField(cur);
1298 break;
1299 }
1300 }
1301 } else {
1302 const ObjectArray<Object>* object_array = obj->AsObjectArray<Object>();
1303 for (int32_t i = 0; i < object_array->GetLength(); ++i) {
1304 if (object_array->Get(i) == ref) {
1305 LOG(ERROR) << (is_static ? "Static " : "") << "obj[" << i << "] = ref";
1306 }
1307 }
1308 }
1309
1310 *failed_ = true;
1311 }
1312 }
1313 }
1314 }
1315
1316 private:
1317 Heap* heap_;
1318 bool* failed_;
1319};
1320
1321class VerifyLiveStackReferences {
1322 public:
1323 VerifyLiveStackReferences(Heap* heap)
1324 : heap_(heap),
1325 failed_(false) {
1326
1327 }
1328
1329 void operator ()(const Object* obj) const
1330 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1331 VerifyReferenceCardVisitor visitor(heap_, const_cast<bool*>(&failed_));
1332 MarkSweep::VisitObjectReferences(obj, visitor);
1333 }
1334
1335 bool Failed() const {
1336 return failed_;
1337 }
1338
1339 private:
1340 Heap* heap_;
1341 bool failed_;
1342};
1343
1344bool Heap::VerifyMissingCardMarks() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001345 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001346
1347 VerifyLiveStackReferences visitor(this);
1348 GetLiveBitmap()->Visit(visitor);
1349
1350 // We can verify objects in the live stack since none of these should reference dead objects.
1351 for (Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
1352 visitor(*it);
1353 }
1354
1355 if (visitor.Failed()) {
1356 DumpSpaces();
1357 return false;
1358 }
1359 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001360}
1361
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001362void Heap::SwapBitmaps(GcType gc_type) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001363 // Swap the live and mark bitmaps for each alloc space. This is needed since sweep re-swaps
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001364 // these bitmaps. The bitmap swapping is an optimization so that we do not need to clear the live
1365 // bits of dead objects in the live bitmap.
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001366 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1367 ContinuousSpace* space = *it;
1368 // We never allocate into zygote spaces.
1369 if (space->GetGcRetentionPolicy() == kGcRetentionPolicyAlwaysCollect ||
1370 (gc_type == kGcTypeFull &&
1371 space->GetGcRetentionPolicy() == kGcRetentionPolicyFullCollect)) {
1372 live_bitmap_->ReplaceBitmap(space->GetLiveBitmap(), space->GetMarkBitmap());
1373 mark_bitmap_->ReplaceBitmap(space->GetMarkBitmap(), space->GetLiveBitmap());
1374 space->AsAllocSpace()->SwapBitmaps();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001375 }
1376 }
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001377 SwapLargeObjects();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001378}
1379
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001380void Heap::SwapLargeObjects() {
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001381 large_object_space_->SwapBitmaps();
1382 live_bitmap_->SetLargeObjects(large_object_space_->GetLiveObjects());
1383 mark_bitmap_->SetLargeObjects(large_object_space_->GetMarkObjects());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001384}
1385
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001386void Heap::SwapStacks() {
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001387 ObjectStack* temp = allocation_stack_.release();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001388 allocation_stack_.reset(live_stack_.release());
1389 live_stack_.reset(temp);
1390
1391 // Sort the live stack so that we can quickly binary search it later.
1392 if (VERIFY_OBJECT_ENABLED) {
1393 std::sort(live_stack_->Begin(), live_stack_->End());
1394 }
1395}
1396
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001397void Heap::ClearCards(TimingLogger& timings) {
1398 // Clear image space cards and keep track of cards we cleared in the mod-union table.
1399 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1400 ContinuousSpace* space = *it;
1401 if (space->IsImageSpace()) {
1402 mod_union_table_->ClearCards(*it);
1403 timings.AddSplit("ModUnionClearCards");
1404 } else if (space->GetGcRetentionPolicy() == kGcRetentionPolicyFullCollect) {
1405 zygote_mod_union_table_->ClearCards(space);
1406 timings.AddSplit("ZygoteModUnionClearCards");
1407 } else {
1408 card_table_->ClearSpaceCards(space);
1409 timings.AddSplit("ClearCards");
1410 }
1411 }
1412}
1413
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001414void Heap::CollectGarbageConcurrentMarkSweepPlan(Thread* self, GcType gc_type, GcCause gc_cause,
1415 bool clear_soft_references) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001416 TimingLogger timings("ConcurrentCollectGarbageInternal", true);
1417 uint64_t root_begin = NanoTime(), root_end = 0, dirty_begin = 0, dirty_end = 0;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001418 std::stringstream gc_type_str;
1419 gc_type_str << gc_type << " ";
Mathieu Chartiera6399032012-06-11 18:49:50 -07001420
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001421 // Suspend all threads are get exclusive access to the heap.
1422 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1423 thread_list->SuspendAll();
1424 timings.AddSplit("SuspendAll");
Ian Rogers81d425b2012-09-27 16:03:43 -07001425 Locks::mutator_lock_->AssertExclusiveHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001426
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001427 size_t bytes_freed = 0;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001428 Object* cleared_references = NULL;
1429 {
1430 MarkSweep mark_sweep(mark_stack_.get());
1431 timings.AddSplit("ctor");
1432
1433 mark_sweep.Init();
1434 timings.AddSplit("Init");
1435
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001436 if (verify_pre_gc_heap_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001437 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001438 if (!VerifyHeapReferences()) {
1439 LOG(FATAL) << "Pre " << gc_type_str.str() << "Gc verification failed";
1440 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001441 timings.AddSplit("VerifyHeapReferencesPreGC");
1442 }
1443
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001444 // Swap the stacks, this is safe since all the mutators are suspended at this point.
1445 SwapStacks();
1446
1447 // Check that all objects which reference things in the live stack are on dirty cards.
1448 if (verify_missing_card_marks_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001449 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001450 // Sort the live stack so that we can quickly binary search it later.
1451 std::sort(live_stack_->Begin(), live_stack_->End());
1452 if (!VerifyMissingCardMarks()) {
1453 LOG(FATAL) << "Pre GC verification of missing card marks failed";
1454 }
1455 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001456
1457 // We will need to know which cards were dirty for doing concurrent processing of dirty cards.
1458 // TODO: Investigate using a mark stack instead of a vector.
1459 std::vector<byte*> dirty_cards;
Mathieu Chartier0325e622012-09-05 14:22:51 -07001460 if (gc_type == kGcTypeSticky) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001461 dirty_cards.reserve(4 * KB);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001462 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1463 card_table_->GetDirtyCards(*it, dirty_cards);
1464 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001465 timings.AddSplit("GetDirtyCards");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001466 }
1467
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001468 // Clear image space cards and keep track of cards we cleared in the mod-union table.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001469 ClearCards(timings);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001470
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001471 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001472 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001473
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001474 for (Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001475 DCHECK(!GetLiveBitmap()->Test(*it));
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001476 }
1477
Mathieu Chartier0325e622012-09-05 14:22:51 -07001478 if (gc_type == kGcTypePartial) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001479 // Copy the mark bits over from the live bits, do this as early as possible or else we can
1480 // accidentally un-mark roots.
1481 // Needed for scanning dirty objects.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001482 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001483 if ((*it)->GetGcRetentionPolicy() == kGcRetentionPolicyFullCollect) {
1484 mark_sweep.BindLiveToMarkBitmap(*it);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001485 }
1486 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001487 timings.AddSplit("BindLiveToMark");
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001488 mark_sweep.SetImmuneRange(reinterpret_cast<Object*>(spaces_.front()->Begin()),
1489 reinterpret_cast<Object*>(alloc_space_->Begin()));
Mathieu Chartier0325e622012-09-05 14:22:51 -07001490 } else if (gc_type == kGcTypeSticky) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001491 for (Spaces::iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001492 if ((*it)->GetGcRetentionPolicy() != kGcRetentionPolicyNeverCollect) {
1493 mark_sweep.BindLiveToMarkBitmap(*it);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001494 }
1495 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001496 timings.AddSplit("BindLiveToMark");
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001497 large_object_space_->CopyLiveToMarked();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001498 timings.AddSplit("CopyLiveToMarked");
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001499 mark_sweep.SetImmuneRange(reinterpret_cast<Object*>(spaces_.front()->Begin()),
1500 reinterpret_cast<Object*>(alloc_space_->Begin()));
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001501 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001502 mark_sweep.FindDefaultMarkBitmap();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001503
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001504 // Marking roots is not necessary for sticky mark bits since we only actually require the
1505 // remarking of roots.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001506 if (gc_type != kGcTypeSticky) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001507 mark_sweep.MarkRoots();
1508 timings.AddSplit("MarkRoots");
1509 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001510
1511 if (verify_mod_union_table_) {
1512 zygote_mod_union_table_->Update();
1513 zygote_mod_union_table_->Verify();
1514 mod_union_table_->Update();
1515 mod_union_table_->Verify();
1516 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001517 }
1518
1519 // Roots are marked on the bitmap and the mark_stack is empty.
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001520 DCHECK(mark_stack_->IsEmpty());
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001521
1522 // Allow mutators to go again, acquire share on mutator_lock_ to continue.
1523 thread_list->ResumeAll();
1524 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001525 ReaderMutexLock reader_lock(self, *Locks::mutator_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001526 root_end = NanoTime();
1527 timings.AddSplit("RootEnd");
1528
Ian Rogers81d425b2012-09-27 16:03:43 -07001529 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001530 UpdateAndMarkModUnion(&mark_sweep, timings, gc_type);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001531
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001532 if (gc_type != kGcTypeSticky) {
1533 // Mark everything allocated since the last as GC live so that we can sweep concurrently,
1534 // knowing that new allocations won't be marked as live.
1535 MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
1536 live_stack_.get());
1537 timings.AddSplit("MarkStackAsLive");
1538 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001539
Mathieu Chartier0325e622012-09-05 14:22:51 -07001540 if (gc_type != kGcTypeSticky) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001541 // Recursively mark all the non-image bits set in the mark bitmap.
Mathieu Chartier0325e622012-09-05 14:22:51 -07001542 mark_sweep.RecursiveMark(gc_type == kGcTypePartial, timings);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001543 } else {
1544 mark_sweep.RecursiveMarkCards(card_table_.get(), dirty_cards, timings);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001545 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001546 mark_sweep.DisableFinger();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001547 }
1548 // Release share on mutator_lock_ and then get exclusive access.
1549 dirty_begin = NanoTime();
1550 thread_list->SuspendAll();
1551 timings.AddSplit("ReSuspend");
Ian Rogers81d425b2012-09-27 16:03:43 -07001552 Locks::mutator_lock_->AssertExclusiveHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001553
1554 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001555 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001556
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001557 // Re-mark root set.
1558 mark_sweep.ReMarkRoots();
1559 timings.AddSplit("ReMarkRoots");
1560
1561 // Scan dirty objects, this is only required if we are not doing concurrent GC.
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001562 mark_sweep.RecursiveMarkDirtyObjects(false);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001563 timings.AddSplit("RecursiveMarkDirtyObjects");
1564 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001565
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001566 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001567 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001568
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001569 mark_sweep.ProcessReferences(clear_soft_references);
1570 timings.AddSplit("ProcessReferences");
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001571 }
1572
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001573 // Only need to do this if we have the card mark verification on, and only during concurrent GC.
1574 if (verify_missing_card_marks_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001575 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001576 mark_sweep.SweepArray(timings, allocation_stack_.get(), false);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001577 } else {
Ian Rogers81d425b2012-09-27 16:03:43 -07001578 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001579 // We only sweep over the live stack, and the live stack should not intersect with the
1580 // allocation stack, so it should be safe to UnMark anything in the allocation stack as live.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001581 UnMarkAllocStack(alloc_space_->GetMarkBitmap(), large_object_space_->GetMarkObjects(),
1582 allocation_stack_.get());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001583 timings.AddSplit("UnMarkAllocStack");
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001584#ifndef NDEBUG
1585 if (gc_type == kGcTypeSticky) {
1586 // Make sure everything in the live stack isn't something we unmarked.
1587 std::sort(allocation_stack_->Begin(), allocation_stack_->End());
1588 for (Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
1589 if (std::binary_search(allocation_stack_->Begin(), allocation_stack_->End(), *it)) {
1590 LOG(FATAL) << "Unmarked object " << *it << " in the live stack";
1591 }
1592 }
1593 } else {
1594 for (Object** it = allocation_stack_->Begin(); it != allocation_stack_->End(); ++it) {
1595 if (GetLiveBitmap()->Test(*it)) {
1596 LOG(FATAL) << "Object " << *it << " is marked as live";
1597 }
1598 }
1599 }
1600#endif
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001601 }
1602
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001603 if (kIsDebugBuild) {
1604 // Verify that we only reach marked objects from the image space.
Ian Rogers81d425b2012-09-27 16:03:43 -07001605 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001606 mark_sweep.VerifyImageRoots();
1607 timings.AddSplit("VerifyImageRoots");
1608 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001609
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001610 if (verify_post_gc_heap_) {
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001611 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1612 SwapBitmaps(gc_type);
1613 if (!VerifyHeapReferences()) {
1614 LOG(FATAL) << "Post " << gc_type_str.str() << "Gc verification failed";
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001615 }
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001616 SwapBitmaps(gc_type);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001617 timings.AddSplit("VerifyHeapReferencesPostGC");
1618 }
1619
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001620 thread_list->ResumeAll();
1621 dirty_end = NanoTime();
Ian Rogers81d425b2012-09-27 16:03:43 -07001622 Locks::mutator_lock_->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001623
1624 {
1625 // TODO: this lock shouldn't be necessary (it's why we did the bitmap flip above).
Mathieu Chartier0325e622012-09-05 14:22:51 -07001626 if (gc_type != kGcTypeSticky) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001627 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001628 mark_sweep.Sweep(gc_type == kGcTypePartial, false);
1629 timings.AddSplit("Sweep");
1630 mark_sweep.SweepLargeObjects(false);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001631 timings.AddSplit("SweepLargeObjects");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001632 } else {
Ian Rogers50b35e22012-10-04 10:09:15 -07001633 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001634 mark_sweep.SweepArray(timings, live_stack_.get(), false);
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001635 timings.AddSplit("SweepArray");
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001636 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001637 live_stack_->Reset();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001638 }
1639
1640 {
1641 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1642 // Unbind the live and mark bitmaps.
1643 mark_sweep.UnBindBitmaps();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001644
Ian Rogersf0bbeab2012-10-10 18:26:27 -07001645 // Swap the live and mark bitmaps for each space which we modified space. This is an
1646 // optimization that enables us to not clear live bits inside of the sweep.
1647 const bool swap = true;
1648 if (swap) {
1649 if (gc_type == kGcTypeSticky) {
1650 SwapLargeObjects();
1651 } else {
1652 SwapBitmaps(gc_type);
1653 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001654 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001655 }
1656
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001657 if (verify_system_weaks_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001658 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001659 mark_sweep.VerifySystemWeaks();
1660 timings.AddSplit("VerifySystemWeaks");
1661 }
1662
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001663 cleared_references = mark_sweep.GetClearedReferences();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001664 bytes_freed = mark_sweep.GetFreedBytes();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001665 }
1666
1667 GrowForUtilization();
1668 timings.AddSplit("GrowForUtilization");
1669
1670 EnqueueClearedReferences(&cleared_references);
1671 RequestHeapTrim();
1672 timings.AddSplit("Finish");
1673
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001674 // If the GC was slow, then print timings in the log.
1675 uint64_t pause_roots = (root_end - root_begin) / 1000 * 1000;
1676 uint64_t pause_dirty = (dirty_end - dirty_begin) / 1000 * 1000;
Mathieu Chartier637e3482012-08-17 10:41:32 -07001677 uint64_t duration = (NanoTime() - root_begin) / 1000 * 1000;
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001678 if (pause_roots > MsToNs(5) || pause_dirty > MsToNs(5)) {
Mathieu Chartier637e3482012-08-17 10:41:32 -07001679 const size_t percent_free = GetPercentFree();
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001680 const size_t current_heap_size = GetUsedMemorySize();
Mathieu Chartier637e3482012-08-17 10:41:32 -07001681 const size_t total_memory = GetTotalMemory();
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001682 LOG(INFO) << gc_cause << " " << gc_type_str.str()
Mathieu Chartier637e3482012-08-17 10:41:32 -07001683 << "Concurrent GC freed " << PrettySize(bytes_freed) << ", " << percent_free
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -07001684 << "% free, " << PrettySize(current_heap_size) << "/"
Mathieu Chartier637e3482012-08-17 10:41:32 -07001685 << PrettySize(total_memory) << ", " << "paused " << PrettyDuration(pause_roots)
1686 << "+" << PrettyDuration(pause_dirty) << " total " << PrettyDuration(duration);
Mathieu Chartier0325e622012-09-05 14:22:51 -07001687 if (VLOG_IS_ON(heap)) {
1688 timings.Dump();
1689 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001690 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001691
Mathieu Chartier0325e622012-09-05 14:22:51 -07001692 CumulativeLogger* logger = cumulative_timings_.Get(gc_type);
1693 logger->Start();
1694 logger->AddLogger(timings);
1695 logger->End(); // Next iteration.
Carl Shapiro69759ea2011-07-21 18:13:35 -07001696}
1697
Ian Rogers81d425b2012-09-27 16:03:43 -07001698GcType Heap::WaitForConcurrentGcToComplete(Thread* self) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001699 GcType last_gc_type = kGcTypeNone;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001700 if (concurrent_gc_) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001701 bool do_wait;
1702 uint64_t wait_start = NanoTime();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001703 {
1704 // Check if GC is running holding gc_complete_lock_.
Ian Rogers81d425b2012-09-27 16:03:43 -07001705 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001706 do_wait = is_gc_running_;
Mathieu Chartiera6399032012-06-11 18:49:50 -07001707 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001708 if (do_wait) {
1709 // We must wait, change thread state then sleep on gc_complete_cond_;
1710 ScopedThreadStateChange tsc(Thread::Current(), kWaitingForGcToComplete);
1711 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001712 MutexLock mu(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001713 while (is_gc_running_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001714 gc_complete_cond_->Wait(self, *gc_complete_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001715 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001716 last_gc_type = last_gc_type_;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001717 }
1718 uint64_t wait_time = NanoTime() - wait_start;
1719 if (wait_time > MsToNs(5)) {
1720 LOG(INFO) << "WaitForConcurrentGcToComplete blocked for " << PrettyDuration(wait_time);
1721 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001722 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001723 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001724 return last_gc_type;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001725}
1726
Elliott Hughesc967f782012-04-16 10:23:15 -07001727void Heap::DumpForSigQuit(std::ostream& os) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001728 os << "Heap: " << GetPercentFree() << "% free, " << PrettySize(GetUsedMemorySize()) << "/"
1729 << PrettySize(GetTotalMemory()) << "; " << GetObjectsAllocated() << " objects\n";
Mathieu Chartier0325e622012-09-05 14:22:51 -07001730 // Dump cumulative timings.
1731 LOG(INFO) << "Dumping cumulative Gc timings";
1732 for (CumulativeTimings::iterator it = cumulative_timings_.begin();
1733 it != cumulative_timings_.end(); ++it) {
1734 it->second->Dump();
1735 }
Elliott Hughesc967f782012-04-16 10:23:15 -07001736}
1737
1738size_t Heap::GetPercentFree() {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001739 return static_cast<size_t>(100.0f * static_cast<float>(GetFreeMemory()) / GetTotalMemory());
Elliott Hughesc967f782012-04-16 10:23:15 -07001740}
1741
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001742void Heap::SetIdealFootprint(size_t max_allowed_footprint) {
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001743 AllocSpace* alloc_space = alloc_space_;
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001744 if (max_allowed_footprint > GetMaxMemory()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001745 VLOG(gc) << "Clamp target GC heap from " << PrettySize(max_allowed_footprint) << " to "
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001746 << PrettySize(GetMaxMemory());
1747 max_allowed_footprint = GetMaxMemory();
1748 }
1749 // We want to update the footprint for just the alloc space.
1750 max_allowed_footprint -= large_object_space_->GetNumBytesAllocated();
1751 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1752 if ((*it)->IsAllocSpace()) {
1753 AllocSpace* alloc_space = (*it)->AsAllocSpace();
1754 if (alloc_space != alloc_space_) {
1755 max_allowed_footprint -= alloc_space->GetNumBytesAllocated();
1756 }
1757 }
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001758 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001759 alloc_space->SetFootprintLimit(max_allowed_footprint);
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001760}
1761
Ian Rogers3bb17a62012-01-27 23:56:44 -08001762// kHeapIdealFree is the ideal maximum free size, when we grow the heap for utilization.
Shih-wei Liao7f1caab2011-10-06 12:11:04 -07001763static const size_t kHeapIdealFree = 2 * MB;
Ian Rogers3bb17a62012-01-27 23:56:44 -08001764// kHeapMinFree guarantees that you always have at least 512 KB free, when you grow for utilization,
1765// regardless of target utilization ratio.
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001766static const size_t kHeapMinFree = kHeapIdealFree / 4;
1767
Carl Shapiro69759ea2011-07-21 18:13:35 -07001768void Heap::GrowForUtilization() {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001769 // We know what our utilization is at this moment.
1770 // This doesn't actually resize any memory. It just lets the heap grow more when necessary.
1771 size_t target_size = num_bytes_allocated_ / Heap::GetTargetHeapUtilization();
1772 if (target_size > num_bytes_allocated_ + kHeapIdealFree) {
1773 target_size = num_bytes_allocated_ + kHeapIdealFree;
1774 } else if (target_size < num_bytes_allocated_ + kHeapMinFree) {
1775 target_size = num_bytes_allocated_ + kHeapMinFree;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001776 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001777
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001778 // Calculate when to perform the next ConcurrentGC.
1779 if (GetFreeMemory() < concurrent_min_free_) {
1780 // Not enough free memory to perform concurrent GC.
1781 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
1782 } else {
1783 // Start a concurrent Gc when we get close to the target size.
1784 concurrent_start_bytes_ = target_size - concurrent_start_size_;
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001785 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001786
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07001787 SetIdealFootprint(target_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001788}
1789
jeffhaoc1160702011-10-27 15:48:45 -07001790void Heap::ClearGrowthLimit() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001791 WaitForConcurrentGcToComplete(Thread::Current());
jeffhaoc1160702011-10-27 15:48:45 -07001792 alloc_space_->ClearGrowthLimit();
1793}
1794
Elliott Hughesadb460d2011-10-05 17:02:34 -07001795void Heap::SetReferenceOffsets(MemberOffset reference_referent_offset,
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001796 MemberOffset reference_queue_offset,
1797 MemberOffset reference_queueNext_offset,
1798 MemberOffset reference_pendingNext_offset,
1799 MemberOffset finalizer_reference_zombie_offset) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07001800 reference_referent_offset_ = reference_referent_offset;
1801 reference_queue_offset_ = reference_queue_offset;
1802 reference_queueNext_offset_ = reference_queueNext_offset;
1803 reference_pendingNext_offset_ = reference_pendingNext_offset;
1804 finalizer_reference_zombie_offset_ = finalizer_reference_zombie_offset;
1805 CHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1806 CHECK_NE(reference_queue_offset_.Uint32Value(), 0U);
1807 CHECK_NE(reference_queueNext_offset_.Uint32Value(), 0U);
1808 CHECK_NE(reference_pendingNext_offset_.Uint32Value(), 0U);
1809 CHECK_NE(finalizer_reference_zombie_offset_.Uint32Value(), 0U);
1810}
1811
1812Object* Heap::GetReferenceReferent(Object* reference) {
1813 DCHECK(reference != NULL);
1814 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1815 return reference->GetFieldObject<Object*>(reference_referent_offset_, true);
1816}
1817
1818void Heap::ClearReferenceReferent(Object* reference) {
1819 DCHECK(reference != NULL);
1820 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
1821 reference->SetFieldObject(reference_referent_offset_, NULL, true);
1822}
1823
1824// Returns true if the reference object has not yet been enqueued.
1825bool Heap::IsEnqueuable(const Object* ref) {
1826 DCHECK(ref != NULL);
1827 const Object* queue = ref->GetFieldObject<Object*>(reference_queue_offset_, false);
1828 const Object* queue_next = ref->GetFieldObject<Object*>(reference_queueNext_offset_, false);
1829 return (queue != NULL) && (queue_next == NULL);
1830}
1831
1832void Heap::EnqueueReference(Object* ref, Object** cleared_reference_list) {
1833 DCHECK(ref != NULL);
1834 CHECK(ref->GetFieldObject<Object*>(reference_queue_offset_, false) != NULL);
1835 CHECK(ref->GetFieldObject<Object*>(reference_queueNext_offset_, false) == NULL);
1836 EnqueuePendingReference(ref, cleared_reference_list);
1837}
1838
1839void Heap::EnqueuePendingReference(Object* ref, Object** list) {
1840 DCHECK(ref != NULL);
1841 DCHECK(list != NULL);
1842
1843 if (*list == NULL) {
1844 ref->SetFieldObject(reference_pendingNext_offset_, ref, false);
1845 *list = ref;
1846 } else {
1847 Object* head = (*list)->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
1848 ref->SetFieldObject(reference_pendingNext_offset_, head, false);
1849 (*list)->SetFieldObject(reference_pendingNext_offset_, ref, false);
1850 }
1851}
1852
1853Object* Heap::DequeuePendingReference(Object** list) {
1854 DCHECK(list != NULL);
1855 DCHECK(*list != NULL);
1856 Object* head = (*list)->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
1857 Object* ref;
1858 if (*list == head) {
1859 ref = *list;
1860 *list = NULL;
1861 } else {
1862 Object* next = head->GetFieldObject<Object*>(reference_pendingNext_offset_, false);
1863 (*list)->SetFieldObject(reference_pendingNext_offset_, next, false);
1864 ref = head;
1865 }
1866 ref->SetFieldObject(reference_pendingNext_offset_, NULL, false);
1867 return ref;
1868}
1869
Ian Rogers5d4bdc22011-11-02 22:15:43 -07001870void Heap::AddFinalizerReference(Thread* self, Object* object) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001871 ScopedObjectAccess soa(self);
Elliott Hughes77405792012-03-15 15:22:12 -07001872 JValue args[1];
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07001873 args[0].SetL(object);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001874 soa.DecodeMethod(WellKnownClasses::java_lang_ref_FinalizerReference_add)->Invoke(self, NULL, args,
1875 NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001876}
1877
1878size_t Heap::GetBytesAllocated() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001879 return num_bytes_allocated_;
1880}
1881
1882size_t Heap::GetObjectsAllocated() const {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001883 size_t total = 0;
1884 // TODO: C++0x
1885 for (Spaces::const_iterator it = spaces_.begin(); it != spaces_.end(); ++it) {
1886 Space* space = *it;
1887 if (space->IsAllocSpace()) {
1888 total += space->AsAllocSpace()->GetNumObjectsAllocated();
1889 }
1890 }
1891 return total;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001892}
1893
1894size_t Heap::GetConcurrentStartSize() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001895 return concurrent_start_size_;
1896}
1897
1898size_t Heap::GetConcurrentMinFree() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001899 return concurrent_min_free_;
Elliott Hughesadb460d2011-10-05 17:02:34 -07001900}
1901
1902void Heap::EnqueueClearedReferences(Object** cleared) {
1903 DCHECK(cleared != NULL);
1904 if (*cleared != NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001905 ScopedObjectAccess soa(Thread::Current());
Elliott Hughes77405792012-03-15 15:22:12 -07001906 JValue args[1];
Elliott Hughesf24d3ce2012-04-11 17:43:37 -07001907 args[0].SetL(*cleared);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001908 soa.DecodeMethod(WellKnownClasses::java_lang_ref_ReferenceQueue_add)->Invoke(soa.Self(), NULL,
1909 args, NULL);
Elliott Hughesadb460d2011-10-05 17:02:34 -07001910 *cleared = NULL;
1911 }
1912}
1913
Ian Rogers1f539342012-10-03 21:09:42 -07001914void Heap::RequestConcurrentGC(Thread* self) {
Mathieu Chartier069387a2012-06-18 12:01:01 -07001915 // Make sure that we can do a concurrent GC.
Ian Rogers120f1c72012-09-28 17:17:10 -07001916 Runtime* runtime = Runtime::Current();
1917 if (requesting_gc_ || runtime == NULL || !runtime->IsFinishedStarting() ||
1918 !runtime->IsConcurrentGcEnabled()) {
1919 return;
1920 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001921 {
1922 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1923 if (runtime->IsShuttingDown()) {
1924 return;
1925 }
1926 }
1927 if (self->IsHandlingStackOverflow()) {
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001928 return;
1929 }
1930
1931 requesting_gc_ = true;
Ian Rogers120f1c72012-09-28 17:17:10 -07001932 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07001933 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
1934 DCHECK(WellKnownClasses::java_lang_Daemons_requestGC != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001935 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
1936 WellKnownClasses::java_lang_Daemons_requestGC);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001937 CHECK(!env->ExceptionCheck());
1938 requesting_gc_ = false;
1939}
1940
Ian Rogers81d425b2012-09-27 16:03:43 -07001941void Heap::ConcurrentGC(Thread* self) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001942 {
1943 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1944 if (Runtime::Current()->IsShuttingDown() || !concurrent_gc_) {
1945 return;
1946 }
Mathieu Chartier2542d662012-06-21 17:14:11 -07001947 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001948
Ian Rogers81d425b2012-09-27 16:03:43 -07001949 if (WaitForConcurrentGcToComplete(self) == kGcTypeNone) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001950 // Start a concurrent GC as one wasn't in progress
Ian Rogers81d425b2012-09-27 16:03:43 -07001951 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001952 if (alloc_space_->Size() > min_alloc_space_size_for_sticky_gc_) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001953 CollectGarbageInternal(kGcTypeSticky, kGcCauseBackground, false);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001954 } else {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001955 CollectGarbageInternal(kGcTypePartial, kGcCauseBackground, false);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001956 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001957 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001958}
1959
Ian Rogers81d425b2012-09-27 16:03:43 -07001960void Heap::Trim(Thread* self) {
1961 WaitForConcurrentGcToComplete(self);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001962 alloc_space_->Trim();
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001963}
1964
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001965void Heap::RequestHeapTrim() {
1966 // We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
1967 // because that only marks object heads, so a large array looks like lots of empty space. We
1968 // don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
1969 // to utilization (which is probably inversely proportional to how much benefit we can expect).
1970 // We could try mincore(2) but that's only a measure of how many pages we haven't given away,
1971 // not how much use we're making of those pages.
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001972 uint64_t ms_time = NsToMs(NanoTime());
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001973 float utilization =
1974 static_cast<float>(alloc_space_->GetNumBytesAllocated()) / alloc_space_->Size();
1975 if ((utilization > 0.75f) || ((ms_time - last_trim_time_) < 2 * 1000)) {
1976 // Don't bother trimming the alloc space if it's more than 75% utilized, or if a
1977 // heap trim occurred in the last two seconds.
1978 return;
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001979 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001980
1981 Thread* self = Thread::Current();
1982 {
1983 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
1984 Runtime* runtime = Runtime::Current();
1985 if (runtime == NULL || !runtime->IsFinishedStarting() || runtime->IsShuttingDown()) {
1986 // Heap trimming isn't supported without a Java runtime or Daemons (such as at dex2oat time)
1987 // Also: we do not wish to start a heap trim if the runtime is shutting down (a racy check
1988 // as we don't hold the lock while requesting the trim).
1989 return;
1990 }
Ian Rogerse1d490c2012-02-03 09:09:07 -08001991 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07001992 last_trim_time_ = ms_time;
Ian Rogers120f1c72012-09-28 17:17:10 -07001993 JNIEnv* env = self->GetJniEnv();
Mathieu Chartiera6399032012-06-11 18:49:50 -07001994 DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
1995 DCHECK(WellKnownClasses::java_lang_Daemons_requestHeapTrim != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001996 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
1997 WellKnownClasses::java_lang_Daemons_requestHeapTrim);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08001998 CHECK(!env->ExceptionCheck());
1999}
2000
Carl Shapiro69759ea2011-07-21 18:13:35 -07002001} // namespace art